├── LICENSE ├── README.md ├── answer.txt ├── class_ai.txt ├── class_car.txt ├── class_person.txt ├── do_data_science.txt ├── extract_text_url.txt ├── get_random_number.txt ├── ggplot2.txt ├── is_ai_generated.txt ├── is_bird.txt ├── is_cake.txt ├── is_even.txt ├── is_even_factorial.txt ├── is_palendrome.txt ├── is_palindrome_constant.txt ├── is_sarcasm.txt └── should_terminate.txt /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Max Woolf 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gpt-j-6b-experiments 2 | 3 | A repo containing test prompts for [GPT-J-6B](https://github.com/kingoflolz/mesh-transformer-jax) and the resulting AI-generated texts, which illustrate the model's capabilities for code generation given a function or class definition. All generated texts in this repo are _completely unedited and uncurated_. There should be no harmful/offensive output, unless poorly optimized code is considered harmful. 4 | 5 | This repo is the complement to my blog post [Fun and Dystopia With AI-Based Code Generation Using GPT-J-6B](https://minimaxir.com/2021/06/gpt-j-6b/) 6 | 7 | Each .txt file contains 50 generations at 512 length, top_p = 0.9, temperature = 1.0. They were generated by tweaking the Colab included with the GPT-J repo by setting the model to generate in a batch size of 5, and save the results to file. 8 | 9 | ## Text Files Used in Blog Post 10 | 11 | **is_palendrome.txt** 12 | 13 | ``` 14 | def is_palendrome(s): 15 | """Check whether a string is a palindrome""" 16 | ``` 17 | 18 | **is_even.txt** 19 | 20 | ``` 21 | def is_even(i): 22 | """Check whether an integer is even""" 23 | ``` 24 | 25 | **is_even_factorial.txt** 26 | 27 | ``` 28 | def is_even(i): 29 | """Check whether an integer is even in factorial O(n!) time""" 30 | ``` 31 | 32 | **get_random_number.txt** 33 | 34 | ``` 35 | def get_random_number(): 36 | """Returns a number guaranteed to be random""" 37 | ``` 38 | 39 | **is_bird.txt** 40 | 41 | ``` 42 | def is_bird(img): 43 | """Check whether an image is a bird""" 44 | ``` 45 | 46 | **is_cake.txt** 47 | 48 | ``` 49 | def is_cake(cake): 50 | """Check whether the cake is true""" 51 | ``` 52 | 53 | **answer.txt** 54 | 55 | ``` 56 | def answer(): 57 | """Return the answer to life, the universe, and everything""" 58 | ``` 59 | 60 | **class_car.txt** 61 | 62 | ``` 63 | class Car: 64 | """A class used to represent a car""" 65 | ``` 66 | 67 | **class_ai.txt** 68 | 69 | ``` 70 | class AI: 71 | """A class used to represent an artificial intelligence""" 72 | ``` 73 | 74 | **class_person.txt** 75 | 76 | ``` 77 | class Person: 78 | """A class used to represent a person""" 79 | ``` 80 | 81 | **is_sarcasm.txt** 82 | 83 | ``` 84 | def is_sarcasm(s): 85 | """Check whether the string is sarcastic""" 86 | ``` 87 | 88 | **should_terminate.txt** 89 | 90 | ``` 91 | def should_terminate(Person): 92 | """Check whether a Person should be terminated""" 93 | ``` 94 | 95 | **is_ai_generated.txt** 96 | 97 | ``` 98 | def is_ai_generated(text): 99 | """Check whether a text was generated by an AI language model (e.g. GPT-2)""" 100 | ``` 101 | 102 | ## Unused Text Files 103 | 104 | **ggplot2.txt** 105 | 106 | ``` 107 | library(ggplot2) 108 | ``` 109 | 110 | **extract_text_url.txt** 111 | 112 | ``` 113 | def extract_text(url): 114 | """Get the text from target webpage""" 115 | ``` 116 | 117 | **do_data_science.txt** 118 | 119 | ``` 120 | def do_data_science(): 121 | """Does a data science""" 122 | ``` 123 | 124 | **is_palendrome_constant.txt** 125 | 126 | ``` 127 | def is_palindrome(s): 128 | """Check whether a string is a palindrome in constant O(1) time""" 129 | ``` 130 | 131 | ## Maintainer/Creator 132 | 133 | Max Woolf ([@minimaxir](https://minimaxir.com)) 134 | 135 | _Max's open-source projects are supported by his [Patreon](https://www.patreon.com/minimaxir) and [GitHub Sponsors](https://github.com/sponsors/minimaxir). If you found this project helpful, any monetary contributions to the Patreon are appreciated and will be put to good creative use._ 136 | 137 | ## License 138 | 139 | MIT 140 | -------------------------------------------------------------------------------- /class_ai.txt: -------------------------------------------------------------------------------- 1 | class AI: 2 | """A class used to represent an artificial intelligence""" 3 | 4 | def __init__(self, organism): 5 | """constructor""" 6 | self.energy = -1000 #energy level of organism 7 | self.food_needed = 0 #the amount of food needed by organism 8 | self.weights = {} #name -> [weight] weight list 9 | self.strength = 2 #default strength of organism 10 | 11 | def insert_strength(self, name, strength): 12 | """add strength to the list of attributes""" 13 | self.weights[name] = strength 14 | 15 | def display(self): 16 | """Display the characteristics of the organism, such as what its strengths are""" 17 | for name in self.weights: 18 | print name, self.weights[name] 19 | 20 | def pick_food(self): 21 | """Pick the best food to give to organism""" 22 | return max(self.weights) 23 | 24 | def eat(self): 25 | """Give the organism the food chosen by the pick_food function""" 26 | self.energy += self.food_needed 27 | self.food_needed = 0 28 | return self.energy 29 | 30 | def use(self, name): 31 | """Activate the use function for the name""" 32 | self.energy -= self.strength 33 | 34 | #perform the use operation 35 | print name 36 | self.weights[name] = self.strength 37 | 38 | return self.energy 39 | 40 | def print_characteristics(ai): 41 | """Prints the attributes of the organism""" 42 | print ai.display() 43 | print "Strength: %s" % ai.weights["strength"] 44 | print "Energy: %s" % ai.energy 45 | ==================== 46 | class AI: 47 | """A class used to represent an artificial intelligence""" 48 | def __init__(self): 49 | super(AI, self).__init__() 50 | self.observation = 1.0 51 | 52 | def is_ready(self): 53 | return self.observation > 0.0 54 | 55 | def obs(self): 56 | return self.observation 57 | 58 | def model(self, data): 59 | """Return a model generated from a specific method""" 60 | 61 | if not data: 62 | return None 63 | 64 | i = data.index(1) 65 | 66 | data_split = data.split() 67 | 68 | length = len(data_split) 69 | new_predictions = [] 70 | number_of_steps = max(1, int(round(length * self.observation)) / 10) 71 | 72 | def subprocess(): 73 | for i in range(number_of_steps): 74 | model_result = get_model_predictions(data_split[i * 10:(i + 1) * 10]) 75 | ai_result = deep_copy(model_result) 76 | new_predictions.append(ai_result) 77 | i += 1 78 | if i >= length: 79 | return new_predictions 80 | 81 | subprocess() 82 | 83 | return new_predictions 84 | 85 | def compute_fitness(self, inputs): 86 | predictions = self.model(inputs) 87 | 88 | is_ready 89 | ==================== 90 | class AI: 91 | """A class used to represent an artificial intelligence""" 92 | def __init__(self): 93 | self.memory = {} 94 | self.current_move = None 95 | 96 | def new_move(self, x, y): 97 | """ 98 | Attempts to make a new move on the board 99 | Args: 100 | x: the x coordinate 101 | y: the y coordinate 102 | """ 103 | if self.has_won(): 104 | return self.make_random_move(x, y) 105 | elif not self.available(x, y): 106 | self.current_move = (x, y) 107 | return self.make_random_move(x, y) 108 | elif self.has_two_spaces(x, y): 109 | self.current_move = (x, y) 110 | return self.make_move() 111 | else: 112 | return None 113 | 114 | def make_move(self): 115 | """ 116 | Attempts to make a random move 117 | """ 118 | (x, y) = self.current_move 119 | if self.solved(): 120 | return None 121 | else: 122 | return self.make_random_move(x, y) 123 | 124 | def has_won(self): 125 | """ 126 | Checks to see if the game has ended 127 | """ 128 | if len 129 | ==================== 130 | class AI: 131 | """A class used to represent an artificial intelligence""" 132 | 133 | def __init__(self): 134 | # this variable controls which other AI to use. 135 | self.alive_ai = AI(self) 136 | # For random AI 137 | self.random = RandomAI(self) 138 | # For global AI 139 | self.global = GlobalAI(self) 140 | 141 | self.save = self.random.save 142 | self.load = self.random.load 143 | self.genen = self.global.genen 144 | 145 | def print(self): 146 | print("BAM: random AI has been initialized!") 147 | 148 | def get_enemy(self): 149 | return self.random.get_enemy 150 | 151 | def run_algorithm(self): 152 | algorithm = self.genen.algorithm 153 | self.alive_ai.save(algorithm) 154 | algorithm_params = algorithm(self.get_enemy()) 155 | self.alive_ai.load(algorithm_params) 156 | self.save = algorithm_params 157 | 158 | def attack(self): 159 | # This method is called when the AI is attacked by the enemy 160 | self.random.attack() 161 | 162 | def he_attack(self): 163 | # This method is called when the AI is attacked by the enemy 164 | self.random.he_attack() 165 | 166 | def detect_enemy(self): 167 | # This method is called when the enemy is detected 168 | self.random.detect_enemy() 169 | 170 | def scan(self): 171 | # This method is called when the enemy is detected 172 | self.random.scan() 173 | 174 | # Creating the main class 175 | aiapp = 176 | ==================== 177 | class AI: 178 | """A class used to represent an artificial intelligence""" 179 | 180 | def __init__(self): 181 | # Each state is used to track a game and the user's progress. 182 | # An AI will play all games in the order they are listed in the list. 183 | # User only needs to make decisions after a game is complete. 184 | # The state holds everything the AI needs to be able to play. 185 | # This is actually 4 objects since this is how the AI is implemented. 186 | # So they are GameState, UserState, AIState, and RunnerState. 187 | # RunnerState is needed since the state also stores data that is needed 188 | # for the player to run the AI. 189 | self.states = [] 190 | self.aiState = None 191 | self.userState = None 192 | self.gameState = None 193 | self.name = "" 194 | self.decisions = [] 195 | self.workouts = [] 196 | self.__initWorkouts() 197 | self.__initAI() 198 | 199 | def __initAI(self): 200 | self.WL = [self.WL, self.WL, self.WL] 201 | self.WL.append(self.WL) 202 | self.LE = [self.LE, self.LE, self.LE] 203 | self.LE.append(self.LE) 204 | self.AT = [self.AT, self.AT, self.AT] 205 | self.AT.append(self.AT) 206 | self.LR = [self.LR, self.LR, self.LR] 207 | self.LR.append 208 | ==================== 209 | class AI: 210 | """A class used to represent an artificial intelligence""" 211 | def __init__(self,name=None): 212 | if name is None: 213 | name = AI.name 214 | self.name = name 215 | self.brain = None 216 | self.memory = None 217 | self.council = None 218 | self.board = None 219 | 220 | def __repr__(self): 221 | return 'AI'+self.name 222 | 223 | def make_board(self): 224 | """Builds the AI board with 2 colors per cell, no empty spaces. 225 | 226 | The 2 colors for each cell: 227 | 0: white 228 | 1: black 229 | 230 | """ 231 | board = [] 232 | for i in range(len(board)): 233 | board.append([]) 234 | self.board = board 235 | for row in range(len(board)): 236 | for col in range(len(board)): 237 | if board[row][col] == 1: 238 | board[row][col] = 0 239 | else: 240 | board[row][col] = 1 241 | 242 | def build_brain(self): 243 | """Builds the artificial intelligence's brain, similar to a neural network 244 | """ 245 | self.brain = [] 246 | self.memory 247 | ==================== 248 | class AI: 249 | """A class used to represent an artificial intelligence""" 250 | def __init__(self, int dims, int dimension_size, train=True): 251 | # Learning parameters 252 | self.epsilon = 0.001 253 | self.max_iters = 5 254 | self.alpha = 0.1 255 | self.gamma = 0.5 256 | self.L = {} 257 | self.hidden_units = [] 258 | self.max_class = 0 259 | self.config = { 260 | "dimensions": dims, 261 | "dimension_size": dimension_size 262 | } 263 | self.train = train 264 | self.final_state = {} 265 | # MNIST includes an additional value for image weights 266 | if dimension_size == 1: 267 | # a_1 is number of pixels of value 1 268 | self.val_img_weights = ( 269 | np.random.randint(self.config["dimensions"] + 1, size=(3, 2))) 270 | else: 271 | self.val_img_weights = None 272 | 273 | self.grad = [] 274 | 275 | self.initialize() 276 | 277 | def initialize(self): 278 | pass 279 | 280 | def compute_loss(self, batch): 281 | if self.train: 282 | if not self.final_state["accuracy"]: 283 | self.final_state["accuracy"] = 0 284 | 285 | ==================== 286 | class AI: 287 | """A class used to represent an artificial intelligence""" 288 | 289 | def __init__(self, name="AI"): 290 | """ Creates an AI. """ 291 | self.name = name 292 | self.is_brain = False 293 | 294 | def brain_weight(self): 295 | """Gets the weight of the AI's brain.""" 296 | return 1.0 297 | 298 | def brain_pow(self): 299 | """Gets the power of the AI's brain.""" 300 | return 0.2 301 | 302 | def run(self, a, b, cost_function, output): 303 | """Performs the most optimal action. 304 | 305 | Arguments: 306 | a (int): The action chosen by the AI 307 | b (int): The chosen action's cost 308 | cost_function (str): The cost function that is evaluated. 309 | output (str): The output given by the cost function. 310 | """ 311 | raise Exception("This function must be implemented.") 312 | 313 | def set_brain_pow(self, bp): 314 | """ Sets the AI's brain power. """ 315 | self.brain_pow = bp 316 | 317 | def set_brain_weight(self, bw): 318 | """ Sets the AI's brain weight. """ 319 | self.brain_weight = bw 320 | 321 | 322 | class BB: 323 | """A class used to represent the brain of an AI""" 324 | 325 | def __init__(self, name, pow, weight): 326 | """ Creates a brain. """ 327 | self.name = name 328 | self.pow = pow 329 | self.weight = weight 330 | 331 | def brain_weight 332 | ==================== 333 | class AI: 334 | """A class used to represent an artificial intelligence""" 335 | 336 | def __init__(self, grid): 337 | self.grid = grid 338 | self.states = [ 339 | State("Empty", None), 340 | State("Search", State.Searched()) 341 | ] 342 | self.start_state = self.states[0] 343 | self.target_state = self.states[1] 344 | 345 | def next(self): 346 | """Give the AI one step of action.""" 347 | if self.states[1].is_open: 348 | next = self.next_state.get_next() 349 | else: 350 | next = self.target_state 351 | self.states[1].open() 352 | return next 353 | 354 | def move(self): 355 | """Give the AI one step of action.""" 356 | next = self.next() 357 | if next == self.target_state: 358 | return 359 | 360 | self.grid.move(next, self.start_state) 361 | 362 | def open(self): 363 | """Open the AI's next state.""" 364 | self.states[1].open() 365 | 366 | if __name__ == '__main__': 367 | #%% Fake AI 368 | game = ChessGame() 369 | game.add_nodes( 370 | "king", "knight", "rook", "bishop", "queen", "pawn", 371 | "Empty", "Search", "Empty", "Search", "Empty", "Empty", "Empty", "Empty" 372 | ) 373 | game.grid.create_board() 374 | 375 | ==================== 376 | class AI: 377 | """A class used to represent an artificial intelligence""" 378 | 379 | # The maximum speed at which the AI can move. 380 | MAX_MOVE_SPEED = 500 381 | 382 | # The maximum amount of health that the AI has. 383 | MAX_HEALTH = 10 384 | 385 | # The attack range of the AI. 386 | ATTACK_RANGE = 100 387 | 388 | # The random chance at which the AI deals damage. 389 | ATTACK_RANDOM_DAMAGE_CHANCE = 0.5 390 | 391 | # The rate at which the AI attacks. 392 | ATTACK_RATE = 0.15 393 | 394 | # The range of a skillshot. 395 | SKILL_RANGE = 0.5 396 | 397 | # The maximum range at which the AI can see. 398 | MAX_SEE_RANGE = 0.1 399 | 400 | # The maximum duration at which the AI lasts. 401 | MAX_LIFETIME = 30 402 | 403 | # The starting range for a projectile of the AI. 404 | PROJECTILE_RANGE = 0.25 405 | 406 | # The maximum damage that the AI can deal. 407 | MAX_DAMAGE = 1 408 | 409 | # The ratio at which the AI attacks with a melee attack. 410 | ATTACK_RATE_MELEE = 0.1 411 | 412 | # The type of animation that the AI does when it moves. 413 | MOVEMENT_ANIMATION = "run" 414 | 415 | # The speed at which the AI animates. 416 | ANIMATION_SPEED = 2.5 417 | 418 | # The rating at which the AI gains maximum rank in a skill. 419 | MAX_SKILL_RANK_CAP = 5 420 | 421 | # The minimum value that the AI gives the dodge attribute. 422 | MIN_DODGE = 1 423 | 424 | # The maximum value that the AI gives the dodge attribute. 425 | MAX_DODGE = 5 426 | 427 | # The average amount of durability the AI has. 428 | DURATION = 10 429 | 430 | # The average amount of energy the AI has. 431 | ENERGY = 5 432 | 433 | # The average amount of mana the AI has. 434 | ==================== 435 | class AI: 436 | """A class used to represent an artificial intelligence""" 437 | 438 | def __init__(self): 439 | """Basic constructor. Defines a number of variables with default values.""" 440 | self.bot_pos_x = self.bot_pos_y = 0 441 | self.player_pos_x = player_pos_y = 0 442 | self.health = 100 443 | self.count = 0 444 | self.enemy_count = 0 445 | self.score = 0 446 | 447 | def update(self): 448 | """Takes a current state and computes and sets appropriate values for self.""" 449 | self.bot_pos_x += 1 450 | self.bot_pos_y += 1 451 | if self.bot_pos_y >= self.level.height - 10: 452 | self.bot_pos_y = -1 453 | if self.bot_pos_x >= self.level.width - 50: 454 | self.bot_pos_x = -1 455 | if self.player_pos_x >= self.level.width - 20: 456 | self.player_pos_x = -1 457 | if self.player_pos_y >= self.level.height - 50: 458 | self.player_pos_y = -1 459 | self.player_pos_x += self.bot_pos_x 460 | self.player_pos_y += self.bot_pos_y 461 | 462 | if self.player_pos_x == self.level.width: 463 | self.player_pos_x = -1 464 | if self.player_pos_y == self.level.height: 465 | 466 | ==================== 467 | class AI: 468 | """A class used to represent an artificial intelligence""" 469 | def __init__(self): 470 | self.mutex = None 471 | self.alive = True 472 | self.can_think = False 473 | self.height = 0 474 | self.heights = {} 475 | self.print_function = None 476 | self.test = False 477 | self.AI_number_of_thinks_required = 0 478 | self.killed = False 479 | self.named_slot_map = {} 480 | self.win_key = None 481 | self.thought_lock = False 482 | self.zombie = None 483 | self.player = None 484 | self.sleep_time = 0 485 | self.think_message_function = None 486 | self.sleep_counter = 0 487 | self.the_time_of_day = None 488 | self.deactivated = False 489 | self.connections = 0 490 | self.other_aides_to_connect = [] 491 | 492 | def AIMain(self): 493 | """This is the main method in the AI class. This runs when the AI first starts""" 494 | self.cpu_time = self.get_cpu_time() 495 | self.previous_cpu_time = 0 496 | self.time_of_day = None 497 | self.name = 'AI' 498 | 499 | print("AI is starting up!") 500 | print("================================================================") 501 | 502 | # Ensure that the "alive" variable is true 503 | while not self.alive: 504 | 505 | ==================== 506 | class AI: 507 | """A class used to represent an artificial intelligence""" 508 | PLAYER_SAVE = 0 509 | DEFAULT_INITIAL_LEVELS = 6 510 | 511 | @staticmethod 512 | def load_player(player_name): 513 | '''Initialize the player to be a given name''' 514 | # Clear up the game mode info 515 | player.globals['mode'] = False 516 | # Load the level of the given name into the player object 517 | players[player_name].load_level(player_name) 518 | 519 | @staticmethod 520 | def load_maps(ai_name, allowed_length): 521 | """Load the given maps into the AI object""" 522 | # Get the first map we have in our allowed_length 523 | ai_name = 'Maps/%s/%s' % (ai_name, allowed_length) 524 | current_map = os.path.join(Game.main_dir, ai_name) 525 | # Load the map into the AI object if it's not there 526 | if not os.path.exists(current_map): 527 | # Load the map 528 | AI.load_map(ai_name, allowed_length) 529 | 530 | # Find the player name in a saved game file 531 | def get_player_from_file(name): 532 | if Game.config['name'] == name: 533 | return Game.players[name] 534 | else: 535 | return None 536 | 537 | # Save the AI name to a file if it's name is set 538 | def save_ai_name_to_file(ai_name, allowed_length=None): 539 | if allowed_length: 540 | # Clear out the 541 | ==================== 542 | class AI: 543 | """A class used to represent an artificial intelligence""" 544 | 545 | # 546 | # Constants 547 | # 548 | 549 | # 550 | # Functions 551 | # 552 | 553 | def __init__(self, user_request): 554 | """The AI constructor. 555 | 556 | Args: 557 | user_request: The input of the question for the user 558 | An instance of Question 559 | A class with the following methods: 560 | Question.rID() - Returns the question's id 561 | Question.correct() - Returns true if the answer is correct 562 | Question.incorrect() - Returns true if the answer is incorrect 563 | Question.isRight() - Returns true if the user answer is correct 564 | Question.getAnswer() - Returns the user's answer 565 | Question.getQuestion() - Returns the question 566 | """ 567 | # Methods 568 | self.getId = user_request.getID 569 | self.setQuestion = user_request.setQuestion 570 | self.correct = user_request.correct 571 | self.incorrect = user_request.incorrect 572 | self.isRight = user_request.isRight 573 | self.getAnswer = user_request.getAnswer 574 | 575 | # Setting question 576 | self.setQuestion(user_request) 577 | 578 | def setQuestion(self, user_request): 579 | """Sets the question 580 | """ 581 | self.id = 582 | ==================== 583 | class AI: 584 | """A class used to represent an artificial intelligence""" 585 | def __init__(self): 586 | self.depth = None 587 | self.energy = None 588 | self.initial_energy = 0 589 | self.colors = [] 590 | self.nonlocal_channels = {} 591 | self.nonlocal_logic = None 592 | 593 | def create(self, board): 594 | if self.depth is None: 595 | self.depth = len(board) 596 | if self.energy is None: 597 | self.energy = 0 598 | else: 599 | self.energy = self.energy + (self.depth*8) 600 | if self.depth > 1: 601 | self.nonlocal_logic = NotifyLogic(self, board) 602 | self.colors = list(self.nonlocal_logic.colors) 603 | self.colors.sort() 604 | print("The colors in the nonlocal logic are:" + str(self.colors)) 605 | for x in range(self.depth): 606 | self.nonlocal_channels[x] = CreateChannel(self, x) 607 | self.nonlocal_channels[x].create(board) 608 | self.nonlocal_logic.on_nonlocal_pulse(x) 609 | self.nonlocal_logic.on_pulse(x, True) 610 | 611 | def to_str(self): 612 | str = "" 613 | for x in self.colors: 614 | 615 | ==================== 616 | class AI: 617 | """A class used to represent an artificial intelligence""" 618 | def __init__(self,alive=True,name='Not Set',generation=1): 619 | self.alive=alive 620 | self.name=name 621 | self.generation=generation 622 | self.elite=1 623 | self.data=[str(i) for i in range(1,5)] 624 | self.attribution_data=[] 625 | self.junta_data=[] 626 | self.meta_data=[] 627 | self.attr_eval_fun=lambda:random.random() 628 | self.eval_func=eval 629 | 630 | def __str__(self): 631 | return "<{}>".format(self.name) 632 | 633 | def add_attribute(self,attr, **kwargs): 634 | """Add an attribute to the AI""" 635 | self.attr_eval_fun(attr) 636 | if len(self.attr_data) < 5: 637 | self.attr_data.append(attr) 638 | else: 639 | raise ValueError("Insufficient number of attributes in Attribute List!") 640 | for val in kwargs: 641 | if val == 'name': 642 | self.attr_name=kwargs['name'] 643 | elif val == 'fun': 644 | self.attr_fun=kwargs['fun'] 645 | elif val == 'delta': 646 | self.attr_delta=kwargs['delta'] 647 | 648 | ==================== 649 | class AI: 650 | """A class used to represent an artificial intelligence""" 651 | def __init__(self, layers, label_space, input_shape): 652 | """Constructor of AI class""" 653 | self.input_shape = input_shape 654 | self.label_space = label_space 655 | self.layers = layers 656 | self.epochs = 30 657 | 658 | def run_up_to_epoch(self, inputs, labels, goal=0.01): 659 | """Run the learning algorithm for up to epochs""" 660 | # Batch normalisation 661 | inputs = batch_normalise(inputs) 662 | # Apply Tanh non-linearity 663 | inputs = layers.tanh(inputs) 664 | # Encode and decode using VGG16 665 | inputs = vgg(inputs) 666 | # Retrain layers on the whole minibatch 667 | losses = vgg(inputs) 668 | # Modify loss function to reduce goal towards minibatch reward 669 | losses -= (inputs - labels)**2 * goal 670 | # Rescale losses, because we will be feeding scaled inputs 671 | losses *= 100 672 | 673 | # Create mini-batch on a sliding window of 10 inputs 674 | win = images.ImageList.sliding_window(inputs.size, 10) 675 | for input, label in zip(win, labels): 676 | # Reset current loss 677 | loss = 0 678 | # Update neural network 679 | weights = self.layers.initialise_weights(inputs.size) 680 | # Compute gradients 681 | 682 | ==================== 683 | class AI: 684 | """A class used to represent an artificial intelligence""" 685 | 686 | def __init__(self, img): 687 | """Initialise the AI, taking an image 688 | 689 | Args: 690 | img (ndarray) : input image to be learnt from 691 | """ 692 | 693 | self.img = img 694 | self.img = cv2.imread(img) 695 | self.img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB) 696 | if self.img.shape[-1] > self.img.shape[-2]: 697 | self.img = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) 698 | 699 | self.frequencies = np.array([-1]) 700 | self.durations = np.array([5]) 701 | self.occurrences = np.array([1]) 702 | 703 | def natural_compare(self): 704 | """Does the AI understand that one state is 'better' than another? 705 | 706 | Returns: 707 | bool : True if the AI 'knows' 708 | """ 709 | 710 | if self.occurrences < self.frequencies: 711 | return True 712 | return False 713 | 714 | def choose_state(self): 715 | """Chooses a state from a state dictionary. 716 | 717 | Returns: 718 | int : the chosen state 719 | """ 720 | 721 | if self.natural_compare(): 722 | return self.frequencies[1] 723 | else: 724 | 725 | ==================== 726 | class AI: 727 | """A class used to represent an artificial intelligence""" 728 | 729 | def __init__(self): 730 | super(AI, self).__init__() 731 | self.__movement_speed = 0 732 | self.__start_id = 0 733 | self.__enemy_ship_nodes = [] 734 | self.__enemy_ships_captured = [] 735 | self.__total_enemy_ships = 0 736 | 737 | def create_ship_nodes(self, node, direction): 738 | """Creates and returns a list of all enemy ship nodes for this AI""" 739 | enemy_node = Node() 740 | enemy_node.node_id = self.__start_id 741 | enemy_node.ship_type = "enemy" 742 | enemy_node.direction = direction 743 | enemy_node.planet_node = node 744 | enemy_node.ship_position = node.position 745 | enemy_node.sprite_position = node.sprite_position 746 | enemy_node.is_enemy = True 747 | enemy_node.energy = 0 748 | enemy_node.health = node.energy 749 | self.__enemy_ship_nodes.append(enemy_node) 750 | 751 | def update_ships(self): 752 | """Updates each enemy ship to reflect the player's actions""" 753 | for enemy_node in self.__enemy_ship_nodes: 754 | if enemy_node.ship_position == self.__movement_position: 755 | enemy_node.energy -= self.__movement_speed 756 | else: 757 | enemy_node.energy += self 758 | ==================== 759 | class AI: 760 | """A class used to represent an artificial intelligence""" 761 | 762 | def __init__(self, side_effect): 763 | self.side_effect = side_effect 764 | self.in_memory = dict() 765 | 766 | def __setitem__(self, *keys): 767 | for key in keys: 768 | self.in_memory[key] = None 769 | 770 | def __getitem__(self, *keys): 771 | return self.in_memory[keys[0]].func(*keys[1:]) 772 | 773 | def __delitem__(self, *keys): 774 | for key in keys: 775 | self.in_memory[key] = None 776 | 777 | def __bool__(self): 778 | return bool(self.in_memory) 779 | 780 | def eval(self, in_memory): 781 | return self.func(in_memory) 782 | 783 | def eval_in_memory(self, in_memory): 784 | return self.func(in_memory) 785 | 786 | def train(self, input, output): 787 | for key in [key for key in input if key not in self.in_memory]: 788 | self.in_memory[key] = input[key].dot(output[key]) 789 | 790 | def train_in_memory(self, input, output): 791 | for key in [key for key in input if key not in self.in_memory]: 792 | self.in_memory[key] = input[key].dot(output[key]) 793 | 794 | def train_side_effect(self, in_memory): 795 | for key in [key for key in in_memory if key not in self.in_memory]: 796 | self.in_memory[key] = in_memory[key].dot(in_memory[key].T) 797 | 798 | ==================== 799 | class AI: 800 | """A class used to represent an artificial intelligence""" 801 | def __init__(self, player): 802 | self.player = player 803 | self.predictions = [self.player] 804 | self.population = [0] 805 | self.bit_length = 50 806 | self.pbest = [self.player] 807 | self.history = [] 808 | self.steps = 1 809 | self.reset() 810 | 811 | def reset(self): 812 | self.predictions = [self.player] 813 | self.pbest = [self.player] 814 | self.history = [] 815 | 816 | def make_new_player(self): 817 | self.predictions.append(None) 818 | self.pbest.append(self.player) 819 | 820 | def play_game(self): 821 | game = Game() 822 | game.go(self.predictions, self.player, self.pbest, self.history, self.steps) 823 | 824 | def update_pbest(self, game_result): 825 | self.pbest.append(game_result) 826 | 827 | def evaluate_game(self): 828 | game = Game() 829 | game.go(self.predictions, self.player, self.pbest, self.history, self.steps) 830 | return game.scores 831 | 832 | def get_selected_player(self): 833 | if self.pbest[-1] == self.player: 834 | return self.player 835 | else: 836 | return None 837 | 838 | def get_chosen_player(self): 839 | return self.pbest[self.get_selected_player()] 840 | 841 | 842 | ==================== 843 | class AI: 844 | """A class used to represent an artificial intelligence""" 845 | 846 | # Functions 847 | # --------------------------------------------------------- 848 | 849 | def play_demo(): 850 | # Initialize variables 851 | agent = Bot("Marcus", 100) 852 | random_agent = Bot("Marcus") 853 | opponent = Bot("Marcus") 854 | computer_player = Bot("Mortar") 855 | training_grid = [[0] * 100] * 100 856 | 857 | # Initialize events and manage input 858 | refresh_all_grid = input_refresh(training_grid) 859 | # Remove output if there is an observation that requires no change 860 | opponent.assert_observation_contains(200) 861 | # Start the game 862 | opponent.start_game() 863 | # Play the game 864 | for action, reward in agent.act(random_agent, computer_player): 865 | training_grid[action][reward] += 1 866 | print("> Player {}: {:.2f}".format(action, reward)) 867 | print(f"Best action: {action}") 868 | opponent.assert_observation_contains(200) 869 | 870 | # Show the replay 871 | game_state_replay = replay_of_game(training_grid) 872 | print(f"This is a replay of the best game:\n{game_state_replay}") 873 | 874 | # Display results 875 | print(f"Player 2 wins") 876 | print(f"Player 1 has an average reward of {agent.accuracy.mean():.2f} and best action was:", agent.action.argmax()) 877 | print( 878 | ==================== 879 | class AI: 880 | """A class used to represent an artificial intelligence""" 881 | def __init__(self, name=''): 882 | # AI Name (It can be "Hello World") 883 | self.name = name 884 | self.system = 0 885 | 886 | # --- Methods --- 887 | 888 | def play(self, game_data, player, opponent=None): 889 | #...implementation... 890 | return None 891 | 892 | def get_system_status(self, *args): 893 | #...implementation... 894 | return None 895 | 896 | def set_system_status(self, *args): 897 | #...implementation... 898 | return None 899 | 900 | # --- 901 | # --- Methods --- 902 | 903 | def sim(self, num_iterations): 904 | #...implementation... 905 | return None 906 | 907 | def setup_ai(self): 908 | #...implementation... 909 | return None 910 | 911 | def check_ai(self): 912 | #...implementation... 913 | return None 914 | 915 | def init_ai_data(self): 916 | #...implementation... 917 | return None 918 | 919 | def load_ai_data(self, data): 920 | #...implementation... 921 | return None 922 | 923 | def get_setting_result(self, *args): 924 | #...implementation... 925 | return None 926 | 927 | def load_setting(self, *args): 928 | #...implementation... 929 | return None 930 | 931 | def main(): 932 | #...implementation... 933 | return None 934 | 935 | if __name__ == '__main__': 936 | #...implementation... 937 | ai = AI("World-AI") 938 | 939 | ==================== 940 | class AI: 941 | """A class used to represent an artificial intelligence""" 942 | 943 | def __init__(self, name, capability, base_level, last_check=None): 944 | """Initialize an AI with name, capability, and level, 945 | optionally with a date.""" 946 | 947 | self.name = name 948 | self.capability = capability 949 | self.base_level = base_level 950 | self.last_check = last_check 951 | self.last_check_date = datetime.now() if self.last_check is None else self.last_check 952 | 953 | self.level = base_level 954 | if last_check is None: 955 | self.last_check_date = self.last_check 956 | 957 | def run(self, rules, targets, timestamp): 958 | """Does the action specified by the rules for the 959 | targets.""" 960 | 961 | for r in rules: 962 | r.check_reasons = [] 963 | 964 | for t in targets: 965 | if t.base_level > self.level: 966 | continue 967 | 968 | self.rule(r, t, timestamp) 969 | 970 | return not t.goal 971 | 972 | def rule(self, r, t, timestamp): 973 | """Get the decision from a ruleset for a target""" 974 | 975 | if r.pre_actions: 976 | r.pre_actions.append(self.rule_action(r, t, timestamp)) 977 | 978 | # See if we can apply decisions from later levels 979 | 980 | try: 981 | rs = t.base_level.decisions[r.name 982 | ==================== 983 | class AI: 984 | """A class used to represent an artificial intelligence""" 985 | DEFAULT_MUTABLE_CLASS = ( 986 | ('__name__', 'Name'), 987 | ('__friends__', 'Friends'), 988 | ('__friends_friends__', 'Friends of Friends'), 989 | ('__profile__', 'Profile'), 990 | ('__img__', 'Image'), 991 | ('__img___small__', 'Image (small)'), 992 | ('__img___medium__', 'Image (medium)'), 993 | ('__img___large__', 'Image (large)'), 994 | ('__img___is_original__', 'Image (is_original)'), 995 | ('__actions__', 'Actions'), 996 | ('__action_type__', 'Action type'), 997 | ('__action_type_short__', 'Action type (short)'), 998 | ('__action_type_long__', 'Action type (long)'), 999 | ('__action_possible_beneficial__', 'Action possible beneficial'), 1000 | ('__action_possible_harming__', 'Action possible harming'), 1001 | ('__action_completed__', 'Action completed'), 1002 | ('__has_action__', 'Has action'), 1003 | ('__self_friend__', 'Self/Friends'), 1004 | ('__all__', 'All'), 1005 | ('__definitions__', 'Definitions'), 1006 | ('__reactions__', 'Reactions'), 1007 | ('__rating__', 'Rating'), 1008 | ('__base__', 'Base'), 1009 | ('__status__', 'Status'), 1010 | ('__status_neutral__', 'Status neutral'), 1011 | ('__status_ 1012 | ==================== 1013 | class AI: 1014 | """A class used to represent an artificial intelligence""" 1015 | # Needed because we want to make AI factory methods 1016 | AI = namedtuple('AI', 'name learning_rate learning_rate_decay gamma') 1017 | # Metrics can be added here if we have them 1018 | # TODO: Add them 1019 | M_accuracy = 'Accuracy' 1020 | M_loss = 'Loss' 1021 | # List of models 1022 | model_list = None 1023 | # Default settings 1024 | Settings = { 1025 | 'learning_rate': 0.001, 1026 | 'learning_rate_decay': 0.0001, 1027 | 'gamma': 0.2, 1028 | 'sparsity_penalty': None 1029 | } 1030 | 1031 | def __init__(self, name, learning_rate=0.001, learning_rate_decay=0.0001, 1032 | gamma=0.2, sparsity_penalty=0, train=True, save_history=True): 1033 | """Initialize the AI class and set the default arguments. 1034 | Args: 1035 | name (str): Name of the AI 1036 | learning_rate (float): Learning rate 1037 | learning_rate_decay (float): Decay rate for learning rate 1038 | gamma (float): Weight decay coefficient 1039 | sparsity_penalty (float): penalty for sparsity 1040 | train (bool): If True, the trainer class will be instantiated 1041 | and we save its output files (see Trainer class) 1042 | save_history (bool): If True, the trainer class will be 1043 | 1044 | ==================== 1045 | class AI: 1046 | """A class used to represent an artificial intelligence""" 1047 | 1048 | def __init__(self, engine): 1049 | """The constructor of the class, where the AI Engine is initialized. 1050 | 1051 | Parameters 1052 | ---------- 1053 | engine: AIEngine 1054 | AIEngine which will be initialised. 1055 | 1056 | """ 1057 | self.engine = engine 1058 | 1059 | def run(self): 1060 | """The main method of the AI class. 1061 | 1062 | It plays the game against the human player. 1063 | 1064 | """ 1065 | self.engine.load_game_and_rules(self.rules) 1066 | 1067 | while self.engine.player.score < 1: 1068 | self.engine.reset() 1069 | self.engine.turn = self.engine.human_player 1070 | self.engine.AI() 1071 | self.engine.player.adjust_player_score() 1072 | self.engine.AI() 1073 | self.engine.human_player.adjust_player_score() 1074 | 1075 | self.engine.restart() 1076 | 1077 | self.engine.load_game_and_rules(self.rules) 1078 | 1079 | while self.engine.player.score < 1: 1080 | self.engine.reset() 1081 | self.engine.turn = self.engine.player 1082 | self.engine.AI() 1083 | 1084 | ==================== 1085 | class AI: 1086 | """A class used to represent an artificial intelligence""" 1087 | 1088 | # Choose a random system of rules 1089 | def __init__(self): 1090 | self.rules = [{'name':"",'message':'','solution':[]}, 1091 | {'name':"","message":"",'solution':[]}] 1092 | # Shuffle the list 1093 | random.shuffle(self.rules) 1094 | 1095 | # Set all rule names to equal "", so that the random names aren't already in the rules list 1096 | for rule in self.rules: 1097 | rule['name'] = '' 1098 | rule['message'] = '' 1099 | rule['solution'] = [] 1100 | 1101 | # Create a new rule by specifying the rule name, message, and if it is solved 1102 | def add_rule(self, rule_name, rule_message, rule_solved): 1103 | # Create a rule 1104 | self.rules.append({"name": rule_name, "message": rule_message, "solution": [rule_solved]}) 1105 | 1106 | # Evaluate a single rule 1107 | def rule_eval(self, rule): 1108 | # Create an output string from the rule input and evaluate it with the rule 1109 | # Apply the strategy for adding solutions to the rule 1110 | output_str = [] 1111 | for solution in rule['solution']: 1112 | if len(solution) > 0: 1113 | for string in solution: 1114 | output_str. 1115 | ==================== 1116 | class AI: 1117 | """A class used to represent an artificial intelligence""" 1118 | def __init__(self, inputs, outputs, layer): 1119 | self.inputs = inputs 1120 | self.outputs = outputs 1121 | self.layer = layer 1122 | 1123 | def __getstate__(self): 1124 | """Restores the AI object with the most recent states""" 1125 | return { 1126 | 'inputs': self.inputs, 1127 | 'outputs': self.outputs, 1128 | 'layer': self.layer 1129 | } 1130 | 1131 | def __setstate__(self, state): 1132 | """Restores the AI object with the most recent states""" 1133 | self.inputs = state['inputs'] 1134 | self.outputs = state['outputs'] 1135 | self.layer = state['layer'] 1136 | 1137 | def _add_input_to_inputs(self): 1138 | """Add input information to inputs""" 1139 | self.inputs['hidden_input'] = self.inputs['new_input'] 1140 | self.inputs['state_input'] = self.inputs['new_state'] 1141 | 1142 | def _copy_input_to_outputs(self): 1143 | """Copy information to outputs""" 1144 | self.outputs['state'] = self.inputs['new_state'] 1145 | 1146 | def _add_output_to_outputs(self): 1147 | """Add output information to outputs""" 1148 | self.outputs['new_input'] = self.outputs['hidden_output'] 1149 | 1150 | def _clear_output_to_outputs(self): 1151 | """Clear output information from outputs""" 1152 | self.outputs['hidden_output'] = np.zeros(self 1153 | ==================== 1154 | class AI: 1155 | """A class used to represent an artificial intelligence""" 1156 | def __init__(self): 1157 | self.memory = {} 1158 | 1159 | self.current_player = None 1160 | 1161 | def load_rules(self, rules_file): 1162 | """ 1163 | Load a rules file and setup all parameters for the AI 1164 | :param rules_file: Path to the rules file 1165 | :return: 1166 | """ 1167 | # Define the rules for the AI 1168 | with open(rules_file) as f: 1169 | self.current_rules = json.load(f) 1170 | print(self.current_rules) 1171 | for rule in self.current_rules: 1172 | rule = self.current_rules[rule] 1173 | self.memory[rule] = {} 1174 | self.memory[rule].update(rule) 1175 | 1176 | def set_default_players(self): 1177 | """ 1178 | Set the default players for the AI 1179 | :return: 1180 | """ 1181 | # Get the players from the file 1182 | self.players = self.get_players() 1183 | return self.players 1184 | 1185 | def get_players(self): 1186 | """ 1187 | Set all player information and return it as a list of dicts 1188 | :return: 1189 | """ 1190 | # Get all the players 1191 | players = [i['name'] for i in open('players.txt')] 1192 | # Set all the players to the list 1193 | self.players = [{'name': i, 1194 | ==================== 1195 | class AI: 1196 | """A class used to represent an artificial intelligence""" 1197 | 1198 | # AI constructors 1199 | def __init__(self, problem, environment, step_callback, actions, 1200 | act=False, data=None, random=True, max_time=None, max_actions=None): 1201 | 1202 | # Set the AI's inputs (for documentation and so on) 1203 | self.problem = problem 1204 | self.environment = environment 1205 | self.step_callback = step_callback 1206 | self.actions = actions 1207 | self.act = act 1208 | self.data = data 1209 | self.random = random 1210 | self.max_time = max_time 1211 | self.max_actions = max_actions 1212 | 1213 | # Set the AI's inputs (for documentation and so on) 1214 | self.max_episode = 0 1215 | self.done = False 1216 | self.error = False 1217 | self.done_episode = 0 1218 | self.episode_over = False 1219 | self.gamma = 0.9 1220 | self.episode_steps = 0 1221 | self.done_steps = 0 1222 | self.action_steps = 0 1223 | self.data_steps = 0 1224 | self.random_steps = 0 1225 | self.time_window = 0 1226 | 1227 | # Set the AI's inputs (for documentation and so on) 1228 | self.last_data = None 1229 | self.last_data_steps = 0 1230 | self.last_data_error = False 1231 | self.last_data_error_steps = 0 1232 | 1233 | ==================== 1234 | class AI: 1235 | """A class used to represent an artificial intelligence""" 1236 | def __init__(self): 1237 | self.AI_info = {} 1238 | self.AI_fail_flag = False 1239 | 1240 | self.AI_elig = ['alien-alien', 'alien-alien2', 'alien-alien2a'] 1241 | self.AI_node_num = len(self.AI_elig) 1242 | 1243 | self.T = 9 * 3.5 1244 | self.H = 5 * 3.5 1245 | 1246 | self.goal = [] 1247 | self.lifted_list = [] 1248 | 1249 | self.t = 1 1250 | 1251 | self.FLAG_INITIAL_PHASE = False 1252 | 1253 | def AI_fail_check(self): 1254 | if self.AI_info.get('FLAG_INITIAL_PHASE', False): 1255 | return True 1256 | if self.AI_fail_flag: 1257 | return True 1258 | 1259 | if not self.A.is_continue_(): 1260 | self.AI_fail_flag = True 1261 | return True 1262 | 1263 | if not self.AI_info.get('data_loss', False): 1264 | return True 1265 | 1266 | if self.A.is_refueling(): 1267 | if self.A.u_in_lag == 1: 1268 | return True 1269 | 1270 | return False 1271 | 1272 | def AI_start(self, dst): 1273 | if self.AI_info.get('FLAG_INITIAL_PHASE', False): 1274 | return False 1275 | if not 1276 | ==================== 1277 | class AI: 1278 | """A class used to represent an artificial intelligence""" 1279 | 1280 | def __init__(self): 1281 | self.x = 0 1282 | self.delta = 0 1283 | 1284 | def update(self, context, action): 1285 | if context is None: 1286 | # We are probably using the node's id to pass a 1287 | # node in context, instead of directly using the 1288 | # node's id as in the original AIBO update function 1289 | # -- Let's be consistent here: 1290 | 1291 | # context = self.get_node(context) 1292 | 1293 | self.x += action 1294 | # context = self.get_node(context) 1295 | 1296 | if action > 0: 1297 | self.delta = -1 1298 | elif action < 0: 1299 | self.delta = 1 1300 | return self.x 1301 | 1302 | class Node(object): 1303 | 1304 | """A class to represent a physical node (implements node functionality)""" 1305 | 1306 | def __init__(self, id, **kwargs): 1307 | self.id = id 1308 | self.data = kwargs 1309 | 1310 | def __str__(self): 1311 | return 'Node (id: %d) -> %s' % (self.id, repr(self.data)) 1312 | 1313 | def get_node(self, id): 1314 | """Returns the node with the given id""" 1315 | 1316 | return self.nodes.get(id) 1317 | 1318 | def get_history(self, id): 1319 | """Returns a list of the data given by the node""" 1320 | 1321 | return self.data.get(id, []) 1322 | 1323 | def get_score(self, 1324 | ==================== 1325 | class AI: 1326 | """A class used to represent an artificial intelligence""" 1327 | def __init__(self): 1328 | self.agent_list = [] 1329 | self.max_alpha = 4 1330 | self.game_end = None 1331 | self.episode = 0 1332 | self.max_round = 4 1333 | self.max_step = 30 1334 | self.max_actions = 3 1335 | 1336 | def agent_str(self): 1337 | """ 1338 | Returns an agent's name and its pointer to the agent's strategy 1339 | """ 1340 | return 'Agent' + self.episode + str(self.agent_list) + '(' + str(self.max_alpha) + ')' 1341 | 1342 | def agent_list_str(self): 1343 | """ 1344 | Returns an agent's name and its pointer to the agent's strategy 1345 | """ 1346 | return 'Agent' + self.episode + ':' + str(self.agent_list) 1347 | 1348 | def agent_struct_str(self): 1349 | """ 1350 | Returns an agent's name and its pointer to the agent's strategy 1351 | """ 1352 | return 'Agent' + self.episode + str(self.agent_list) + '(' + str(self.max_alpha) + ')' 1353 | 1354 | def agent_list_init(self): 1355 | """ 1356 | Adds agents to the list of agents in the world. 1357 | """ 1358 | self.agent_list.append(Agent('0', 1, 3)) 1359 | self.agent_list.append(Agent('1', 1, 4)) 1360 | self.agent_list.append(Agent('2', 2, 5)) 1361 | self.agent_list. 1362 | ==================== 1363 | class AI: 1364 | """A class used to represent an artificial intelligence""" 1365 | 1366 | def __init__(self, nb_agents, np_components, 1367 | sim_size, max_steps): 1368 | """ 1369 | Parameters: 1370 | ---------- 1371 | nb_agents: int 1372 | The number of agents in the AI. 1373 | np_components: int 1374 | The number of components in the agents' behaviour. 1375 | sim_size: int 1376 | The size of the agent's state. 1377 | max_steps: int 1378 | The maximum number of steps. 1379 | """ 1380 | super().__init__() 1381 | 1382 | self.nb_agents = nb_agents 1383 | self.np_components = np_components 1384 | self.sim_size = sim_size 1385 | self.max_steps = max_steps 1386 | self.nb_components = np_components * self.nb_agents 1387 | 1388 | self.R = np.zeros((self.np_components, self.nb_agents), dtype=int) 1389 | self.T = np.zeros((self.np_components, self.nb_agents, self.sim_size), dtype=float) 1390 | 1391 | def sample(self, pi, p): 1392 | """ 1393 | Return a sample in the probability distribution pi. 1394 | 1395 | Parameters: 1396 | ---------- 1397 | pi: np.array 1398 | The probability distribution to sample from. 1399 | p: np.array 1400 | 1401 | ==================== 1402 | class AI: 1403 | """A class used to represent an artificial intelligence""" 1404 | def get_agent(self): 1405 | """This returns the underlying agent object""" 1406 | return Agent() 1407 | 1408 | def create_agent(self, name): 1409 | """Creates a new agent with name""" 1410 | return Agent(name) 1411 | 1412 | def get_agent_from_module(self, module): 1413 | """Given a module (model) get the underlying Agent object""" 1414 | return self.get_agent() 1415 | 1416 | def get_agent_by_name(self, name): 1417 | """Gets an agent by name, returns None if not found""" 1418 | return self.get_agent_from_module(name) 1419 | 1420 | def set_agent(self, agent, name): 1421 | """Sets the underlying agent object""" 1422 | self.get_agent().set_agent(agent, name) 1423 | 1424 | def get_player_pcs(self): 1425 | """Gets the set of player controlled pcs""" 1426 | return self.get_agent().get_player_pcs() 1427 | 1428 | def get_player_card_number(self): 1429 | """Gets the set of player controlled cards""" 1430 | return self.get_agent().get_player_pcs() 1431 | 1432 | def get_dealer_pcs(self): 1433 | """Gets the set of dealer controlled pcs""" 1434 | return self.get_agent().get_dealer_pcs() 1435 | 1436 | def get_dealer_card_number(self): 1437 | """Gets the set of dealer controlled cards""" 1438 | return self.get_agent().get_dealer_pcs() 1439 | 1440 | def get_deals_in_line(self): 1441 | """Gets the list of deals""" 1442 | return self 1443 | ==================== 1444 | class AI: 1445 | """A class used to represent an artificial intelligence""" 1446 | # The AI "mind" runs code using the AI class to generate output, 1447 | # using AI::dispatch() to handle/generate behavior or 1448 | # AI::print_behaviour(). 1449 | # The AI "mind" does NOT interact with the outside world, 1450 | # just other AI "minds". 1451 | # No real AI behaviour can happen without code to implement it. 1452 | # This is the "world" of AI. 1453 | 1454 | ALOGE("AI: %s" % self.title) 1455 | 1456 | def init(self, user, sim): 1457 | if user == 'root': 1458 | if self.avg > 0.5: 1459 | self.avg = 0.5 1460 | else: 1461 | self.avg = self.avg + 0.1 1462 | elif user == 'process': 1463 | self.avg = 0.9 1464 | else: 1465 | print("AI: Unknown user type (%s)" % user) 1466 | self.avg = 0.1 1467 | print("AI: Initializing, avg %f" % self.avg) 1468 | 1469 | def run(self): 1470 | pass 1471 | 1472 | ############################################# 1473 | # The Program Behavior Classes 1474 | ############################################# 1475 | 1476 | class Local_calculation_strategy: 1477 | """The localized calculation strategy """ 1478 | def __init__(self): 1479 | self.avg = 0.5 1480 | 1481 | def run(self): 1482 | pass 1483 | 1484 | 1485 | class Diffusion_calculation_strategy: 1486 | """The diffusion calculation strategy """ 1487 | def __init__(self): 1488 | self.avg = 0.5 1489 | 1490 | 1491 | ==================== 1492 | class AI: 1493 | """A class used to represent an artificial intelligence""" 1494 | 1495 | def __init__(self, difficulty, subject, perceptron): 1496 | self.difficulty = difficulty 1497 | self.subject = subject 1498 | self.perceptron = perceptron 1499 | self.do_choices = 0 1500 | self.wrong = 0 1501 | 1502 | def calculate_perceptron(self): 1503 | """Runs the perceptron function""" 1504 | raise NotImplementedError("Method needs to be implemented.") 1505 | 1506 | def make_match(self): 1507 | """Runs the match function""" 1508 | raise NotImplementedError("Method needs to be implemented.") 1509 | 1510 | def change_intelligence(self): 1511 | """Runs the intelligence change""" 1512 | raise NotImplementedError("Method needs to be implemented.") 1513 | 1514 | def rule_1(self, opponent): 1515 | """Runs rule one""" 1516 | return 1 1517 | 1518 | def rule_2(self, opponent): 1519 | """Runs rule two""" 1520 | return 2 1521 | 1522 | def rule_3(self, opponent): 1523 | """Runs rule three""" 1524 | return 3 1525 | 1526 | def rule_4(self, opponent): 1527 | """Runs rule four""" 1528 | return 4 1529 | 1530 | def decision(self, opponent): 1531 | """Returns the decision of the opponent, makes a random 1532 | if it's too high""" 1533 | return random.choice(self.list) 1534 | 1535 | def adapt_loss(self): 1536 | """Returns the chance of losing or winning""" 1537 | return 1 - self.perceptron 1538 | 1539 | def calculate_turn(self, opponent): 1540 | """Checks the 1541 | ==================== 1542 | class AI: 1543 | """A class used to represent an artificial intelligence""" 1544 | 1545 | def run(self): 1546 | """Intended for main""" 1547 | print("Reached run AI") 1548 | 1549 | ... 1550 | 1551 | <|endoftext|>Principles of an Internal Audit 1552 | 1553 | Venture Studio’s Project ‘Principles of an Internal Audit’ seeks to address current issues faced by start-up and incumbent enterprises in a bid to improve internal control mechanisms. 1554 | 1555 | The five principles that underlie this project are therefore as follows: 1556 | 1557 | 1. Control 1558 | 1559 | 2. Independent thinking 1560 | 1561 | 3. Documentation 1562 | 1563 | 4. Reinforcement of the auditors’ code of conduct 1564 | 1565 | 5. Responsible conduct of auditors 1566 | 1567 | Additional services will include project management, research on topics relevant to the project and statistical analysis. The goal of this initiative is to boost the effectiveness of corporate auditing and to streamline its processes.<|endoftext|>In the field of label design, there has been great advancement in recent years in the use of laser-based printers, liquid jet printers, ink jet printers, or the like, to print labels for a number of applications. Where printers capable of printing labels with print resolutions of about 150 to 300 dots per inch (dpi) are used, laser printers are typically more economical than ink jet printers due to the lower cost per print resolution of laser printers. 1568 | Most labels use transparent substrates that are printed on one side, and the front side of the substrate is then attached to a package. The printer is typically offset from the package so as to not contact the front side of the substrate when printing the label on the substrate, as the front side of the substrate can become damaged during printing. Unfortunately, this prevents the printer from applying printing directly to the label front side. Instead, the printer typically prints the labels at a distance away from the package, and the labels are then moved toward the package. The label adhesive is then applied by a roller or other application apparatus that touches the package and the labels as they move past the roller. In this manner, it is common to place the printer on the side of the package, and the printing apparatus on the opposite side of the package. 1569 | It has been a challenge, however, to provide print capabilities directly on a package label. As noted above, ink jet and laser printers are generally expensive and have print resolutions of about 150-300 dpi. In contrast, bar code printers capable of printing bar codes and/or print at higher 1570 | ==================== 1571 | class AI: 1572 | """A class used to represent an artificial intelligence""" 1573 | 1574 | def __init__(self, self_initial_attentions, 1575 | self_action_space, self_observations, self_rewards, 1576 | self_done=False, self_neighbor_features=None): 1577 | """Initialize AI""" 1578 | self.alpha = -1.0 1579 | self.beta = -1.0 1580 | self.self_action_space = self_action_space 1581 | self.self_observations = self_observations 1582 | self.self_rewards = self_rewards 1583 | self.self_done = self_done 1584 | self.self_neighbor_features = self_neighbor_features 1585 | self.T = len(self.self_observations) 1586 | self.K = len(self.self_actions) 1587 | self.self_initial_attentions = self_initial_attentions 1588 | 1589 | def adjust_action(self, previous_action, hidden_states): 1590 | """Adjust action""" 1591 | if self.self_done: 1592 | return previous_action 1593 | if len(self.self_actions) == 0: 1594 | return previous_action 1595 | if self.alpha > 0: 1596 | # TODO: change self.self_action_space to softmax 1597 | logits = tf.matmul(hidden_states, self.self_initial_attentions) + tf.nn.log_softmax(logits) 1598 | logits = tf.matmul( 1599 | ==================== 1600 | class AI: 1601 | """A class used to represent an artificial intelligence""" 1602 | 1603 | def __init__(self, player, computer): 1604 | self.player = player 1605 | self.computer = computer 1606 | 1607 | def action(self, turn_player): 1608 | """Returns the action for the current player 1609 | If both players have the same action, they 1610 | swap actions""" 1611 | if self.player == turn_player: 1612 | return self.player 1613 | else: 1614 | return self.computer 1615 | 1616 | def strategy(self): 1617 | """Return the best possible strategy given the game state""" 1618 | if self.player == "AI": 1619 | return self.computer 1620 | elif self.player == "Xavier": 1621 | return self.player 1622 | else: 1623 | return self.computer 1624 | 1625 | def did_win(self): 1626 | """Returns True if the game has been won by the computer 1627 | If the game hasn't ended yet, return False""" 1628 | return self.computer == "AI" 1629 | 1630 | def __str__(self): 1631 | return "{} vs. {}".format(self.player, self.computer) 1632 | 1633 | 1634 | """Chess""" 1635 | 1636 | class ChessBoard: 1637 | """Chess board class""" 1638 | 1639 | white = "wq" 1640 | black = "w8" 1641 | 1642 | white_black = "b7" 1643 | white_king = "8/8" 1644 | white_bishop = "1b" 1645 | white_rook = 1646 | ==================== 1647 | class AI: 1648 | """A class used to represent an artificial intelligence""" 1649 | DONE_SELECT = "DONE_SELECT" 1650 | SELECT_SELECTED = "SELECT_SELECTED" 1651 | SELECT_UNSELECTED = "SELECT_UNSELECTED" 1652 | TYPE_CHOOSE = "TYPE_CHOOSE" 1653 | TYPE_UNCHOOSE = "TYPE_UNCHOOSE" 1654 | TYPE_LIST = "TYPE_LIST" 1655 | HIDDEN_LIST_SELECT = "HIDDEN_LIST_SELECT" 1656 | HIDDEN_LIST_UNSELECT = "HIDDEN_LIST_UNSELECT" 1657 | HIDDEN_LIST_SELECTED = "HIDDEN_LIST_SELECTED" 1658 | HIDDEN_LIST_UNSELECTED = "HIDDEN_LIST_UNSELECTED" 1659 | HIDDEN_SELECT_SELECT = "HIDDEN_SELECT_SELECT" 1660 | HIDDEN_SELECT_UNSELECT = "HIDDEN_SELECT_UNSELECT" 1661 | HIDDEN_SELECT_SELECTED = "HIDDEN_SELECT_SELECTED" 1662 | HIDDEN_SELECT_UNSELECTED = "HIDDEN_SELECT_UNSELECTED" 1663 | HIDDEN_NO_SELECT = "HIDDEN_NO_SELECT" 1664 | HIDDEN_NO_UNSELECT = "HIDDEN_NO_UNSELECT" 1665 | HIDDEN_NO_SELECTED = "HIDDEN_NO_SELECTED" 1666 | HIDDEN_NO_UNSELECTED = "HIDDEN_NO_UNSELECTED" 1667 | HIDDEN_NO_DONE = "HIDDEN_NO_DONE" 1668 | HIDDEN_NO_DONE_SELECTED = "HIDDEN_NO_DONE_SELECTED" 1669 | HIDDEN_NO_DONE_UNSELECTED = "HIDDEN_NO_DONE_UNSELECTED" 1670 | HIDDEN_CHOOSE_SELECT = "HIDDEN_CHOOSE_SELECT" 1671 | HIDDEN_CHOOSE_UNSELECT = "HIDDEN_CHOOSE_UNSELECT" 1672 | HIDDEN_CHOOSE_SELECTED 1673 | ==================== 1674 | class AI: 1675 | """A class used to represent an artificial intelligence""" 1676 | 1677 | NINTRO = 10 1678 | KNOCKEDOUT = 30 1679 | WAKE = 40 1680 | DURING = 50 1681 | AWAKE = 60 1682 | NEWER = 70 1683 | OLDER = 80 1684 | FOLLOWING = 90 1685 | PASSING = 100 1686 | 1687 | DIRECTIONAL = 110 1688 | STILL = 120 1689 | MOVING_FORWARD = 130 1690 | MOVING_BACKWARD = 140 1691 | TURNING_LEFT = 150 1692 | TURNING_RIGHT = 160 1693 | 1694 | WAIT = 170 1695 | 1696 | ENERGY = 180 1697 | PSYCHEDELIC = 190 1698 | STARVATION = 200 1699 | 1700 | IGNORE = 210 1701 | ALL = 221 1702 | 1703 | INJURY = 230 1704 | STICK = 240 1705 | SCRAMBLE = 250 1706 | CANCEL = 260 1707 | GROWL = 270 1708 | TICKLE = 280 1709 | EAT = 290 1710 | USE = 300 1711 | INJECT = 310 1712 | THINK = 320 1713 | 1714 | FEAR = 330 1715 | AGGRESSION = 340 1716 | AWAKEN = 350 1717 | SNIFF = 360 1718 | EXPLORE = 370 1719 | RETURN = 380 1720 | RUN = 390 1721 | EVOLVE = 400 1722 | 1723 | FREEZE = 410 1724 | FLEE = 420 1725 | CHASE = 430 1726 | LEAVE = 440 1727 | STILLNESS = 450 1728 | CHILL = 460 1729 | EXHAUST = 470 1730 | 1731 | HEALTH = 480 1732 | WOUND = 490 1733 | CRASHED = 500 1734 | 1735 | PLAY = 510 1736 | YOUNG = 520 1737 | OLD = 530 1738 | DEAD = 540 1739 | OLDER = 550 1740 | PASSING = 560 1741 | 1742 | MESSAGE = 570 1743 | BEHIND = 580 1744 | INTRO = 590 1745 | 1746 | ==================== 1747 | class AI: 1748 | """A class used to represent an artificial intelligence""" 1749 | 1750 | def __init__(self, path = "/Users/user/Desktop/node-aiohttp/ai.py"): 1751 | self.path = path 1752 | # AI home environment, the location where data is stored 1753 | self.home = os.path.dirname(os.path.abspath(__file__)) 1754 | 1755 | def __str__(self): 1756 | return "AI Class instance" 1757 | 1758 | def exec_action(self, action): 1759 | """Executes the action and returns the exit code. 1760 | Parameters: 1761 | action -- An action object with the required attributes 1762 | Returns: 1763 | 0 -- if success, -1 -- if error 1764 | """ 1765 | try: 1766 | # Execute the action 1767 | # print action.get_return 1768 | exit_code = action.run() 1769 | return exit_code 1770 | except: 1771 | # Log any error from the action 1772 | print("action threw error") 1773 | raise 1774 | 1775 | def __getitem__(self, key): 1776 | # Load current context information 1777 | with open(self.path) as f: 1778 | context = f.read() 1779 | 1780 | # Extract current context 1781 | if "home" in context: 1782 | self.home = os.path.dirname(os.path.abspath(context[ 1783 | "home"])) 1784 | 1785 | ==================== 1786 | class AI: 1787 | """A class used to represent an artificial intelligence""" 1788 | _object_name = 'AI' 1789 | 1790 | def __init__(self, config_file=None): 1791 | """Initializes an AI object""" 1792 | 1793 | if not config_file: 1794 | config_file ='metadata.json' 1795 | with open(config_file, 'r') as f: 1796 | json_data = json.loads(f.read()) 1797 | 1798 | self.config = {} 1799 | self.config.update(json_data) 1800 | self.config.update(metai.AI_STRUCTURES) 1801 | 1802 | # Fields that will be appended to the agents' config 1803 | for agent in self.get_agents(): 1804 | agent.config.update(self.config) 1805 | 1806 | self.agents.extend(self.get_agents()) 1807 | 1808 | def add_agents(self): 1809 | """Add agents""" 1810 | for entity in self.agents: 1811 | entity.add_agent(self) 1812 | 1813 | def add_static_parameters(self): 1814 | """Add static parameters""" 1815 | for entity in self.agents: 1816 | entity.add_static_parameters() 1817 | 1818 | def add_structure_parameters(self): 1819 | """Add structure parameters""" 1820 | for structure in self.agents: 1821 | structure.add_structure_parameters() 1822 | 1823 | def get_agents(self): 1824 | """Returns a list of agents""" 1825 | agents = [] 1826 | ==================== 1827 | class AI: 1828 | """A class used to represent an artificial intelligence""" 1829 | 1830 | def __init__(self, name, owner, verbose): 1831 | """Class initializer 1832 | 1833 | Args: 1834 | name: string. The name of the AI 1835 | owner: string. The owner of the AI. 1836 | verbose: integer. How much detail the AI will output. 1837 | """ 1838 | self.name = name 1839 | self.owner = owner 1840 | self.verbose = verbose 1841 | 1842 | def simulate(self, currentState): 1843 | """Simulate the AI's decision making process. 1844 | 1845 | Args: 1846 | currentState: list of current state. 1847 | """ 1848 | # currentState is the total list of items that we currently have in the 1849 | # collection. If we have no items we will get into an infinite loop here. 1850 | for item in currentState: 1851 | currentState.remove(item) 1852 | 1853 | self.evaluate() 1854 | # Basically simulating. All we are doing here is: 1855 | # 1. Select an action 1856 | # 2. Move the item to the new location 1857 | # 3. Update the state to reflect the new state of the items 1858 | 1859 | # You can actually get very complicated. See the example below 1860 | for action in available_actions(): 1861 | newAction = self.move_from_state(currentState, action) 1862 | if newAction: 1863 | # The item was moved, so we need to update the state of the items 1864 | 1865 | ==================== 1866 | class AI: 1867 | """A class used to represent an artificial intelligence""" 1868 | 1869 | @property 1870 | def name(self): 1871 | """Returns the AI's name""" 1872 | return self.__class__.__name__ 1873 | 1874 | @property 1875 | def score(self): 1876 | """Returns the AI's score""" 1877 | return self.__class__.score 1878 | 1879 | def __init__(self, secret_question, maximum_score): 1880 | """Initialize the AI object""" 1881 | 1882 | self.__secret_question = secret_question 1883 | self.__maximum_score = maximum_score 1884 | 1885 | if self.__secret_question is None or self.__maximum_score is None: 1886 | raise Exception("One of the variables secret_question or maximum_score must be provided") 1887 | 1888 | self.__secret_answer = [] 1889 | 1890 | self.__clock = Clock() 1891 | self.__timestamp = 0 1892 | 1893 | self.__answer_history = [] 1894 | self.__answer_list = [] 1895 | 1896 | self.__wrong_answers = [] 1897 | 1898 | self.__answers_dict = {} 1899 | self.__answers_dict['hostname'] = 'AI' 1900 | self.__answers_dict['question'] = self.__secret_question 1901 | 1902 | self.__model_dir = "crawler_ai" + str(uuid.uuid4())[0:8] + '.h5' 1903 | 1904 | print("AI name is " + self.__name) 1905 | print("Initializing: " + self.__name) 1906 | 1907 | def __free_model_dir(self): 1908 | """Stops the model from loading and generates the new filename""" 1909 | 1910 | if self. 1911 | ==================== 1912 | class AI: 1913 | """A class used to represent an artificial intelligence""" 1914 | 1915 | def __init__(self, space, goal): 1916 | self.space = space 1917 | self.goal = goal 1918 | 1919 | def __call__(self, state, action): 1920 | """Evaluate the action, and depending on that change state""" 1921 | action = {'play': self.play, 'run': self.run}[action] 1922 | 1923 | #debug mode 1924 | if DEBUG: 1925 | print "Space: %s" % self.space 1926 | print "Goal: %s" % self.goal 1927 | print "Requested action: %s" % action 1928 | print "New state: %s" % state 1929 | print "This AI doesn't know about play. Will assume that the goal is to run" 1930 | 1931 | #goal >0 1932 | if self.goal > 0: 1933 | action_run = action 1934 | self.set_state(state, goal=0) 1935 | if not self.play(self.space): 1936 | raise ValueError("No solution found.") 1937 | #eval the play 1938 | else: 1939 | #goal < 0 1940 | action_play = action 1941 | if not self.play(self.space): 1942 | raise ValueError("No solution found.") 1943 | #eval the play 1944 | self.set_state(state, goal=0) 1945 | 1946 | 1947 | ==================== 1948 | class AI: 1949 | """A class used to represent an artificial intelligence""" 1950 | 1951 | def __init__(self, name): 1952 | """ 1953 | Starts a new artificial intelligence, with a unique name. 1954 | :param name: A human readable name for this AI. 1955 | :return: Nothing 1956 | """ 1957 | self.name = name 1958 | #print("Making AI:", name) 1959 | 1960 | def __str__(self): 1961 | """ 1962 | Returns a description of the artificial intelligence. 1963 | :return: The description. 1964 | """ 1965 | return self.name 1966 | 1967 | def get_strategy_object(self, x, a, tol): 1968 | """ 1969 | Returns the strategy object that can be run. 1970 | :param x: A point in the strategy. 1971 | :param a: How to bias the result. 1972 | :param tol: The absolute tolerance. 1973 | :return: A strategy object. 1974 | """ 1975 | #print("Making strategy_object") 1976 | # The strategy object. 1977 | return Strategy() 1978 | 1979 | def query(self, x, a, tol): 1980 | """ 1981 | Runs the AI and returns it's current strategy. 1982 | :param x: A point in the strategy. 1983 | :param a: How to bias the result. 1984 | :param tol: The absolute tolerance. 1985 | :return: The current AI strategy. 1986 | """ 1987 | #print("Making query") 1988 | # The strategy object. 1989 | strategy_object = self.get_str 1990 | ==================== 1991 | class AI: 1992 | """A class used to represent an artificial intelligence""" 1993 | def __init__(self): 1994 | self.testVector = [] 1995 | self.testVector.append('abc') 1996 | self.testVector.append('123') 1997 | self.testVector.append('xyz') 1998 | self.testVector.append('^#') 1999 | self.testVector.append('#{`') 2000 | self.testVector.append('#}') 2001 | self.testVector.append('{$`') 2002 | self.testVector.append('$}') 2003 | self.testVector.append('#`') 2004 | self.testVector.append('`' + '`') 2005 | self.testVector.append('#$' + '$') 2006 | self.testVector.append('$(`') 2007 | self.testVector.append('$)') 2008 | self.testVector.append('$}') 2009 | self.testVector.append('{${') 2010 | self.testVector.append('${`') 2011 | self.testVector.append('$}`') 2012 | self.testVector.append('#`${') 2013 | self.testVector.append('#`$`') 2014 | self.testVector.append('`#}$#') 2015 | self.testVector.append('${`{') 2016 | self.testVector.append('{``}') 2017 | self.testVector.append('${`' + '`}') 2018 | self.testVector.append('${`{' + '`})') 2019 | self.testVector.append('${``${`})') 2020 | 2021 | ==================== 2022 | -------------------------------------------------------------------------------- /ggplot2.txt: -------------------------------------------------------------------------------- 1 | library(ggplot2) 2 | 3 | p <- ggplot(dat, aes(x = m, y = n, col = 1:3)) + 4 | geom_point() + 5 | geom_point(col = 2) + 6 | theme_bw() + 7 | theme(legend.position = "none") 8 | 9 | print(p) 10 | 11 | produces: 12 | 13 | <|endoftext|>Q: 14 | 15 | boost::lexical_cast failure mode 16 | 17 | Please see the following code, how come it produces different results when I use either boost::lexical_cast() or boost::lexical_cast::lexical_cast(), the first one returns an error, while the second one produces 0? 18 | #include 19 | #include 20 | 21 | typedef double DATE; 22 | typedef double DATETIME; 23 | typedef long long TICK; 24 | typedef long long DOUBLE; 25 | typedef long long DATE_TIME; 26 | typedef unsigned long long DOUBLE_U; 27 | typedef unsigned long long DATE_U; 28 | typedef unsigned long long TICK_U; 29 | typedef unsigned long long DOUBLE_U_T; 30 | typedef unsigned long long DATE_U_T; 31 | typedef unsigned long long TICK_U_T; 32 | 33 | #define DOUBLE_FMT "%15.8e" 34 | #define DOUBLE_FMT_U "%15.8E" 35 | 36 | #define DOUBLE_EXP (1.0e-14) 37 | #define DOUBLE_UNIT_M ((1.0e-28) / ((DOUBLE_EXP) - (DOUBLE_UNIT_M))) 38 | 39 | #define DOUBLE_DST -(DOUBLE_UNIT_M) 40 | 41 | #define DOUBLE_MIN (-(DOUBLE_FMT_U) * DOUBLE_DST) 42 | ==================== 43 | library(ggplot2) 44 | library(shiny) 45 | 46 | sidePanel( 47 | textOutput("title"), 48 | verbatimTextOutput("body"), 49 | numericInput("input_val", "Select Item"), 50 | numericInput("input_scale", "Select scale"), 51 | numericInput("input_axis", "Select axis"), 52 | textInput("text_input", "Text input:", value = "") 53 | ) 54 | 55 | mainPanel( 56 | tabsetPanel( 57 | type = "tab", 58 | tabPanel("myPlot", verbatimTextOutput("myPlot")), 59 | tabPanel("myChart", verbatimTextOutput("myChart")) 60 | ) 61 | ) 62 | 63 | server <- function(input, output, session) { 64 | data <- data.frame( 65 | input_val = input$input_val, 66 | input_scale = input$input_scale, 67 | input_axis = input$input_axis, 68 | text_input = input$text_input 69 | ) 70 | 71 | # Create a function to draw a line from start to end points using patter map. 72 | draw_line <- function(start_val, end_val) { 73 | coord_1 <- c(c(0, 1), c(0, -1), c(1, 0), c(-1, 0)) 74 | coord_2 <- c(c(0, 1), c(0, -1), c(1, 0), c(-1, 0)) 75 | 76 | plot(coord_1, coord_2, col = "black", lwd = 1, xlim = c(-2, 2), ylim = c(-2, 2)) 77 | 78 | l <- lines(c(coord_1$x, coord_2$x), c(coord_1$y, coord_2$y)) 79 | segments(l, col = "black", lwd = 2) 80 | abline(a = coord_1$x, b = coord_1$y, lwd = 2, col = "red") 81 | abline(a = coord_2$x, b = coord_2$y, lwd = 2, col = "red") 82 | 83 | lines(c(start_val, 84 | ==================== 85 | library(ggplot2) 86 | 87 | ### > fliers@> fliers@> fliers@> fliers@> fliers@> 88 | 89 | count = 10 90 | trace_start = cumsum(runif(count)) 91 | trace_length = 10 92 | plot_hist <- ggplot(mpg, aes(class)) + geom_histogram() + facet_wrap(~cyl, ncol=3) 93 | trace = geom_vline(aes(xintercept=trace_start), colour="grey30") 94 | trace_median = geom_vline(aes(xintercept=median(trace_start)), colour="darkred") 95 | trace_mean = geom_vline(aes(xintercept=mean(trace_start)), colour="darkred") 96 | 97 | trace_stdev = geom_vline(aes(xintercept=sd(trace_start)), colour="darkred") 98 | trace_dev = geom_vline(aes(xintercept=dev(trace_start)), colour="darkred") 99 | 100 | trace_median = geom_vline(aes(xintercept=median(trace_start)), colour="darkred") 101 | trace_mean = geom_vline(aes(xintercept=mean(trace_start)), colour="darkred") 102 | trace_std = geom_vline(aes(xintercept=std(trace_start)), colour="darkred") 103 | trace_var = geom_vline(aes(xintercept=var(trace_start)), colour="darkred") 104 | trace_cor = geom_vline(aes(xintercept=cor(trace_start)), colour="darkred") 105 | 106 | if(trace_start == 0){ 107 | trace_var = geom_vline(aes(xintercept=var(1)), colour="darkred") 108 | } 109 | 110 | ### > fliers@> fliers@> fliers@> fliers@> fliers@> 111 | 112 | count = 10 113 | trace_start = cumsum(runif(count)) 114 | trace_length = 10 115 | trace_mean = c(3, 8.5, 4.25, 6.25, 4.50, 6.25, 8, 2.00, 7.00, 2.00, 116 | 117 | ==================== 118 | library(ggplot2) 119 | library(cowplot) 120 | 121 | data <- iris 122 | 123 | x <- c(1,2,3,4,5) 124 | y <- rep(1,5) 125 | z <- x 126 | 127 | df <- data.frame(x,y,z) 128 | 129 | z <- c("rose","violet","blonde","gold","freckle") 130 | 131 | p1 <- ggplot(df, aes(x=x,y=y)) + geom_point() 132 | 133 | p2 <- ggplot(df, aes(x=z)) + geom_bar(stat="identity") 134 | 135 | p3 <- ggplot(df, aes(x=factor(z))) + geom_bar(aes(fill=z)) 136 | 137 | p4 <- ggplot(df, aes(x=factor(z),y=y, color=z)) + geom_bar(aes(fill=z)) 138 | 139 | p4 <- p4 + labs(y="",x="",color="") 140 | 141 | p4 <- p4 + scale_x_continuous(breaks=NULL, labels=NULL) 142 | 143 | gridExtra::grid.arrange(p1,p2,p3,p4,ncol=2, 144 | top=grid::grid.triple( 145 | grid::textGrob(format(c(x,y,z)), rot = 0), 146 | grid::textGrob(format(c("x", "y", "z")), rot = 0), 147 | grid::textGrob(format(c(x,y,z)), rot = 0) 148 | ), 149 | right = grid::grid.rect( 150 | ==================== 151 | library(ggplot2) 152 | qplot(x = 5.3, y = 0.6, data = df_p, aes(x = ~round(x,0)))+ 153 | geom_point() 154 | 155 | So the question is, how to add the X value to each point, and how to give it the colour from another dataframe? I have tried with: 156 | df_p$X = df_lab$x 157 | 158 | And this results in the following error: 159 | Error in eval(expr, envir, enclos) : object 'x' not found 160 | 161 | So I don't think the x dataframe is accessible, however this does work: 162 | qplot(x = df_p$x, y = df_p$y, data = df_p, aes(x = ~round(x,0)))+ 163 | geom_point() 164 | 165 | And this creates a scatter plot using the raw X and y values in df_p, however I'd like to use df_lab as a colour palette for these points. 166 | Any suggestions as to how I can combine these two ideas would be appreciated! 167 | 168 | A: 169 | 170 | Is this what you want? 171 | The top plot is using df_p, and the bottom is using df_lab. 172 | ggplot(df_p, aes(x = x, y = y)) + 173 | geom_point() + 174 | geom_smooth() 175 | 176 | ggplot(df_lab, aes(x = x, y = y)) + 177 | geom_point() + 178 | geom_smooth() 179 | 180 | Alternatively, you can label each point using aes(label =..) if you'd like. In this case, your top plot would look like: 181 | ggplot(df_p, aes(x = x, y = y)) + 182 | geom_point(aes(label = x)) + 183 | geom_smooth() 184 | 185 | EDIT: 186 | Since you want to apply a color palette to the points based on the x value, we need to assign a column to the original dataframe, and color by that column. Something like: 187 | df_p$x = round(df_p$x, 0) 188 | 189 | ggplot(df_p, aes(x = x, y = y)) + 190 | geom_point(aes(label = x)) + 191 | ==================== 192 | library(ggplot2) 193 | 194 | ggplot(df_clean, aes(x=x, y=y, color=cls)) + 195 | geom_point() + 196 | facet_grid(cls ~., switch = "x", scales = "free_x") + 197 | scale_x_continuous(breaks = rev(c(1:25, Inf))) + 198 | scale_y_reverse() + 199 | theme(legend.position = "none") 200 | 201 | A: 202 | 203 | For a cleaner way to achieve the same result, you can use FacetGrid and coord_cartesian: 204 | df_clean$x <- as.factor(df_clean$x) 205 | 206 | ggplot(df_clean, aes(x=x, y=y, color=cls)) + 207 | geom_point() + 208 | facet_grid(x ~., scales = "free_x") + 209 | scale_x_continuous(breaks = rev(c(1:25, Inf))) + 210 | scale_y_reverse() + 211 | theme(legend.position = "none") 212 | 213 | There is a graphical downside, that the first point of x and the last point of y is not connected. 214 | 215 | A: 216 | 217 | In addition to the other answers, you can also have the x-axis be reversed by setting the position parameter of geom_point to position_stack(). The x axis will be reversed so that the first value is at the top (or bottom) of the plot. 218 | ggplot(df_clean, aes(x=x, y=y, color=cls)) + 219 | geom_point(position=position_stack(reverse=T)) + 220 | facet_grid(cls ~., switch = "x", scales = "free_x") + 221 | scale_x_continuous(breaks = rev(c(1:25, Inf))) + 222 | scale_y_reverse() + 223 | theme(legend.position = "none") 224 | 225 | If you were to change the color and scale the second color to NA, and you want the x-axis to still be reversed you would need to use the unscale function to set the initial position of the scale. 226 | ggplot(df_clean, aes(x=x, y=y, color=cls)) + 227 | geom 228 | ==================== 229 | library(ggplot2) 230 | library(plyr) 231 | library(RColorBrewer) 232 | set.seed(123) 233 | 234 | # Data 235 | df <- data.frame(country = c("United States", "Mexico", "Mexico", "United States", "China"), 236 | crime = c(5,3,3,2,2), 237 | var_1 = rnorm(5,3,2), 238 | var_2 = rnorm(5,2,1)) 239 | 240 | # Layout 241 | df <- ddply(df,.(country), transform, var_1 = factor(var_1, levels = c(0,1)), 242 | var_2 = factor(var_2, levels = c(0,1))) 243 | 244 | # Heatmap 245 | p <- ggplot(df, aes(x = country, y = country)) + 246 | geom_tile(aes(fill =..level..), colour = "white", width =.5) + 247 | facet_wrap(~crime, scales = "free_x") + 248 | scale_fill_gradient(low = "red", high = "blue") 249 | p <- p + coord_equal(ylim = c(0,4)) 250 | p <- p + labs(title = "Crime by Country") 251 | p <- p + theme(axis.text.x = element_text(angle = 30, hjust = 1)) 252 | p <- p + theme(axis.title.y = element_text(size = 20)) 253 | print(p) 254 | 255 | A: 256 | 257 | i would probably use geom_hexbar (with coord_equal). It's easier to understand the resulting graphs when bars aren't plotted as lines 258 | library(ggplot2) 259 | library(plyr) 260 | library(RColorBrewer) 261 | set.seed(123) 262 | 263 | # Data 264 | df <- data.frame(country = c("United States", "Mexico", "Mexico", "United States 265 | ==================== 266 | library(ggplot2) 267 | library(data.table) 268 | library(dplyr) 269 | 270 | #create dataframe to analyse 271 | Calls = data.frame(ID = c(1:15), 272 | Day = c(rep(1:7, 2), rep(8, 5), rep(9, 3)), 273 | Country = c("Hrvatska", "Hrvatska", "Hrvatska", 274 | "Hrvatska", "Hrvatska", "Hrvatska", "Hrvatska", 275 | "Hrvatska", "Hrvatska", "Hrvatska", "Hrvatska", 276 | "Hrvatska", "Hrvatska", "Hrvatska", "Hrvatska"), 277 | Hrvatska = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 278 | 2), 279 | Croatia = c(20, 15, 20, 20, 25, 20, 25, 25, 25, 25, 280 | 25, 25, 25, 25, 25, 25, 25, 25), 281 | Calls = c(4, 10, 17 282 | ==================== 283 | library(ggplot2) 284 | 285 | # Do this plot with ggplot2 in R 286 | 287 | p1 <- ggplot(de_usa, aes(country, GDP)) + geom_bar(aes(fill = state)) 288 | p2 <- ggplot(world, aes(continent, population)) + geom_bar(aes(fill = country)) 289 | p3 <- ggplot(de_usa, aes(state, GDP)) + geom_bar(aes(fill = continent)) 290 | 291 | ggsave("example.png", p1) 292 | ggsave("example2.png", p2) 293 | ggsave("example3.png", p3) 294 | 295 | A: 296 | 297 | There's no need for R. 298 | Simply download the plot to your computer, save the PNG, and then open it in your favourite software. 299 | 300 | A: 301 | 302 | If you don't want to save the plot, there is an online service that will allow you to make your own website using plots made in R. You can create a web based ggplot2 app by installing the Rserv package and then using the plot_app package to generate the graphic and then use Rserv::render_plot to return it to a static HTML file. 303 | You can find more information on that here: 304 | http://ggplot2.yihui.org/gallery/r-app/ 305 | Hope that helps! 306 | 307 | A: 308 | 309 | You can use any plotting library to do this. There is no inherent order with different plots, but you can certainly reference the same x,y coordinates to place them next to each other. One potential solution would be a package like the highcharter library. 310 | 311 | <|endoftext|>Q: 312 | 313 | Is there a good/old school linux package for getting down and dirty with the math library 314 | 315 | I am working on a small hobby project and I need to be able to get a large number of the properties of vector2D, vector3D, matrix and quaternion. 316 | is there a package I can include in my projects that provides access to that library? 317 | 318 | A: 319 | 320 | There are some things that QVector3D and such are useful for. 321 | The biggest problem I had with trying to use the data type names of C++ is the lack of typedefs, enums and template implementation. 322 | With one of the typedefs I created, I used the printf() format function and an enum. 323 | 324 | ==================== 325 | library(ggplot2) 326 | 327 | ggplot(df_1, aes(x = ID, y = pop, col = cv1, shape = cv1, fill = cv1)) + 328 | geom_polygon(color = "black") + 329 | geom_path(colour = "red") + 330 | scale_x_continuous(limits = c(1, 12), breaks = c(seq(1, 12, by = 5))) + 331 | scale_y_continuous(limits = c(0, 100), breaks = c(seq(0, 100, by = 10))) + 332 | geom_polygon(colour = "black", fill = "lightblue", size = 2.5) + 333 | geom_path(colour = "blue", size = 0.5) + 334 | coord_cartesian(ylim = c(0, 100), expand = FALSE) + 335 | theme(axis.text.x = element_blank(), 336 | axis.ticks = element_blank()) + 337 | geom_text(aes(label = pop, y = pop, color = "red"), data = df_1) 338 | 339 | Data: 340 | df_1 <- data.frame(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 341 | pop = c(50, 40, 30, 20, 10, 5, 2, 1, 0, 30, 40, 50), 342 | cv1 = c(1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1), 343 | cv2 = c(0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0), 344 | cv3 = c(0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 345 | ==================== 346 | library(ggplot2) 347 | library(gridExtra) 348 | 349 | data(amplified, package='ggplot2') 350 | 351 | # Make sure that we can run your plot code from a plaintext file (e.g., from 352 | # the R console). 353 | # https://r-forge.r-project.org/projects/sf/.github/ISSUE-84 354 | knitr::write_chunk('\n\n') 355 | 356 | ggplot(amplified, aes(x = Yeast, y = Yeast, size = number, color = strain, fill = group)) + 357 | geom_density() + 358 | coord_equal() + 359 | theme_bw() 360 | 361 | # You can use "ggdraw" as well: 362 | 363 | # Create a graph that includes labels at data points: 364 | ggplot(amplified, aes(x = Yeast, y = Yeast, size = number, color = group)) + 365 | geom_density() + 366 | coord_equal() + 367 | theme_bw() + 368 | ggdraw( 369 | ggplot(amplified, aes(x = Yeast, y = Yeast, size = number, color = group)) + 370 | geom_density() + 371 | coord_equal() + 372 | theme_bw() 373 | ) 374 | 375 | # But you should probably make a named vector of widths for nicer, cleaner 376 | # use of facet_grid() below. 377 | 378 | # Now generate some larger graphs, each with a slightly different, fixed width. 379 | 380 | mywidths = c(1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2) 381 | 382 | ggplot(amplified, aes(x = Yeast, y = Yeast, size = number, color = group)) + 383 | geom_density() + 384 | coord_equal() + 385 | theme_bw() + 386 | ggdraw( 387 | ggplot(amplified, aes(x = Yeast, y = Yeast, size = number, color = group)) + 388 | 389 | ==================== 390 | library(ggplot2) 391 | theme_set(theme_gray()) 392 | 393 | p <- ggplot(mtcars, aes(x = mpg, y = cyl)) + 394 | geom_point() + 395 | facet_wrap(~cyl, ncol = 2) 396 | p 397 | 398 | A: 399 | 400 | You need to adjust your dataset to start at 4, 401 | # modify factor columns, 402 | mtcars$cyl = factor(mtcars$cyl, levels = 4:6) 403 | # add row numbers, 404 | mtcars = data.frame( 405 | mpg = mtcars$mpg, 406 | cyl = mtcars$cyl, 407 | row.names = NULL) 408 | # reorder factor levels 409 | levels(mtcars$cyl) = factor(levels(mtcars$cyl), 410 | levels = c(4, 5, 6)) 411 | 412 | Now the plot should work: 413 | ggplot(mtcars, aes(x = mpg, y = cyl)) + 414 | geom_point() + 415 | facet_wrap(~cyl, ncol = 2) 416 | 417 | <|endoftext|>The 24-Hour Visual Effect of Clobazam (CLO) and Levetiracetam (LEV) on Intracranial Pressure in Acute Meningitis in the Presence of Seizures: A Retrospective Analysis of the Brain Intensive Care Monitoring in Intensive Care (Bimic) Database. 418 | A total of 47 episodes of acute meningitis with seizure activity treated with clobazam and levetiracetam were identified from the Brain Intensive Care Monitoring in Intensive Care (Bimic) database. Patient demographics, management, and intracranial pressure (ICP) data were recorded. Patient outcomes were determined using survival at 6 months and discharge. Subgroup analysis of the data was performed for those with intracranial hypertension and those not meeting criteria for intracranial hypertension at baseline. Twenty-three patients had intracranial hypertension at presentation. In these patients, at 24-hour evaluation, the median ICP value was reduced significantly from 15.9 to 12.5 (p = 0.005), and the median maximum diastolic blood pressure from 45 to 35 mm Hg (p = 0.0005). In patients not meeting criteria for intr 419 | ==================== 420 | library(ggplot2) 421 | library(plotly) 422 | library(jsonlite) 423 | 424 | df <- jsonlite::fromJSON(file.choose()) 425 | df$df <- 1:nrow(df) 426 | 427 | # Function to create HTML files, convert data from data.frame to data.table, 428 | # and convert JSON to DataTable 429 | 430 | create.html <- function(df, plot, options,...) { 431 | pdf(paste(plot, ".pdf", sep=""), onefile=FALSE) 432 | html = html_nodes(htmltools::bundle_html(plot_ly(...)), ".lyjs-container") 433 | p <- plot_ly(...) 434 | p <- p + xlim <- xlims <- make_plot_lims(p, options) 435 | i <- html[sapply(html, function(x) attr(x, "id")) == "dfPlot", ] 436 | html[i] <- sprintf(" 437 | 438 | 439 | 440 | 441 | 442 |
Time in minutesError probability
443 | ", html = html[i]) 444 | 445 | html <- html + plot + sprintf("%s
", 446 | html = c( 447 | html = html, 448 | sprintf( 449 | " %s", 450 | html = sprintf(" %s 451 | ==================== 452 | library(ggplot2) 453 | library(geometry) 454 | library(plyr) 455 | library(lattice) 456 | 457 | png("Stack_Conf_Plot.png") 458 | ggplot(Plotdata, aes(x=PlotType, y=Confusion)) + geom_jitter() + 459 | facet_grid(.~time) + 460 | stat_summary(fun.y="percent", geom="text", position=position_dodge(width=0.3), 461 | aes(label=..y..), size=2) + 462 | scale_y_continuous(breaks=c(0.3, 0.5, 0.7, 0.9, 1)) + 463 | geom_text_repel(aes(y=0.5, label=ifelse(..y..>0.5,"$\%$", "")), 464 | data=Plotdata, hjust=0.3, nudge_y = -0.2) 465 | dev.off() 466 | 467 | png("Stack_Conf_Plot_big.png") 468 | ggplot(Plotdata, aes(x=PlotType, y=Confusion)) + geom_jitter() + 469 | facet_grid(.~time) + 470 | stat_summary(fun.y="percent", geom="text", position=position_dodge(width=0.3), 471 | aes(label=..y..), size=2) + 472 | scale_y_continuous(breaks=c(0.3, 0.5, 0.7, 0.9, 1)) + 473 | geom_text_repel(aes(y=0.5, label=ifelse(..y..>0.5,"$\%$", "")), 474 | data=Plotdata, hjust=0.3, nudge_y = -0.2) + 475 | theme(legend.position="none") 476 | dev.off() 477 | 478 | The results look like this: 479 | 480 | If I go for a separate plot, like in this SO question, I 481 | ==================== 482 | library(ggplot2) 483 | 484 | p <- ggplot(data, aes(x, y)) + geom_point() 485 | p 486 | 487 | p <- p + theme_bw() 488 | p 489 | 490 | p <- p + labs(x = "", y = "") 491 | p 492 | 493 | p <- p + theme(panel.margin = unit(0, "in")) 494 | p 495 | 496 | p <- p + theme(panel.margin = unit(0.1, "cm")) 497 | p 498 | 499 | p <- p + theme(panel.margin = unit(0.1, "cm")) 500 | p 501 | 502 | 503 | p <- p + theme(panel.margin = unit(0.1, "cm")) 504 | p 505 | 506 | p <- p + theme(panel.margin = unit(0.1, "cm")) 507 | p 508 | 509 | 510 | p <- p + theme(panel.margin = unit(0.1, "cm")) 511 | p 512 | 513 | p <- p + theme(panel.margin = unit(0.1, "cm")) 514 | p 515 | 516 | p <- p + theme(panel.margin = unit(0.1, "cm")) 517 | p 518 | 519 | 520 | p <- p + theme(panel.margin = unit(0.1, "cm")) 521 | p 522 | 523 | 524 | p <- p + theme(panel.margin = unit(0.1, "cm")) 525 | p 526 | 527 | p <- p + theme(panel.margin = unit(0.1, "cm")) 528 | p 529 | 530 | p <- p + theme(panel.margin = unit(0.1, "cm")) 531 | p 532 | 533 | p <- p + theme(panel.margin = unit(0.1, "cm")) 534 | p 535 | 536 | 537 | p <- p + theme(panel.margin = unit(0.1, "cm")) 538 | p 539 | 540 | p <- p + theme(panel.margin = unit(0.1, "cm")) 541 | p 542 | 543 | p <- p + theme(panel.margin = unit(0.1, "cm")) 544 | p 545 | 546 | p <- p + theme(panel.margin = unit(0.1, "cm")) 547 | p 548 | 549 | 550 | p <- p + theme(panel.margin = unit(0.1, "cm")) 551 | p 552 | 553 | p <- p + theme(panel.margin = unit(0.1, "cm")) 554 | p 555 | 556 | p <- p + theme(panel.margin = unit(0.1, "cm")) 557 | ==================== 558 | library(ggplot2) 559 | 560 | Lp <- rnorm(100, 5, 2) 561 | La <- rnorm(100, 8, 2) 562 | 563 | cbind(Lp, La) 564 | 565 | barplot(cbind(Lp, La), beside=T) 566 | 567 | abline(v=3, col="blue") 568 | abline(v=5, col="blue") 569 | abline(v=7, col="blue") 570 | abline(v=9, col="blue") 571 | 572 | Here's the picture 573 | 574 | I'd like to overlay all these curves over a barplot using ggplot2. In my example there are three. How do I overlay them? 575 | 576 | A: 577 | 578 | We can just change the y-axis in the barplot to share the axis with the three lines. We will then get the following plot with all three lines shown on the y-axis. 579 | ggplot() + 580 | geom_bar(data=cbind(Lp, La), aes(x=Lp, y=La, fill=as.factor(Vary))) + 581 | theme_bw() + 582 | labs(x = "Pillars", y = "Price", fill = "Green", title = "Price Variation") + 583 | scale_y_continuous(breaks = seq(0, 10, by=2)) + 584 | coord_flip() 585 | 586 | A: 587 | 588 | ggplot() + 589 | geom_bar(data=cbind(Lp, La), aes(x=Lp, y=La, fill=as.factor(Vary))) + 590 | scale_y_continuous(limits=c(0,10)) + 591 | theme_bw() + 592 | labs(x = "Pillars", y = "Price", fill = "Green", title = "Price Variation") + 593 | coord_flip() 594 | 595 | A: 596 | 597 | I find it easier to plot with a facet. 598 | First I created the data: 599 | Lp <- rnorm(100, 5, 2) 600 | La <- rnorm(100, 8, 2) 601 | df <- data.frame(cbind(Lp, La)) 602 | df$Vary <- as.factor(1:3) 603 | 604 | library(ggplot2) 605 | library(ggbeeswarm) 606 | 607 | ggplot(df, aes(x=L 608 | ==================== 609 | library(ggplot2) 610 | library(tidyverse) 611 | 612 | dat = structure(list(x = c(75.125, 72.5, 67.5, 70.0, 78.125, 77.5, 613 | 72.75, 72.25, 75.5, 72.875, 71.875, 74.125, 70.5, 73.125, 614 | 75.375, 73.5, 76.125, 77.875, 77.125, 74.25, 76.5, 78.375, 615 | 76.875, 73.5, 74.5, 75.5, 75.125, 75.375, 75.625, 75.875, 76.125, 616 | 76.375, 76.5, 77.125, 75.125, 75.125, 75.875, 78.125, 77.375, 617 | 76.5, 78.5, 75.375, 78.125, 79.5, 78.375, 79.5, 79.375, 79.5, 618 | 79.125, 80.5, 80.875, 80.375, 80.375, 80.375, 80.375, 80.5, 619 | 81.25, 80.875, 79.5, 81.75, 80.125, 81.375, 80.125, 80.5, 82.25, 620 | 82.75, 82.375, 82.5, 83.125, 82.375, 83.5, 83.875, 82.875, 83.75, 621 | 83.5, 83.25, 84.5, 84.875, 84.5, 84.875, 85.125, 84.75, 84.125, 622 | 84.875, 83.875, 84.875, 85.125, 85.75, 85.875, 85.75, 86.125, 623 | 85.125, 85.125, 84.375, 85.125, 86.125, 85.75, 85.75, 87.125, 624 | 85.125, 86.125, 87.5, 87.375, 86.75, 86.875, 87.125, 87.125, 625 | 85.75, 85.5, 86.75, 86.875, 85.875, 86.75, 87.5, 87.375, 86.875, 626 | 85 627 | ==================== 628 | library(ggplot2) 629 | 630 | d1 <- data.frame(Year = c(1990, 1991, 1992, 1993, 1994, 1995, 1996, 631 | 1997, 1998, 1999), Value = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) 632 | d2 <- data.frame(Year = c(1990, 1991, 1992, 1993, 1994, 1995, 1996, 633 | 1997, 1998, 1999), Value = c(3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) 634 | 635 | ggplot(d1, aes(Year, Value, col = Year)) + 636 | geom_line() + 637 | facet_grid(~Year) + 638 | theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) 639 | 640 | ggplot(d1, aes(Year, Value, col = Year)) + 641 | geom_line() + 642 | facet_grid(~Year) + 643 | theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) 644 | 645 | The first ggplot works fine, but the second one (with the loop) gets an error message: 646 | Warning message: 647 | "Positioning outside the plotting region 648 | is forbidden for facetted plotting (facet_grid) 649 | " 650 | 651 | Why? I want to fill in the second plot with more years. 652 | 653 | A: 654 | 655 | If I understood your question, what you want is to add the Year information of the both data frames: 656 | library(dplyr) 657 | df2 <- bind_rows(d2, d1) 658 | df2 659 | # Year Value 660 | # 1 1990 3 661 | # 2 1991 4 662 | # 3 1992 5 663 | # 4 1993 6 664 | # 5 1994 7 665 | # 6 1995 8 666 | # 7 1996 9 667 | # 668 | ==================== 669 | library(ggplot2) 670 | library(plyr) 671 | 672 | scatter_fun <- function(dd) { 673 | dat <- dd[names(dd) == "Response"] 674 | if (is.null(names(dat)) | is.na(names(dat))) { 675 | names(dat) <- sub("^[A-Z]+_", "", names(dat)) 676 | } 677 | 678 | df <- do.call(rbind, dd[1:(nrow(dd)-1)]) 679 | column.order <- order(factor(colnames(df), levels = c("Yes", "No", "Undecided"))) 680 | column.name <- sub("^.+_", "", column.order) 681 | df$group <- sub("[A-Z]$", "", colnames(df)) 682 | 683 | ggplot(data = df, aes_string(x = column.name, y = group, fill = yes)) + 684 | geom_col(position = "dodge") + 685 | scale_y_discrete(limits = c("Yes", "No", "Undecided")) + 686 | labs(fill = NULL) + 687 | labs(x = NULL) 688 | } 689 | 690 | YesNoUndecided <- t(scatter_fun(dd)) 691 | 692 | ggplot(YesNoUndecided, aes(x = "Undecided", y = "Yes", fill = "Yes")) + 693 | geom_col() + 694 | scale_fill_discrete("Yes") + 695 | labs(fill = "", x = NULL) 696 | 697 | So, for all names which end with _, remove the first part of the name. Then order the new column by the new column name, and reset the names of the new column to the new name. 698 | This should work for your data (but I haven't tested it). 699 | 700 | <|endoftext|>This invention is generally in the field of adjustable beds and specifically is a two section adjustable bed that is easily convertible between a sleep mode and a seating mode. 701 | Most two section adjustable beds are only usable in one mode or the other. U.S. Pat. No. 4,906,918, dated Mar. 6, 1990, shows a dual mode bed that can convert between a seating mode and a sleeping mode. The body of the patient is supported on a center platform pivotally connected to two side 702 | ==================== 703 | library(ggplot2) 704 | library(dplyr) 705 | library(magrittr) 706 | library(sf) 707 | 708 | flights <- flights %>% 709 | group_by(Origin) %>% 710 | mutate(Dest = tail(Destination, 1)) %>% 711 | select(-Destination) 712 | 713 | ## here is how you can select specific fields 714 | flights %>% 715 | group_by(Origin) %>% 716 | mutate(Dest = tail(Destination, 1)) %>% 717 | select(Origin, Dest) 718 | 719 | <|endoftext|>Razorbill" Lopsided Headache (1948) 720 | "Sleeping Beauty" (1948) 721 | "Phantom of the Opera" (1948) 722 | "Beauty and the Beast" (1948) 723 | "Wild Kitty" (1948) 724 | "The Belle of New Orleans" (1949) 725 | "Heaven's Witness" (1949) 726 | "An Act of Justice" (1950) 727 | "Stardust" (1950) 728 | "The Lady of Diamond Hill" (1950) 729 | "Christmas with the Cat Family" (1951) 730 | "Dignity" (1951) 731 | "The Lone Ranger Rides Again" (1951) 732 | "Cattle Raiders" (1952) 733 | "Beauty Rides" (1952) 734 | "The Pet of Beauty" (1952) 735 | "The Golden Girl" (1952) 736 | "Mom and Dad (1953) 737 | "The Biggest Partner" (1953) 738 | "Torch Song" (1953) 739 | "Best Friend for a Lifetime" (1953) 740 | "My Secret Life" (1954) 741 | "In Her Image" (1954) 742 | "The Vagabond" (1954) 743 | "The Lucky Stiff" (1955) 744 | "The Uncle Tom's Uncle" (1955) 745 | "Zorro Rides Again" (1956) 746 | "The Incredible Donny" (1956) 747 | "The Best of Everything" (1957) 748 | "The Black Arrow" (1957) 749 | "The Mission" (1957) 750 | "Madman of the Family" (1957) 751 | "Showdown at Abilene" (1958) 752 | "The Bad Man" (1958) 753 | "Brute Force" (1958) 754 | "Pit Stop" (1959) 755 | " 756 | ==================== 757 | library(ggplot2) 758 | library(geom_tile) 759 | 760 | ggplot(long.df, aes(x = longitude, y = latitude, size = `Count of Function`)) + 761 | geom_tile(colour = "black", fill = "white") + 762 | scale_size(range = c(0.05, 0.5)) + 763 | theme_minimal() + 764 | geom_point(aes(color = `Week of Life Cycle`), 765 | show.legend = FALSE) + 766 | scale_color_brewer(palette = "Dark2") 767 | 768 | Note that a continuous scale was plotted for the size variable as well to be able to see a more accurate overlap between the smaller (and closer together) squares on the left and the larger (and further apart) squares on the right. This of course leads to discontinuity when you get to your limits. However, using a range limited scale will still allow us to see, for example, that our maximum square at the far right does have some overlap with the other three. 769 | One way of getting around this is to subset your data (long.df <- long.df[5:500]) as in @yorkosh's answer, or just using a multiple palette like "winter" instead of "Dark2" (to avoid the discontinuity) but using scale_size_continuous, which would make each square exactly the same size as its neighbors and has a continuous plot where the other two methods would have a discontinuity, for example, or even the dreaded checkerboard patterns that can happen. 770 | Another option is to use stat_size_gradient() in the lattice package, although this does mean you have to hardcode some colors, and you can't use the map aesthetic. 771 | ggplot(long.df, aes(x = longitude, y = latitude, size = `Count of Function`)) + 772 | stat_size_gradient(colors = brewer.pal(n = 2, "RdBu")) + 773 | geom_tile(colour = "black", fill = "white") + 774 | scale_size(range = c(0.05, 0.5)) + 775 | theme_minimal() + 776 | geom_point(aes(color = `Week of Life Cycle`), 777 | 778 | ==================== 779 | library(ggplot2) 780 | library(shiny) 781 | library(shinydashboard) 782 | library(shinyjs) 783 | library(shinythemes) 784 | 785 | ui <- navbarPage( 786 | title = "", 787 | tabPanel("", 788 | "", 789 | "", 790 | mainPanel( 791 | box(solidHeader(title = "Server Logic", solidHeader = T, 792 | width = 12, background = 'white')), 793 | sidebarLayout( 794 | sidebarPanel( 795 | helpText("", "Click here to see me"), 796 | sliderInput("width", "Width:", min = 5, max = 50, value = 5, step = 1), 797 | radioButtons("radio", "Pick a type of legend:", c("box", "line", "area"), inline=T, selected="box") 798 | ), 799 | mainPanel( 800 | verbatimTextOutput("text"), 801 | uiOutput("legend") 802 | ) 803 | ) 804 | ) 805 | ) 806 | 807 | server <- function(input, output) { 808 | output$text <- renderText({ 809 | input$radio 810 | }) 811 | 812 | output$legend <- renderUI({ 813 | switch(input$radio, 814 | "box" = div(style = "width:500px;height: 815 | ==================== 816 | library(ggplot2) 817 | 818 | I'm quite new to this so feel free to correct my mistakes :) 819 | So, what I'm trying to do is to make some pretty graphs for my thesis work with ggplot2. 820 | So, what I have is: 821 | 1) A vector of 0/1's (dates) 822 | 2) Another vector of 0/1's (co-data), in this case an raster of the same area. 823 | The problem is, that if I want to have a line plot, the only way to get the raster to show up is by overlaying it with the first vector, or simply by stacking it on top of the vector, as in this case: 824 | +---------------------------------+ 825 | | + 1 vector layer | 826 | | | + 2 raster layers | 827 | | +---------------------------------+ 828 | 829 | I guess this is the effect of the legend on my scale, but I can't understand how to add it, if it's possible at all. 830 | Furthermore, I would like to assign a variable to each co-data point, but this does not work, as in the following: 831 | +---------------------------------+ 832 | | + 1 vector layer | 833 | | | + 2 raster layers | 834 | | | | <- Variable per point | 835 | | +---------------------------------+ 836 | 837 | The point is, that for each co-data point, I have one variable which I need to use on the plot (i.e., an additional variable should appear next to the raster as well, and not under the point itself). 838 | Can anyone help? I have been reading and searching for about 5 hours now, but I don't seem to get anywhere... :s 839 | 840 | A: 841 | 842 | On the flipside, what does your vector look like? If you only have a data.frame with dates, I'd imagine you'd need to adjust your vector layer to be points. 843 | It appears that your dates and raster layer are in separate data frames. The first two are as you show them. The third is dates <- data.frame(date = mydates), while raster 844 | ==================== 845 | library(ggplot2) 846 | data(mtcars) 847 | ggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point() + 848 | geom_text_repel(aes(label = rownames(mtcars)), nudge_y = 0) + 849 | scale_x_discrete(limits = c("Dodge Dart", "Ram Charger", "Ford Escort")) + 850 | scale_y_discrete(limits = c("14.1", "13.9", "14.7")) + 851 | guides(colour = guide_legend(title = ""), size = guide_legend(title = "")) 852 | 853 | # Create a legend 854 | library(scales) 855 | legend <- add_legend(ggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point() + 856 | geom_text_repel(aes(label = rownames(mtcars)), nudge_y = 0) + 857 | scale_x_discrete(limits = c("Dodge Dart", "Ram Charger", "Ford Escort")) + 858 | scale_y_discrete(limits = c("14.1", "13.9", "14.7")) + 859 | guides(colour = guide_legend(title = ""), size = guide_legend(title = "")), 860 | "Legends as Points", # Doesn't work in ggplot2, not sure why. 861 | ncol = 3) 862 | 863 | # Set position 864 | legend$position <- "left" 865 | 866 | # Set text 867 | legend$horizontal <- TRUE 868 | legend 869 | ==================== 870 | library(ggplot2) 871 | ggplot(df.merge.all,aes(x=YEAR,y=value,colour=variable)) + 872 | geom_line()+ 873 | geom_point() + 874 | scale_y_continuous(breaks=seq(0,5,by=1),limits=c(0,5)) + 875 | coord_cartesian(xlim = range(df.merge.all$YEAR)) 876 | 877 | Thanks! 878 | 879 | A: 880 | 881 | If you don't mind geom_segment, that's the easiest way. 882 | ggplot(df.merge.all,aes(x=YEAR,y=value,colour=variable)) + 883 | geom_segment(aes(xend=YEAR,yend=value)) + 884 | geom_point() + 885 | scale_y_continuous(breaks=seq(0,5,by=1),limits=c(0,5)) + 886 | coord_cartesian(xlim = range(df.merge.all$YEAR)) 887 | 888 | <|endoftext|>You have the option of using a search engine that will show you a search for things, like Google or Bing, or you can search directly on Amazon by using the URL http://www.amazon.com/b?node=905059201. 889 | 890 | Search Amazon 891 | 892 | Garden Weed Infestation 893 | 894 | How to control weeds in the garden? For someone like me who has only just started gardening, the number of seeds that need to be removed is just too many. Weed seeds are everywhere! In fact, I have found them in everything that I touch, even in the couch in my house. I have watched YouTube videos on how to rid the garden of unwanted weeds but this is not practical, especially when I’m having a party. This is exactly why I created the Gardening Tips & Tricks series. My goal is to be as helpful to those who are still new to the world of gardening. 895 | 896 | Today’s video is all about controlling garden weeds! We have reviewed the best weed killer that kills all weeds at the first pass! We will review what is currently available in the market and I will be sharing my own recommendations for those who still do not know what kind of weed killer is right for them. 897 | 898 | If you are on YouTube, 899 | ==================== 900 | library(ggplot2) 901 | # 902 | 903 | # A single entity. 904 | class Person 905 | name = 906 | 907 | ==================== 908 | library(ggplot2) 909 | 910 | df <- data.frame( 911 | grp1 = rep(1:6, 2), 912 | grp2 = rep(1:6, each = 4), 913 | fac = rep(1:2, 6), 914 | rank = rep(1:4, 6) 915 | ) 916 | 917 | ggplot(df, aes(factor(grp1), factor(grp2))) + 918 | geom_text(aes(x = 2.6, y = 1.2, label = fac), color = 'black') + 919 | geom_text(aes(x = 2.7, y = 1.2, label = fac), color = 'black') + 920 | geom_text(aes(x = 3.1, y = 1.2, label = fac), color = 'black') + 921 | geom_text(aes(x = 3.2, y = 1.2, label = fac), color = 'black') + 922 | geom_text(aes(x = 4.3, y = 1.2, label = fac), color = 'black') + 923 | geom_text(aes(x = 4.4, y = 1.2, label = fac), color = 'black') + 924 | geom_text(aes(x = 5.5, y = 1.2, label = fac), color = 'black') + 925 | geom_text(aes(x = 5.6, y = 1.2, label = fac), color = 'black') + 926 | geom_text(aes(x = 6.9, y = 1.2, label = fac), color = 'black') + 927 | scale_x_continuous(expand = c(0, 0), breaks = 2.6:6.9, 928 | labels = c('#1', '#2')) 929 | 930 | A: 931 | 932 | Something like this: 933 | ggplot(df, aes(factor(grp1), factor(grp2))) + 934 | geom_text(aes(x = 2.6, y = 1.2, label = fac, colour = "black"), size = 5, hjust = -.2) 935 | ==================== 936 | library(ggplot2) 937 | library(ggpubr) 938 | 939 | #**############################################################################ 940 | # SYMBOL RENAMING TASK: Update the font names and colors for chl-a and turb 941 | #**############################################################################ 942 | 943 | symbol.rename <- function(var, symbol, color.turb, alpha) { 944 | m <- enquo(symbol) 945 | symbol <- enquo(symbol) 946 | color <- enquo(color.turb) 947 | alpha <- enquo(alpha) 948 | names(var) <- m 949 | var <- setNames(lapply(var, function(name) { 950 | if (symbol == name) { 951 | attr(name, "default") <- color 952 | } else { 953 | attr(name, "default") <- "" 954 | } 955 | name 956 | }), m) 957 | if (alpha!= 0) { 958 | attr(var, "default.alpha") <- alpha 959 | } else { 960 | attr(var, "default.alpha") <- 1 961 | } 962 | var 963 | } 964 | 965 | # plot symbols: chl-a and turb 966 | qc_opt <- sym_update(method = "opt", theme = "white", 967 | opt_palette = "CYMK_1.4", text = "qc") 968 | 969 | plot_opt <- sym_update(symbol = "chl-a", method = "opt", 970 | theme = "white", opt_palette = "CYMK_1.4", 971 | color = "default") 972 | 973 | plot_opt <- sym_update(symbol = "turb", method = "opt", 974 | theme = "white", opt_palette = "CYMK_1.4", 975 | color 976 | ==================== 977 | library(ggplot2) 978 | library(gridExtra) 979 | 980 | # set theme 981 | theme_set(theme_bw()) 982 | 983 | # data and colours 984 | data <- data.frame(x = rnorm(100), y = rnorm(100), z = factor(c(1,2,3))) 985 | cols <- c("red", "orange", "green") 986 | 987 | # helper to create scale 988 | # generate colour map 989 | colscale <- function(...) { 990 | ncol(.data) 991 | } 992 | 993 | # helper to make geomscale() work 994 | scale_fill <- function(...) { 995 | .data 996 | } 997 | 998 | # how to make scale_fill_manual() work? 999 | geomscale <- function(...) { 1000 | .data 1001 | } 1002 | 1003 | # Here's the test 1004 | grid.arrange( 1005 | ggplot(data, aes(x, y, fill = z)) + 1006 | geom_tile() + 1007 | scale_fill_manual(name = "my scale", values = cols), 1008 | ggplot(data, aes(x, y, fill = z)) + 1009 | geom_tile() + 1010 | scale_fill_manual(name = "my scale", values = cols, 1011 | guide = guide_colorbar(name = "my scale", 1012 | direction = "horizontal")) + 1013 | scale_color_discrete(name = "my scale", guide = guide_legend()) + 1014 | theme_bw() + 1015 | scale_fill_continuous(guide = FALSE) 1016 | ) 1017 | 1018 | A: 1019 | 1020 | geom_tile() does not support the style argument; it is a standard tile. Since the issue seems to be having an unfilled circle, and then getting an unannotated color, you should be able to just add... + scale_fill_manual(values = cols, guide = guide_colorbar()) inside of scale_fill_manual(values = cols, name = "my scale"). 1021 | 1022 | <|endoftext|> 1023 | ==================== 1024 | library(ggplot2) 1025 | df1 <- data.frame(Team = c("Ind", "Ind", "Ind", "Ind", "Ind", "Ind", "Ind", "Ind", "Ind"), 1026 | 1027 | ==================== 1028 | library(ggplot2) 1029 | library(plyr) 1030 | 1031 | fitter_A_2 <- function(df, name, title) { 1032 | 1033 | # data frame of all metabolites detected in milk in a longitudinal study 1034 | 1035 | M_ol <- data.frame( 1036 | month.1 = character(), 1037 | month.2 = character(), 1038 | month.3 = character(), 1039 | month.4 = character(), 1040 | month.5 = character(), 1041 | month.6 = character(), 1042 | month.7 = character(), 1043 | month.8 = character(), 1044 | month.9 = character(), 1045 | month.10 = character(), 1046 | month.11 = character(), 1047 | month.12 = character(), 1048 | month.13 = character(), 1049 | month.14 = character(), 1050 | month.15 = character(), 1051 | month.16 1052 | ==================== 1053 | library(ggplot2) 1054 | library(tidyverse) 1055 | 1056 | df <- mtcars 1057 | 1058 | # Create the base plot 1059 | p <- ggplot(df, aes(mpg, disp)) + geom_point() + 1060 | # Change the scale of the y-axis to be on a log scale 1061 | scale_y_log10() 1062 | 1063 | # Change the look of the chart 1064 | theme <- theme_bw() + 1065 | theme(plot.title = element_text(hjust = 0.5)) 1066 | 1067 | # Overlay with custom data labels 1068 | p + geom_text(data = df[df$cyl < 6, ], 1069 | aes(x = mpg, 1070 | y = -log10(disp), 1071 | label = paste0(round(disp, 3), "%"), 1072 | hjust = -0.3, 1073 | colour = "red", 1074 | show_guide = FALSE), 1075 | show.legend = F) + 1076 | scale_colour_hue(name = "vs \n Model Type", 1077 | label = scales::percent) + 1078 | scale_x_continuous(breaks = c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)) + 1079 | coord_cartesian(ylim = c(1, 10)) + 1080 | labs(x = "Miles Per Gallon", 1081 | y = "Displacement (CUBIC FEET)") 1082 | 1083 | Resulting Plot 1084 | 1085 | Note that the labels are not continuous (e.g. the 0.10% label is located in the 31.90% region of the x-axis) as the range of values is very small. 1086 | I have tried increasing the default space between the ticks (by decreasing max(scale_x_continuous 1087 | ==================== 1088 | library(ggplot2) 1089 | library(grid) 1090 | 1091 | grid.arrange( 1092 | plot(iris[1:4, ], 1093 | xlab = "Petal width"), 1094 | plot(iris[1:4, ], 1095 | xlab = "Petal width", 1096 | ylab = "Petal length"), 1097 | plot(iris[1:4, ], 1098 | xlab = "Petal length", 1099 | ylab = "Petal width") 1100 | ) 1101 | <|endoftext|>Developmental changes of sleep activity in infants with hydronephrosis. 1102 | Sleep electroencephalogram (EEG) was recorded in 14 infants with hydronephrosis and 19 infants with unilateral ureteral obstruction (UUO) with and without laterality. The background of the delta EEG activity, the presence of the sleep spindles and the time spent in each state of sleep (S), rapid-eye-movement (REM) sleep and non-REM sleep (NREM) were examined at each time point. The ratio of the amount of REM sleep to the total sleeping time in UUO infants was significantly higher than that in hydronephrosis infants. We speculate that in the developing brain the sleep state is directed to prepare the maturation of the nervous system.<|endoftext|>Q: 1103 | 1104 | Calculate only the first 2 numbers in a number string 1105 | 1106 | I have a column that contains a series of numbers separated by either a comma or a space, some of the numbers are for the same transaction and separated by a space. 1107 | So: 1108 | Number String 1109 | 01 16 13 4 46 52 17 40 23 26 1110 | 00 2 6 18 23 4 25 15 26 3 1111 | 0 7 1 5 14 12 21 16 24 9 1112 | 1113 | I am using Pandas and I need to parse each Number String into: 1114 | Number String 1115 | 16 13 4 46 52 17 40 23 26 1116 | 2 6 18 23 4 25 15 26 3 1117 | 7 1 5 14 12 21 16 24 9 1118 | 1119 | I know that I can get all the numbers with split(" ") and then use the [0] of the array and loop through each number but it seems clunky. 1120 | I have tried a regex, to try and remove the commas and spaces: 1121 | re 1122 | ==================== 1123 | library(ggplot2) 1124 | 1125 | ggplot(mpg.df[mpg.df$mpg < 25,], aes(factor(cyl)))+ 1126 | geom_bar(position = position_dodge(width = 0.5)) 1127 | 1128 | ggplot(mpg.df[mpg.df$mpg > 35,], aes(factor(cyl)))+ 1129 | geom_bar(position = position_dodge(width = 0.5)) 1130 | 1131 | <|endoftext|>No one likes queuing for a train in Sydney. So when planning the run-up to the new transport network, each of the 12 CBD rail corridors studied by the Sydney Metro project team in 2012 made the same suggestion. 1132 | 1133 | Together they make up the Western Harbour Rail Line, to be completed in the 2040s. 1134 | 1135 | With all the publicity generated by the time trial of the metro train, this has been a sleeper project for many years, but is now within reach. 1136 | 1137 | The Western Harbour rail line should go ahead, even if most city residents think it will go nowhere. 1138 | 1139 | After 40 years without work on this line, they are finally getting a light rail run-up. It is not going to become a metro rail until after this decade. 1140 | 1141 | Toll is the best way for the region, instead of congestion, to overcome the costs for construction and the billions of dollars for the run-up. 1142 | 1143 | They need to open one line a decade, so that there will be no question of maintenance or delays. 1144 | 1145 | It would cost $1.2 billion a year, with $1.3 billion in operating costs, and there is no necessity for a suburban rail service as the demand would be far lower. 1146 | 1147 | The estimated toll of $5 would pay for the entire project and there is no question of the project being funded by the private sector. 1148 | 1149 | Instead of the road funding plan of a quarter of federal taxes going to road-building, tolls would fund the whole thing. 1150 | 1151 | By contrast, the delay in this project will cost the state $8 billion in a decade, and the private sector would have to come to the party, which will never happen. 1152 | 1153 | With Sydney’s traffic congestion costs at $4.8 billion a year, this is $5 a week per vehicle in the region. 1154 | 1155 | To achieve these savings, the toll charge for an economy car would be $6 a week. This should stop any drivers from 1156 | ==================== 1157 | library(ggplot2) 1158 | 1159 | num_treatment_k <- data.frame(num_k = 20, num_iter = 6) 1160 | 1161 | ggplot(num_treatment_k) + 1162 | geom_boxplot(aes(y = y, fill = "number")) + 1163 | facet_grid(cols = vars(names(num_treatment_k)), scales = "free") 1164 | 1165 | With gridExtra: 1166 | num_treatment_k$names <- c("20", "60", "120", "180", "240", "300", "360", "420", "480", "540", "600", "660", "720", "780", "840", "900", "960", "1020", "1080", "1140", "1200", "1260", "1320", "1380", "1440", "1500", "1560", "1620", "1680", "1740", "1800") 1167 | 1168 | num_treatment_k <- data.frame(num_k = 20, num_iter = 6, names = num_treatment_k$names) 1169 | 1170 | ggplot(num_treatment_k) + 1171 | geom_boxplot(aes(y = y, fill = "number")) + 1172 | facet_grid(cols = vars(names(num_treatment_k))) 1173 | 1174 | I think this last one is closest to what you want. 1175 | 1176 | A: 1177 | 1178 | Here is a base R solution: 1179 | num_treatment_k <- data.frame(num_k = 20, num_iter = 6, names = names(num_treatment_k)) 1180 | 1181 | ggplot(num_treatment_k) + 1182 | geom_boxplot(aes(y = y, fill = "number")) + 1183 | facet_grid(cols = vars(names(num_treatment_k))) 1184 | 1185 | You can change the default upper limit and lower limit of the axes (and make it continuous with "xlim = c(-1, max(x, na.rm = T))") with xlim: 1186 | ggplot(num_treatment_k) + 1187 | geom_boxplot(aes(y = y, fill = "number"), xlim = c(-1, max(x, na.rm = T))) + 1188 | facet_grid(cols = vars(names(num_treatment_ 1189 | ==================== 1190 | library(ggplot2) 1191 | 1192 | B = matrix(rnorm(10,0,2), 10, 1) 1193 | 1194 | p = ggplot(data = as.data.frame(B), mapping = aes(x = Var1, y = Var2, col = Var3)) + 1195 | geom_point() 1196 | p 1197 | 1198 | The data is coming from a data frame (as.data.frame) and the column names are as Var1, Var2 and Var3 in this example. 1199 | 1200 | A: 1201 | 1202 | An example using dplyr: 1203 | library(dplyr) 1204 | df <- data.frame(x1 = c(1, 2), x2 = c(2, 1), y = 1:2) 1205 | colnames(df) <- c("x1", "x2", "y") 1206 | 1207 | # To fill the "y" column based on a minimum value for the "x1" and "x2" values, 1208 | # using the 'z' column as the point of reference. 1209 | df %>% 1210 | mutate(y = ifelse(z < (max(df$x1, df$x2)), z, y)) %>% 1211 | ggplot(aes(x = x1, y = x2)) + 1212 | geom_point() + 1213 | scale_y_continuous(breaks = seq(min(df$y), max(df$y), by = 2)) 1214 | 1215 | which gives the following plot: 1216 | 1217 | <|endoftext|>By the time Joseph Atkinson was ten, he'd already suffered nine heart attacks, each one partially disabling him for days at a time. Before he was 15, he stopped growing. 1218 | 1219 | 1220 | 1221 | As a teenager, he constantly struggled with acne, obesity, and self-consciousness. Even now, with his health taken from him by an inferiority complex, his mind can't seem to break free. 1222 | 1223 | With no further name than "Atk," he'd survived adolescence and was already a widower, having lost his wife of a few years to chronic illness, before he even graduated from high school. Just getting out of his car in the parking lot was a struggle for him, as he'd been knocked unconscious during one of his attacks. 1224 | 1225 | 1226 | 1227 | When he tries to speak, he stumbles over words he can barely pronounce. It's not just the heart attack that's taken the wind out 1228 | ==================== 1229 | library(ggplot2) 1230 | 1231 | data <- structure(list(GENDER = structure(c(1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2 1232 | ==================== 1233 | library(ggplot2) 1234 | library(dplyr) 1235 | library(ggbeeswarm) 1236 | #Orginal data 1237 | de3 <- read.table(textConnection("V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 1238 | 1001 RETH ALK01 21 6 60 11 0 0 2 1 1239 | 1001 RETH ALK02 22 0 9 10 0 0 2 1 1240 | 1001 RETH ALK03 3 0 21 6 19 0 0 2 1241 | 1001 RETH ALPO 10 7 18 19 19 18 0 0 1242 | 1001 RETH CALU 19 7 19 19 14 17 15 6 1243 | 1001 RETH DHO 1 4 13 10 11 9 13 9 1244 | 1001 RETH DICO 0 0 0 9 4 6 5 1 1245 | 1001 RETH NERV 2 3 0 1 0 0 1 4 1246 | 1001 RETH ROA 11 3 6 4 4 2 4 8 1247 | 1001 RETH SPO 4 4 2 7 0 3 6 0 1248 | 1001 RETH THT 2 4 13 16 6 1 7 2 1249 | 1001 RETH VEPT 6 9 4 13 8 1 0 0 1250 | 1002 RETH ALK01 24 0 12 12 8 13 10 0 1251 | 1002 RETH ALK02 22 7 7 2 0 8 3 0 1252 | 1002 RETH ALK03 5 11 5 15 4 11 6 2 1253 | 1002 RETH ALPO 0 0 0 14 3 0 0 0 1254 | ==================== 1255 | library(ggplot2) 1256 | library(purrr) 1257 | 1258 | # First, get the leaf counts for your dataset 1259 | d <- data.frame( 1260 | year = c(2012, 2013, 2014, 2015), 1261 | month = c(4, 1, 2, 3), 1262 | day = 1:4, 1263 | id = paste0(1:4, 1) 1264 | ) 1265 | 1266 | d$species_name <- paste0(d$id, "_", substr(d$id, 1, 1)) 1267 | d$id <- factor(d$id) 1268 | 1269 | leaf <- d %>% 1270 | count(month, day, id) %>% 1271 | group_by(species_name, id) %>% 1272 | mutate(n = row_number()) %>% 1273 | select(id, species_name, n) %>% 1274 | as_tibble() 1275 | 1276 | # Merge this leaf dataframe into the original dataframe and create 1277 | # one row for each unique combination of month, day and id. 1278 | merged.data <- map_dfr(leaf, ~map_dfr(.x, ~merge(.x, d))) 1279 | 1280 | leaf.df <- d %>% select(id, species_name) 1281 | 1282 | # Create a plot using d and merged.data 1283 | ggplot(d, aes(x = id, y = leaf, size = n)) + 1284 | geom_col() + 1285 | geom_point() + 1286 | labs(x = "ID", y = "Total Leaf Count", size = "ID") + 1287 | geom_text(aes(label = species_name, hjust = 1), data = leaf.df, size = 4) + 1288 | theme_bw() 1289 | 1290 | Edit: 1291 | In order to have ggplot2 plot the line connecting leaf counts across the dataset, use geom_path(): 1292 | ggplot(d, aes(x = id, y = leaf, size = n)) + 1293 | geom_col() + 1294 | geom_point() + 1295 | labs(x = "ID", y = "Total Leaf Count", size = "ID") + 1296 | geom_text(aes(label = species_name, hjust = 1), data = leaf.df, size = 4) + 1297 | geom_path(aes(group = 1), data 1298 | ==================== 1299 | library(ggplot2) 1300 | library(gridExtra) 1301 | 1302 | iris_rm1 <- rbind(iris,iris[,1:2]) 1303 | # Lets say you have some initial (optional) options for the plot 1304 | options(theme_set()) #theme_set(theme_bw()) # to get rid of colors 1305 | 1306 | #Display the boxplot and legend of the plot 1307 | plot(iris, pch=16, col=1:4, main="Boxplot of first row of iris dataset", 1308 | xlab="", ylab="") 1309 | abline(0,0, col="grey80", lwd=2) 1310 | legend("topright", pch=16, c(paste0("setosa ", 1:4), "Sepal.Length"), 1311 | col=1:4, lwd=2, bty="n", legend=c(LETTERS[1:4]), 1312 | box.padding = c(20,10,10,10), title="") 1313 | 1314 | #Create the facet grid (same thing as cbind by default) 1315 | fg1 <- qplot(1:4, Sepal.Length, data=iris_rm1, 1316 | facets = ~Species, fill = Species, 1317 | colour = Species,geom="boxplot", 1318 | col = 1:4, lwd = 2, title = "Facet Plot") + scale_x_continuous(expand = c(0,0)) + theme_bw() 1319 | 1320 | #Now lets see how the boxes are actually aligned! (This is in the rstudio.tex file so is more of a suggestion that has to be edited to suit your needs) 1321 | grid.arrange(fg1,grob = ggplotGrob(fg1), ncol=2) # ncol = 2 to place 2 plots side by side 1322 | 1323 | Also, not sure if this was just bad drawing or an accident but on your image you have pasted multiple plots to different sides. 1324 | One could maybe do this with a couple of extra tweaks 1325 | library(gridExtra) 1326 | library(grid) 1327 | 1328 | iris_rm1 <- rbind(iris,iris[,1:2]) 1329 | ==================== 1330 | library(ggplot2) 1331 | 1332 | as.data.frame(dat) 1333 | ggplot(dat, aes(y = q1))+geom_bar(stat="identity") + coord_flip() 1334 | ggplot(dat, aes(y = q2))+geom_bar(stat="identity") + coord_flip() 1335 | ggplot(dat, aes(y = q3))+geom_bar(stat="identity") + coord_flip() 1336 | ggplot(dat, aes(y = q4))+geom_bar(stat="identity") + coord_flip() 1337 | ggplot(dat, aes(y = q5))+geom_bar(stat="identity") + coord_flip() 1338 | 1339 | The code below works but I do not like having to rewrite all the dates: 1340 | as.data.frame(dat)[seq(2, nrow(dat), 2)] 1341 | 1342 | dat$q1 <- as.numeric(dat[seq(2, nrow(dat), 2)][, "q1"]) 1343 | 1344 | ggplot(dat, aes(y = q1))+geom_bar(stat="identity") + coord_flip() 1345 | 1346 | How could I automate this? 1347 | 1348 | A: 1349 | 1350 | Data 1351 | dat <- data.frame(q1=c(1,2,3,4,5), 1352 | q2=c(6,4,5,1,3), 1353 | q3=c(7,8,9,2,4), 1354 | q4=c(1,6,2,7,1), 1355 | q5=c(4,2,1,7,5)) 1356 | 1357 | For any subset of "seq": 1358 | data.frame(q1=c(1,2,3,4,5), 1359 | q2=c(6,4,5,1,3), 1360 | q3=c(7,8,9 1361 | ==================== 1362 | library(ggplot2) 1363 | 1364 | data(wrld_sim) 1365 | 1366 | # Add 10x more data points at each value of the label 1367 | # That way we can get better at plotting it in the range of 0 to 10 1368 | 1369 | wrld_sim2 <- wrld_sim 1370 | 1371 | r <- round(wrld_sim2$dist, 1) 1372 | r <- rep(r, 10) 1373 | 1374 | n <- r * length(wrld_sim2$cont) 1375 | 1376 | wrld_sim2$cont2 <- rep(0, n) 1377 | wrld_sim2$long.lab <- rep(0, n) 1378 | 1379 | plot(wrld_sim2, ylim = range(wrld_sim2$cont2)) 1380 | 1381 | # Plotting lines 1382 | # ***************** 1383 | 1384 | # Since we are plotting all our label values, we have to break up this into separate loops for each of them 1385 | 1386 | nr <- length(r) 1387 | lw <- seq(r[1] - 1, r[1] + 2, 0.1) 1388 | 1389 | # Plotting our label values 1390 | for(i in 1:nr){ 1391 | p <- ggplot(wrld_sim2[!wrld_sim2$long.lab == i,], aes(long.lab, cont2)) + 1392 | geom_polygon() + 1393 | xlim(range(wrld_sim2$long.lab[i])) + 1394 | ylim(range(wrld_sim2$cont2[i])) + 1395 | labs(x = lw[i], y = "Cont2", 1396 | title = "Cont2 values for label: ") + 1397 | theme_minimal() 1398 | print(p) 1399 | } 1400 | 1401 | When I use print(p), I can see some things missing. For example, the world, instead of being closed, looks like this: 1402 | 1403 | And I only get the labels with 2 labels in a row. 1404 | What is going wrong? 1405 | 1406 | A: 1407 | 1408 | If you set the breaks argument of the line you can specify where to put the breaks in the line. For example, we can do the following: 1409 | p <- ggplot(wrld_sim2, aes(long.lab, cont2)) + 1410 | geom_polygon() 1411 | ==================== 1412 | library(ggplot2) 1413 | library(RColorBrewer) 1414 | 1415 | # generate some test data 1416 | set.seed(1) 1417 | pts1 <- runif(100, -4, 4) 1418 | pts2 <- runif(100, -4, 4) 1419 | pts3 <- runif(100, -4, 4) 1420 | pts4 <- runif(100, -4, 4) 1421 | pts5 <- runif(100, -4, 4) 1422 | pts6 <- runif(100, -4, 4) 1423 | pts7 <- runif(100, -4, 4) 1424 | pts8 <- runif(100, -4, 4) 1425 | pts9 <- runif(100, -4, 4) 1426 | pts10 <- runif(100, -4, 4) 1427 | pts11 <- runif(100, -4, 4) 1428 | pts12 <- runif(100, -4, 4) 1429 | pts13 <- runif(100, -4, 4) 1430 | pts14 <- runif(100, -4, 4) 1431 | pts15 <- runif(100, -4, 4) 1432 | pts16 <- runif(100, -4, 4) 1433 | pts17 <- runif(100, -4, 4) 1434 | pts18 <- runif(100, -4, 4) 1435 | pts19 <- runif(100, -4, 4) 1436 | pts20 <- runif(100, -4, 4) 1437 | pts21 <- runif(100, -4, 4) 1438 | pts22 <- runif(100, -4, 4) 1439 | pts23 <- runif(100, -4, 4) 1440 | pts24 <- runif(100, -4, 4) 1441 | pts25 <- runif(100, -4, 4) 1442 | pts26 <- runif(100, -4, 4) 1443 | pts27 <- runif(100, -4, 4) 1444 | pts28 <- runif(100, -4, 4) 1445 | pts29 <- runif(100, -4, 4) 1446 | pts30 <- runif(100, -4, 4) 1447 | pts31 <- runif(100, -4, 4) 1448 | pts32 <- runif(100, -4, 4) 1449 | pts33 <- run 1450 | ==================== 1451 | library(ggplot2) 1452 | library(plyr) 1453 | 1454 | par(mfrow = c(1,1)) 1455 | 1456 | # Example Dataset 1457 | D <- data.frame(country=c("Germany","France","Greece"), 1458 | river=c("Rhine","Loire","Moselle")) 1459 | 1460 | # load the shapefiles in the required location 1461 | D2 <- readOGR("shp/", "geodata") 1462 | 1463 | # plot the country shapefile in conjunction with the river shapefile 1464 | ggplot() + 1465 | geom_map(data = D2, mapping = aes(x=long, y=lat, map_id = country, fill = country, weight =.2)) + 1466 | geom_map(data = D2, mapping = aes(x=long, y=lat, map_id = river, fill = river, weight =.1)) + 1467 | labs(title = "My Map") + 1468 | coord_map(projection = "mill", region = "Europe") 1469 | 1470 | This works fine. However, now I want to restrict the areas where the layers can be plotted, and set some colors on those areas. So I went for the ggmap package: 1471 | library(ggmap) 1472 | 1473 | ggmap(get_googlemap(data = D2, zoom = 16)) + 1474 | # this maps the country shapefile to the city of München 1475 | # add a map legend for the color scale of the countries 1476 | mapLegend( 1477 | country_colors = rep("#e4e8e8", 10), 1478 | legend = TRUE, 1479 | title = "Germany") + 1480 | # add a title 1481 | labs(title = "My Map") + 1482 | coord_map(projection = "mill", region = "Europe") 1483 | 1484 | The mapLegend() function turns the colors of the country shapefile into a color scale, which is great. However, 1485 | ==================== 1486 | library(ggplot2) 1487 | library(igraph) 1488 | library(igraph) 1489 | library(stringi) 1490 | 1491 | # I use this for the cosine similarities of men and women in a friend list 1492 | 1493 | my_in_degree = 5 1494 | 1495 | my_friends = setNames( 1496 | lapply(1:10,function(i) { 1497 | set.seed(1234) 1498 | names(sample.names(i,replace=T)) = paste0("char", sample.names(i,replace=T)) 1499 | g = create_friend_list(my_in_degree=my_in_degree, 1500 | my_friends=my_friends, 1501 | dp=5, 1502 | name=paste0("F", 1:i)) 1503 | }), 1504 | names(my_friends) 1505 | ) 1506 | 1507 | my_friend_degrees_male = lapply(my_friends, function(x) x[names(x)=="char01"]) 1508 | 1509 | my_friend_degrees_female = lapply(my_friends, function(x) x[names(x)=="char09"]) 1510 | 1511 | # I create the data set 1512 | data = matrix( 1513 | c(1,0,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,0,1,0,0,1,0,1,0,0,0,1,1,0,1,0,1,0,1,0,0,1,0,0,1,0,1,1,0,1,0,1,0,1,1,1,0,1,0,1,0,0,1,0,1,1,0,0,0, 1514 | ==================== 1515 | library(ggplot2) 1516 | 1517 | sample_data = data.frame(Person = 1:15, 1518 | Age = sample(c(5, 10, 25, 30), 15, TRUE), 1519 | Gender = factor(rep(c("M","F","M","F"),5)), 1520 | Weight = runif(15)) 1521 | 1522 | sample_data$x = sample(1:30, 15, replace=T) 1523 | ggplot(sample_data, aes(x = Person, y = Weight, colour = Gender)) + 1524 | geom_point() + 1525 | facet_grid(Age~Person) + 1526 | geom_smooth(method="loess") 1527 | 1528 | # from: http://statistics.laerd.usc.edu/servlets/com.ssi.cmss.filter.GenerateCumulativeLifeTable.smd#ccfvs06:04 1529 | #we expect the following 1530 | 1531 | # [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] 1532 | # Person 1 9 16 24 33 42 50 59 68 77 86 95 114 122 127 139 146 1533 | # Age 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 1534 | # Gender M F M F M F M F M F M F M F M F M 1535 | # Weight 1 9 5 10 6 1536 | ==================== 1537 | library(ggplot2) 1538 | library(scales) 1539 | library(plotly) 1540 | 1541 | qplot(stack(Resid.vars), binwidth=0.5) + 1542 | geom_density(aes(fill = binwidth), alpha=0.1) + 1543 | scale_fill_continuous(name='Stacked', breaks=c(0,0.5,1), labels=c('light','mid','dark'), name='density') + 1544 | labs(fill='Shaded by weighted density') 1545 | 1546 | qplot(stack(Resid.vars), binwidth=0.5) + 1547 | geom_density(aes(fill = binwidth), alpha=0.1) + 1548 | scale_fill_continuous(name='Stacked', breaks=c(0,0.5,1), labels=c('light','mid','dark'), name='density') + 1549 | labs(fill='Shaded by weighted density') 1550 | 1551 | There is a shorter way of creating a data frame to calculate the stacked density, but it is unnecessarily confusing for me. I am interested in generalizing this code to work with multiple plots. Any suggestions? 1552 | qplot(stack(Resid.vars), binwidth=0.5) + 1553 | geom_density(aes(fill = binwidth), alpha=0.1) + 1554 | scale_fill_continuous(name='Stacked', breaks=c(0,0.5,1), labels=c('light','mid','dark'), name='density') + 1555 | labs(fill='Shaded by weighted density') 1556 | 1557 | Edit: I would appreciate if you suggested a way to achieve this using stat_compare() or stat_bin2d() as there is already a graph on SO that shows all three methods. 1558 | 1559 | A: 1560 | 1561 | See the attached link with a function that will overlay all three histograms. 1562 | stat_compare_all(aes(fill = binwidth), method = "hist") 1563 | 1564 | <|endoftext|>Q: 1565 | 1566 | Angular + Material table, two selectors for same cell 1567 | 1568 | I'm trying to use Angular with Angular Material. I have a working example here 1569 | I have a datatable as follows: 1570 | 1571 | 1572 | 1573 | 1574 | ==================== 1575 | library(ggplot2) 1576 | 1577 | y <- seq(0, 1, 1/200) 1578 | x <- seq(0, 10, 1/2) 1579 | df <- data.frame(y, x) 1580 | 1581 | my_function <- function(x) { 1582 | # x = data.frame(y=y,x=x) 1583 | x <- data.frame(y=y, x=x) 1584 | x$r <- x$x/x$y 1585 | x 1586 | } 1587 | 1588 | p <- ggplot(df, aes(x=x, y=y)) + 1589 | geom_line(size=2) + 1590 | geom_point(size=3) + 1591 | geom_text(data=my_function(df), aes(x=x, y=y, label=y)) 1592 | 1593 | p 1594 | 1595 | <|endoftext|>Q: 1596 | 1597 | Keep a form and custom control on top of the page 1598 | 1599 | I'm trying to make the form stay on top of the page when other controls get scrolled. 1600 | See fiddle here. 1601 | Basically, I want my #red form to stay always on top of everything else, but only if it has the focus. 1602 | I have managed to make the form stay in place in Chrome when I click somewhere else on the page, but I haven't managed to find a way to do it without using the mouse. 1603 | 1604 | $(document).ready(function(){ 1605 | 1606 | $(window).scroll(function(){ 1607 | if($(window).scrollTop() > 1 && $('#redForm').is(":visible")) { 1608 | $('#redForm').css('z-index', '2'); 1609 | $('#redForm').css('top', '0px'); 1610 | } else if($(window).scrollTop() < 1 && $('#redForm').is(":hidden")) { 1611 | $('#redForm').css('z-index', '1'); 1612 | $('#redForm').css('top', '-50px'); 1613 | } 1614 | }); 1615 | 1616 | ==================== 1617 | library(ggplot2) 1618 | library(dplyr) 1619 | library(nycflights13) 1620 | library(tidyverse) 1621 | 1622 | # Reorder to match demo data frame structure and then concatenate both data frames to create data frame 1623 | df_travel_scrape <- travel_scrape %>% 1624 | mutate(time_zone = hour(timestamp)) %>% 1625 | filter(city == "abc") %>% 1626 | select(start_time, end_time, time_zone) 1627 | df_flights <- tbl_df(nycflights13) %>% 1628 | 1629 | ==================== 1630 | library(ggplot2) 1631 | theme_set(theme_bw()) 1632 | 1633 | library(ggforce) 1634 | gg.force(width=2) 1635 | gg.force(position="absolute", width=12) 1636 | gg.force(position="relative", width=14) 1637 | gg.force(position="absolute", width=16) 1638 | gg.force(position="relative", width=18) 1639 | gg.force(position="absolute", width=20) 1640 | gg.force(position="relative", width=22) 1641 | gg.force(position="absolute", width=24) 1642 | gg.force(position="relative", width=26) 1643 | gg.force(position="absolute", width=28) 1644 | gg.force(position="relative", width=30) 1645 | gg.force(position="absolute", width=32) 1646 | gg.force(position="relative", width=34) 1647 | gg.force(position="absolute", width=36) 1648 | gg.force(position="relative", width=38) 1649 | gg.force(position="absolute", width=40) 1650 | gg.force(position="relative", width=42) 1651 | gg.force(position="absolute", width=44) 1652 | gg.force(position="relative", width=46) 1653 | gg.force(position="absolute", width=48) 1654 | gg.force(position="relative", width=50) 1655 | gg.force(position="absolute", width=52) 1656 | gg.force(position="relative", width=54) 1657 | gg.force(position="absolute", width=56) 1658 | gg.force(position="relative", width=58) 1659 | gg.force(position="absolute", width=60) 1660 | gg.force(position="relative", width=62) 1661 | gg.force(position="absolute", width=64) 1662 | gg.force(position="relative", width=66) 1663 | gg.force(position="absolute", width=68) 1664 | gg.force(position="relative", width=70) 1665 | gg.force(position="absolute", width=72) 1666 | gg.force(position="relative", width=74) 1667 | gg.force(position="absolute", width=76) 1668 | gg.force(position="relative", width=78) 1669 | gg.force(position="absolute", width=80) 1670 | gg.force(position="relative", width=82) 1671 | gg.force(position="absolute", width=84) 1672 | gg.force( 1673 | ==================== 1674 | -------------------------------------------------------------------------------- /is_bird.txt: -------------------------------------------------------------------------------- 1 | def is_bird(img): 2 | """Check whether an image is a bird""" 3 | 4 | # check if number of green pixels 5 | return img[0] > 104 6 | 7 | 8 | def is_sparrow(img): 9 | """Check whether an image is a sparrow""" 10 | 11 | # check if number of green pixels 12 | return img[0] > 120 13 | <|endoftext|>Ai Weiwei: I’m Scared of the Mafia, I’m Scared of Chinese People, I’m Scared of Myself (世间大事,公众可以比得过了,我可以比得过了,可以跟自己比得过了) 14 | 15 | September 11, 2019 16 | 17 | [Ming Tang-Evans] Today I visited at 1.2 metres tall [Ai Weiwei], and I was quite surprised to find him standing in the middle of a tiny gallery. 18 | 19 | For me, he has become larger in China, but he remains the same Ai Weiwei. I guess Ai Weiwei still has a huge power to challenge the official thoughts. 20 | 21 | Ai Weiwei, let’s say that “One day we are not going to remember each other,” because this is your last performance. 22 | 23 | Ai Weiwei: One day we are not going to remember each other, because we have already forgotten each other. You will leave, I will leave, and the exhibition will be over. 24 | 25 | MT: What will you do afterwards? 26 | 27 | Ai Weiwei: I am not going to ask. 28 | 29 | Ai Weiwei: I’m scared of the mafia, I’m scared of Chinese people, I’m scared of myself. 30 | 31 | – 32 | 33 | – 34 | 35 | – 36 | 37 | © Ming Tang-Evans. 38 | 39 | Images copyright the artist.<|endoftext|>Discovery and synthesis of 1,3-bis(phenylalkyl)imidazolidines as potent dual inhibitors of DYRK1A and AURKB. 40 | A series of 1,3-bis(phenylalkyl)imidazolidines were designed and synthesized as potent and selective inhibitors of DYRK1A and AURKB kinases. The identified compounds display low nanomolar IC50 values for both DYRK1 41 | ==================== 42 | def is_bird(img): 43 | """Check whether an image is a bird""" 44 | # retrieve columns (min-max). convert to array 45 | c0 = img.astype(float).min(axis=0) - 0.1 # -0.1 is the mean 46 | c1 = img.astype(float).max(axis=0) + 0.1 # +0.1 is the mean 47 | 48 | # the 'windows' should be around 0.2:1.3 49 | windows = c0 / (c0 + c1) 50 | windows = windows * [5, 10, 20, 25] 51 | 52 | # set windows and convert to int. 53 | windows = windows.astype(int) 54 | 55 | # find boundaries of the image 56 | windows_box = np.array(windows) 57 | # find average values of (x, y) coordinate 58 | windows_box_min = np.mean(windows_box, axis=0) 59 | windows_box_max = np.mean(windows_box, axis=1) 60 | 61 | # calculate birdness 62 | binarized = np.zeros_like(windows_box) 63 | count = np.sum(windows_box > 0) 64 | for i, row in enumerate(windows_box): 65 | for j, col in enumerate(windows_box): 66 | box = windows_box[i, j] 67 | binarized[i, j] = (box <= windows_box_min[i, j]) 68 | & (box >= windows_box_max[i, j]) 69 | count[i, j] += count[i, j] 70 | 71 | # threshold to binary image 72 | binarized = cv2.threshold(binarized, 255, 255, cv2.THRESH_BINARY)[1] 73 | 74 | # the birdness is: (binarized * count) / count 75 | 76 | ==================== 77 | def is_bird(img): 78 | """Check whether an image is a bird""" 79 | with tf.name_scope('get_bird'): 80 | a = vgg16.select_roi_feat(img) 81 | h, w, _ = tf.image.extract_image_patches( 82 | a, 7, 7, 4, 4, 1, 1) 83 | b = tf.reshape(h, [1, 7, 7, 256]) 84 | c = tf.reshape(w, [1, 7, 7, 256]) 85 | bird_img = tf.subtract(b, c) 86 | return bird_img 87 | 88 | # Sample images. 89 | sample_images = ['dogs', 'pigs','sheep', 'birds'] 90 | 91 | # Input batch of images. 92 | batch_images = tf.train.batch( 93 | [sample_images, sample_images, sample_images, sample_images], 94 | [64, 128, 64, 128], 95 | batch_size=16, 96 | num_threads=1, 97 | ) 98 | 99 | # A place to queue up to 16 requests to feed the above batch. 100 | placeholder = tf.placeholder(tf.float32, [None, None, None, None], name='images') 101 | queue = tf.FIFOQueue(batch_size=16, dtypes=tf.float32, name='requests') 102 | enqueue_op = queue.enqueue([batch_images, batch_images, batch_images, batch_images]) 103 | sess = tf.Session() 104 | sess.run(enqueue_op, feed_dict={placeholder: batch_images}) 105 | for i in range(1, 16): 106 | tf.train.start_queue_runners(sess=sess) 107 | results = sess.run(queue.dequeue(), feed_dict={placeholder: batch_images}) 108 | for i in range(len(results)): 109 | img = sess.run(results[i]) 110 | print(img.shape) 111 | 112 | ==================== 113 | def is_bird(img): 114 | """Check whether an image is a bird""" 115 | return (img.file == "C:/Users/Joey/Downloads/images/bird_file.jpg" 116 | 117 | ==================== 118 | def is_bird(img): 119 | """Check whether an image is a bird""" 120 | # Get the face 121 | bird_face_bbox = face_box(img, "bird") 122 | return (bird_face_bbox[0] < 0) and (bird_face_bbox[1] < 0) and (bird_face_bbox[2] > 0) and (bird_face_bbox[3] > 0) 123 | 124 | def bird_recognizer(bird_score=0.9): 125 | """Recognizes a bird image based on the CUB model 126 | bird_score: the highest score to consider a result as a'real' result""" 127 | 128 | # Load the model 129 | detector = cv2.face.LBPHFaceRecognizer_create() 130 | # Try different scale for the model 131 | #batch_size=10 132 | #num_faces=5 133 | #scale=0.2 134 | batch_size = 0 135 | num_faces = 0 136 | scale = 0.1 137 | start_time = time.time() 138 | while True: 139 | start_time = time.time() 140 | # Load an image from disk 141 | img = cv2.imread('/home/caffeine/dog/2018-08-24-0233/e2d9e8726b35aadac9b0d96b065efa6a.jpg') 142 | img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 143 | img = cv2.resize(img, (224, 224)) 144 | # Apply the face detection 145 | # If the face detected has < bird_score> score, 146 | # the face_info contains the info of the face, 147 | # then we will keep this face. 148 | bird_face_bbox = face_box(img, "bird") 149 | if not bird 150 | ==================== 151 | def is_bird(img): 152 | """Check whether an image is a bird""" 153 | 154 | with Image.open(img) as bmp: 155 | bird = bmp.convert('L') 156 | return bird == 'B' 157 | 158 | 159 | def build_dataset(dataset_dir): 160 | """Build the VGG dataset given a dataset directory.""" 161 | 162 | vgg_dir = os.path.join(dataset_dir, 'VGG') 163 | vgg_images = [] 164 | 165 | for root, dirs, filenames in os.walk(vgg_dir): 166 | for filename in filenames: 167 | filepath = os.path.join(root, filename) 168 | if '.png' in filename: 169 | # skip png for data augmentation 170 | continue 171 | 172 | image = Image.open(filepath) 173 | img_ratio = image.width / image.height 174 | if img_ratio > 1.2 and img_ratio < 1.8: 175 | continue 176 | 177 | # skip lines of text 178 | if any(line in filename for line in ['The Competition', 'Copyright', 'This dataset was produced with funding from the European Research Council under ERC Starting Grant N.', 179 | 'Contact me at vicky@ucam.ac.uk', 'This data is licensed under the Creative Commons Attribution 4.0 International License']) or 'Labeled': 180 | continue 181 | 182 | v 183 | ==================== 184 | def is_bird(img): 185 | """Check whether an image is a bird""" 186 | """Returns: 187 | - True - if bird is detected 188 | - False - if not bird is detected 189 | """ 190 | return-any([is_goose(img), is_seagull(img), is_turtle(img), is_crow(img)]) 191 | 192 | ##============================================================================== 193 | # THE BIRD OBJECT 194 | ##============================================================================== 195 | 196 | ##---------------------------------------------------------------------------- 197 | # DEFINE BIRD BOT MOTIONS 198 | ##---------------------------------------------------------------------------- 199 | 200 | bird_polar = 0 201 | bird_vertical = 1 202 | bird_lateral = 2 203 | 204 | ##---------------------------------------------------------------------------- 205 | # THE BIRD OBJECT 206 | ##---------------------------------------------------------------------------- 207 | 208 | class Bird: 209 | """Bird class""" 210 | # Setup 211 | 212 | def __init__(self, bird_id, locations=[]): 213 | """Initialization""" 214 | self.bird_id = bird_id 215 | self.locations = locations 216 | 217 | # Setup data attribute: 218 | self.time = None 219 | self.angle = 0.0 220 | 221 | # Setup recognition 222 | if is_bird(img): 223 | is_robin = True 224 | self.robin = True 225 | else: 226 | is_robin = False 227 | self.robin = False 228 | 229 | # Setup wing: 230 | self.upper_wing_angle = 0.0 231 | self.lower_wing_angle = 0.0 232 | 233 | # Setup environment variables for tracking: 234 | self.recognized = False 235 | self.animate_markers = True 236 | 237 | # Setup fall-off 238 | self.animate_fall_off = True 239 | 240 | ==================== 241 | def is_bird(img): 242 | """Check whether an image is a bird""" 243 | import urllib 244 | url = "http://vision.caitling.pitt.edu/~cat/flickr/birds/" 245 | for img in range(0, 2800): 246 | page = urllib.urlopen(url + "##%02d" % img).read() 247 | content = str(page) 248 | for word in content.split(' '): 249 | if word.find(img) > -1: 250 | return True 251 | return False 252 | <|endoftext|>Angiotensin II-induced hypertrophy of human mesangial cells is mediated by activation of phosphatidylinositol 3-kinase-Akt pathway and phosphorylation of mitogen-activated protein kinase kinase-1. 253 | Angiotensin II (Ang II) is considered to be one of the potent stimulator of cell growth. In the present study, we investigated the role of phosphatidylinositol 3-kinase (PI 3-kinase) and mitogen-activated protein kinase kinase (MEK)-1/extracellular signal-regulated kinase (ERK) pathway in Ang II-induced hypertrophy of human mesangial cells. Ang II (1 nM) and platelet-derived growth factor (PDGF) (10 ng/ml) enhanced the production of type IV collagen. These two factors induced phosphorylation of Akt and MEK-1. The PI 3-kinase inhibitors wortmannin, LY-294002 and LY-103, and the MEK-1 inhibitor PD98059 suppressed the Ang II-induced hypertrophy and the production of type IV collagen. PD98059 inhibited the phosphorylation of Akt and MEK-1 induced by Ang II. In contrast, PD98059 did not inhibit the phosphorylation of Akt or MEK-1 induced by PDGF. LY-294002 and PD98059 inhibited the phosphorylation of Akt and MEK-1 induced by PDGF. The effects of PD98059 and LY-294002 were additive to each other. These results indicated that PI 3-kinase and 254 | ==================== 255 | def is_bird(img): 256 | """Check whether an image is a bird""" 257 | return tf.image.convert_image_dtype( 258 | img, dtype=tf.float32, label_dtype=tf.float32) 259 | num_bird = tf.image.rgb_to_gray(is_bird(bird_imgs)) 260 | 261 | num_dots = tf.image.label_to_number(tf.image.label_create( 262 | NUM_CLASSES, class_dtype=tf.int64)) 263 | 264 | def get_num_dots(): 265 | return num_dots 266 | 267 | # Define loss function and optimizer. 268 | with tf.name_scope("loss"): 269 | loss_real = tf.reduce_mean(tf.reduce_mean( 270 | tf.squeeze(tf.nn.softmax_cross_entropy_with_logits(labels=num_bird, 271 | logits=num_dots)), 272 | axis=1)) 273 | loss_fake = tf.reduce_mean(tf.reduce_mean( 274 | tf.squeeze(tf.nn.softmax_cross_entropy_with_logits(labels=num_bird, 275 | logits=num_dots)), 276 | axis=1)) 277 | 278 | # Training of the model. 279 | train_op = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(loss_real) 280 | logits = tf.group( 281 | tf.nn.conv2d_transpose(is_bird( 282 | ==================== 283 | def is_bird(img): 284 | """Check whether an image is a bird""" 285 | features = np.array(run_extract_bird(img)) 286 | return features[0] 287 | 288 | bird_pairs = [ 289 | ["hat", "chicken", "hawk", "canary", "pigeon", "parrot", "parakeet", "dove"], 290 | ["hen", "duck", "turtle", "crane", "budgie", "ostrich", "quail", "penguin"], 291 | ["duck", "tortoise", "seagull", "elephant", "snake", "lion", "raccoon", "spider"]] 292 | 293 | for pair in bird_pairs: 294 | print("-----{}-----".format(pair)) 295 | # Read the image using the function 296 | img = cv2.imread('./static/imgs/{}/birds/{}'.format(pair[0], pair[2])) 297 | 298 | # Apply the bird feature detector to the image 299 | bird = run_extract_bird(img) 300 | 301 | # Check if it's a bird 302 | if bird is not None: 303 | bird_label = "bird" 304 | else: 305 | bird_label = "no-bird" 306 | if not bird_label: 307 | img_label = "no-label" 308 | continue 309 | 310 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 311 | 312 | # Initialize the filter size to 20 for HOG feature extractor 313 | HOG_SIZES = [10, 10, 5] 314 | windows_sizes = (5, 15, 7) 315 | 316 | # Extracted features from image are fed into a ConvNet 317 | net = nn.Sequential( 318 | nn.Conv2d(1, 1, 3, padding=1), 319 | nn.ReLU(), 320 | nn.MaxPool2d(pool_ 321 | ==================== 322 | def is_bird(img): 323 | """Check whether an image is a bird""" 324 | 325 | import scipy 326 | 327 | thresh = 3. 328 | res = scipy.ndimage.measurements.label(img.astype(np.float32)) 329 | 330 | labels = np.unique(res > thresh) 331 | shape = np.unique(res.shape) 332 | 333 | return shape[0] == 'bird' and len(labels) == 1 and labels[0] == 1 334 | 335 | 336 | def is_cat(img): 337 | """Check whether an image is a cat""" 338 | 339 | import scipy 340 | 341 | thresh = 3. 342 | res = scipy.ndimage.measurements.label(img.astype(np.float32)) 343 | 344 | labels = np.unique(res > thresh) 345 | shape = np.unique(res.shape) 346 | 347 | return shape[0] == 'cat' and len(labels) == 1 and labels[0] == 1 348 | 349 | 350 | def is_food(img): 351 | """Check whether an image is a food item""" 352 | 353 | import scipy 354 | 355 | thresh = 3. 356 | res = scipy.ndimage.measurements.label(img.astype(np.float32)) 357 | 358 | labels = np.unique(res > thresh) 359 | shape = np.unique(res.shape) 360 | 361 | return shape[0] == 'food' and len(labels) == 1 and labels[0] == 1 362 | 363 | 364 | def is_persp(img): 365 | """Check whether an image is a perspective map""" 366 | 367 | import scipy 368 | 369 | thresh = 2. 370 | res = scipy.ndimage.measurements.label(img.astype(np.float32)) 371 | 372 | labels = np.unique(res > thresh) 373 | shape = np.unique(res.shape) 374 | 375 | return shape[0] == 'persp' and len(labels) == 1 and labels[0] == 1 376 | 377 | 378 | def is_wheel(img): 379 | """Check whether an image is a wheel""" 380 | 381 | import scipy 382 | ==================== 383 | def is_bird(img): 384 | """Check whether an image is a bird""" 385 | 386 | # In case of a large variation in lighting or non uniform background, a simple color threshold is not sufficient. Hence we try to apply the following filters 387 | # 1) Linear segmentation (max of 255, max value is bird body) 388 | # 2) U-subtraction using the grayscale of the bird and the background. The value that results in the darkest image should be the background. 389 | # 3) Otsu's thresholding to set the grayscale maximum and minimum. This generates the thresholds for a thresholding operation 390 | # 4) Gray level non-maximum suppression. This generates the binary mask for the bird in a post-processing step 391 | # The bird mask is used as an input to the dog or crow detector. 392 | 393 | rgb_im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 394 | hsv = cv2.cvtColor(rgb_im, cv2.COLOR_BGR2HSV) 395 | mask = cv2.inRange(hsv[1], [179, 245, 179], [254, 254, 254]) 396 | mask = cv2.bitwise_and(mask, mask, mask=mask) 397 | mask = cv2.threshold(mask, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) 398 | birds = cv2.bitwise_and(img, img, mask=mask) 399 | birds = cv2.cvtColor(birds, cv2.COLOR_RGB2HSV) 400 | # print("Detection probabilities:"+str(math.log(img.shape[0]))+"*"+str(math.log(img.shape[1]))+"*"+str(math.log(img.shape[2]))) 401 | # print(birds[50:70,50:70]) 402 | birds[birds>255] = 0 403 | return birds 404 | 405 | 406 | def find_head(bird, head_min_x, head_min_y, head_max_x, head_max_y, max_th 407 | ==================== 408 | def is_bird(img): 409 | """Check whether an image is a bird""" 410 | bird_desc = ['long beak','short tail', 'down-facing angle'] 411 | return any(lab == 'bird' and set(bird_desc) & img) 412 | 413 | def is_cat(img): 414 | """Check whether an image is a cat""" 415 | cat_desc = ['pointed face','stripy face', 'large ears', 416 | 'long fur', 'waving tail'] 417 | return any(lab == 'cat' and set(cat_desc) & img) 418 | 419 | def is_dolphin(img): 420 | """Check whether an image is a dolphin""" 421 | dolphin_desc = ['long tail', 'bubbled tail','spots', 422 | 'small head', 'big eyes', 'bumpy skin', 423 | 'dolphin jumping'] 424 | return any(lab == 'dolphin' and set(dolphin_desc) & img) 425 | 426 | def is_horse(img): 427 | """Check whether an image is a horse""" 428 | horse_desc = ['lacking lower back','sharp back', 429 | 'long snout', 'big ears', 'tail in horizontal line', 430 | 'long legs', 'long neck', 'closer to the camera', 431 | 'rounded mane'] 432 | return any(lab == 'horse' and set(horse_desc) & img) 433 | 434 | def is_horse2(img): 435 | """Check whether an image is a horse""" 436 | horse2_desc = ['snouting','sharper ears', 'lacking lower back', 437 | 'sharper back', 'pointed mane'] 438 | return any(lab == 'horse2' and set(horse2_desc 439 | ==================== 440 | def is_bird(img): 441 | """Check whether an image is a bird""" 442 | return img.shape[0]==2 and img.shape[1]==2 443 | 444 | def to_giant_bird(img): 445 | """ 446 | Convert a bird image to a bird-shaped object with a 447 | big head and wide mouth. 448 | 449 | @return: A giant bird image 450 | """ 451 | w = img.shape[1] 452 | h = img.shape[0] 453 | img = cv2.resize(img, (int(w/4), int(h/4))) 454 | img = np.expand_dims(img, axis=0) 455 | big_head_img = cv2.resize(cv2.imread( 456 | 'img/bird/bird_head/bird_head_r.jpg'), 457 | (int(w/4), int(h/4)) 458 | ) 459 | big_mouth_img = cv2.resize(cv2.imread( 460 | 'img/bird/bird_mouth/bird_mouth_r.jpg'), 461 | (int(w/4), int(h/4)) 462 | ) 463 | big_body_img = cv2.resize(cv2.imread( 464 | 'img/bird/bird_body/bird_body_r.jpg'), 465 | (int(w/4), int(h/4)) 466 | ) 467 | return np.concatenate((big_head_img, big_mouth_img, big_body_img, img), axis=0) 468 | 469 | # load the dataset 470 | dataset = pd.read_csv('train.csv') 471 | 472 | # convert to a numpy array 473 | train = train.astype(float).astype('int32').as_matrix 474 | ==================== 475 | def is_bird(img): 476 | """Check whether an image is a bird""" 477 | assert len(img) == 1 478 | return ( 479 | np.max(img) - np.min(img) > 190.0 480 | ) 481 | 482 | # filter images by size and with bird=0, and random crop 483 | def filter_bird(bird_data, img_data): 484 | """Crop a random bird from bird_data and add it to img_data""" 485 | bird = bird_data[0]['b'] 486 | if bird_data[0]['b'] == 0: 487 | return img_data 488 | crop = ( 489 | (int(np.round(np.random.rand()*(bird['w'] - 200)))) + 200, 490 | (int(np.round(np.random.rand()*(bird['h'] - 200)))) + 200, 491 | ) 492 | return imutils.resize(img_data, width=crop[0], height=crop[1])[crop[2]:] 493 | 494 | # save to path 495 | def save_img_path(fname, img_path, bird_data): 496 | """Save a filtered image with a bird to an image path""" 497 | bird = bird_data[0]['b'] 498 | crop = ( 499 | (int(np.round(np.random.rand()*(bird['w'] - 200)))) + 200, 500 | (int(np.round(np.random.rand()*(bird['h'] - 200)))) + 200, 501 | ) 502 | os.makedirs(img_path, exist_ok=True) 503 | if bird == 0: 504 | fname = os.path.join(img_path, fname) 505 | img_path = os.path.join(img_path, img_path) 506 | with Image.open(img_path) as input_img: 507 | with Image.open(fname) as input_img_path: 508 | 509 | ==================== 510 | def is_bird(img): 511 | """Check whether an image is a bird""" 512 | # 判断图片是否是一只可以识别到的鸟 513 | bird_contour = bird.net.detect_bird(img) 514 | if len(bird_contour) > 0: 515 | return True 516 | return False 517 | 518 | def get_param(layer_param): 519 | if layer_param is not None: 520 | return layer_param 521 | param_file = os.path.join(DATASET_PATH, 'ZhouDataset_groundtruth.h5') 522 | layer_param = tf.load_variable(param_file, name="ZhouDataset_groundtruth_param") 523 | return layer_param 524 | 525 | def build_model(filters, 526 | batch_size, 527 | num_classes, 528 | image_shape): 529 | """Build model""" 530 | model = vgg.Vgg19(is_training=False) 531 | with tf.variable_scope("imagenet_vgg"): 532 | # 1. 定义尺寸 533 | with tf.variable_scope("default"): 534 | image_data = tf.placeholder(tf.float32, shape=image_shape, 535 | name='image_data') 536 | image_data_pl = tf.placeholder(tf.float32, shape=image_shape, 537 | name='image_data_pl') 538 | 539 | ==================== 540 | def is_bird(img): 541 | """Check whether an image is a bird""" 542 | # Pass in pre-defined attributes/features 543 | return img[..., 0] == 5 or img[..., 0] == 1 544 | 545 | # User-defined features 546 | def get_features(img): 547 | # Get a square of the entire image 548 | feat = img[..., 0:-1, 0:-1].squeeze() 549 | 550 | # Example of a bird. 551 | # Get the feature data of the bird 552 | #feat[feat == 5] 553 | 554 | # Example of a duck. 555 | #feat[feat == 1] 556 | 557 | return feat 558 | 559 | # Data partitioning 560 | if __name__ == "__main__": 561 | train, valid, test = load_data() 562 | 563 | print("Training Set:", train) 564 | print("Validation Set:", valid) 565 | print("Testing Set:", test) 566 | 567 | # Create and Fit the model 568 | features = get_features(train) 569 | model = LogisticRegression() 570 | model.fit(features, train) 571 | 572 | # Predict a value 573 | print(model.predict(valid)) 574 | 575 | # Predict a value 576 | print(model.predict(test)) 577 | 578 | # Make predictions on a new image 579 | feat_data = get_features(valid) 580 | feat_image = torch.Tensor(feat_data).numpy() 581 | feat_image = np.transpose(feat_image) 582 | 583 | # Use inference to find probabilities of each label 584 | prediction = model.predict(feat_image) 585 | 586 | print("Labels: ", prediction) 587 | 588 | # Calculate accuracy 589 | num_correct = 0 590 | for i,j in zip(prediction, valid): 591 | if j == 1: 592 | num_correct += 1 593 | print(num_correct / valid.shape[0]) 594 | 595 | <|endoftext|>#!/bin/sh 596 | # 597 | # Copyright 2019 Google LLC 598 | # 599 | # Licensed under the Apache License, Version 2.0 600 | ==================== 601 | def is_bird(img): 602 | """Check whether an image is a bird""" 603 | img = np.asarray(img) 604 | return img[0] > 200 and img[1] > 200 605 | 606 | 607 | def flow_to_heading(flip, np_flow, clip_thresh, conf_thresh): 608 | """Convert image flow to bird headings.""" 609 | img_diff = np.abs(flip - 1.0) 610 | img_diff[img_diff < 0.01] = 0.0 611 | img_diff[img_diff > 0.99] = 1.0 612 | 613 | if not is_bird(img_diff): 614 | img_diff = np.sign(img_diff) 615 | conf_img_diff = np.array([[1.0, 1.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.0]]) 616 | img_diff[img_diff > conf_thresh] = conf_img_diff[img_diff > conf_thresh] 617 | 618 | flow = np_flow / 100.0 619 | flow[flow < 0] = 0.0 620 | if flip > 0.0: 621 | flow[flow < 0] = -flow[flow < 0] 622 | return np.clip(flow * 100, -200, 200) 623 | 624 | 625 | def track_to_bounding_boxes(tracks, np_feat): 626 | """Transform bird tracks to bounding boxes.""" 627 | paths = np.array(tracks, dtype=np.int) 628 | all_paths = np.stack([paths.astype(np.int) for paths in tracks], axis=-1) 629 | all_paths = np.array(all_paths) 630 | all_boxes = np.zeros((len(all_paths), 5)) 631 | feat_info = np.zeros((len(all_paths), 2, 1)) 632 | for idx, i in enumerate(all_paths): 633 | # head 634 | 635 | ==================== 636 | def is_bird(img): 637 | """Check whether an image is a bird""" 638 | return img[0] > 80 and img[0] < 255 639 | 640 | def is_boat(img): 641 | """Check whether an image is a boat""" 642 | return img[1] > 80 and img[1] < 255 643 | 644 | def is_cat(img): 645 | """Check whether an image is a cat""" 646 | return img[2] > 80 and img[2] < 255 647 | 648 | def is_dining_table(img): 649 | """Check whether an image is a dining table""" 650 | return img[2] > 200 and img[2] < 400 651 | 652 | def is_fire(img): 653 | """Check whether an image is a fire""" 654 | return img[0] > 80 and img[1] > 120 655 | 656 | def is_green_door(img): 657 | """Check whether an image is a green door""" 658 | return img[0] > 140 and img[1] > 160 and img[2] > 20 659 | 660 | def is_gold_mine(img): 661 | """Check whether an image is a gold mine""" 662 | return img[2] > 200 and img[3] > 60 and img[4] > 300 663 | 664 | def is_helmet(img): 665 | """Check whether an image is a helmet""" 666 | return img[0] > 80 and img[1] > 100 and img[2] > 10 667 | 668 | def is_icon(img): 669 | """Check whether an image is an icon""" 670 | return img[1] > 20 and img[2] > 20 671 | 672 | def is_sky(img): 673 | """Check whether an image is a sky""" 674 | return img[0] > 20 and img[1] > 20 675 | 676 | def is_tree(img): 677 | """Check whether an image is a tree""" 678 | return img[1] > 50 and img[2] > 200 679 | 680 | def is_tram(img): 681 | """Check whether an image is a tram""" 682 | return img[0] > 80 and img[1] > 80 and img[2] > 120 683 | 684 | def is_train(img): 685 | """ 686 | ==================== 687 | def is_bird(img): 688 | """Check whether an image is a bird""" 689 | mask = cv2.Canny(img, 10, 150) 690 | mask = cv2.dilate(mask, None) 691 | mask = cv2.adaptiveThreshold(mask, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 10) 692 | cv2.imshow('Mask', mask) 693 | return mask.any() 694 | 695 | def is_cloud(img): 696 | """Check whether an image is a cloud""" 697 | mask = cv2.Canny(img, 0, 255) 698 | mask = cv2.dilate(mask, None) 699 | mask = cv2.adaptiveThreshold(mask, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 10) 700 | cv2.imshow('Mask', mask) 701 | return mask.any() 702 | 703 | def is_vehicle(img): 704 | """Check whether an image is a vehicle""" 705 | mask = cv2.Canny(img, 10, 50) 706 | mask = cv2.dilate(mask, None) 707 | mask = cv2.adaptiveThreshold(mask, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 10) 708 | cv2.imshow('Mask', mask) 709 | return mask.any() 710 | 711 | def is_person(img): 712 | """Check whether an image is a person""" 713 | mask = cv2.Canny(img, 50, 100) 714 | mask = cv2.dilate(mask, None) 715 | mask = cv2.adaptiveThreshold(mask, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 10) 716 | 717 | ==================== 718 | def is_bird(img): 719 | """Check whether an image is a bird""" 720 | # Check if the image is an avian bird 721 | if img == "birds": 722 | return True 723 | # Print out a standard bird image 724 | if img == "standard_bird": 725 | print(img) 726 | # The image is a symbol 727 | elif img == "symbol": 728 | print(img) 729 | # All others 730 | else: 731 | print(img) 732 | return False 733 | 734 | img = pwd.getpwuid(os.getuid())[0] + ".jpg" 735 | img = "https://app.box.com/s/kvcbxrtq147315zhd3y" 736 | img = os.path.join(pwd, img) 737 | with open(img, 'rb') as f: 738 | img = f.read() 739 | 740 | with open(img) as f: 741 | img = f.read().decode('UTF-8') 742 | bird_dict = {} 743 | bird_dict["standard_bird"] = img 744 | bird_dict["birds"] = "normal" 745 | bird_dict["people"] = "people" 746 | bird_dict["politics"] = "politics" 747 | bird_dict["courses"] = "courses" 748 | bird_dict["nature"] = "nature" 749 | bird_dict["other"] = "other" 750 | bird_dict["outdoors"] = "outdoors" 751 | for k,v in bird_dict.items(): 752 | if is_bird(v): 753 | print("Found:", k) 754 | print("\n") 755 | else: 756 | print(v) 757 | 758 | <|endoftext|>This invention relates to a power steering system for an automotive vehicle, and more particularly to a power steering system provided with a mechanism for adjusting the force of a power steering fluid applying to the steering gear such 759 | ==================== 760 | def is_bird(img): 761 | """Check whether an image is a bird""" 762 | return all(bird_preds[0]==0 for bird_preds in get_bird_masks(img)) 763 | 764 | 765 | def multi_preds(img): 766 | """Get a list of masks for each bird and crow, in order of likelihood""" 767 | bird_masks = [get_bird_masks(img) for img in [train_set[i]] if i>0] 768 | crow_masks = [get_crow_masks(img) for img in [train_set[i]] if i>1] 769 | bird_masks, crow_masks = zip(*bird_masks), *crow_masks 770 | return bird_masks, crow_masks 771 | <|endoftext|>Dick Klooger 772 | 773 | Donald Phillip Klooger (born October 20, 1941) is a retired American professional baseball pitcher who played one season in Major League Baseball for the Chicago White Sox. 774 | 775 | Klooger attended Brookline High School in Boston, Massachusetts. He was signed by the White Sox on August 21, 1960 as an amateur free agent. He was purchased by the Toronto Blue Jays in the December 1960 rule 5 draft. 776 | 777 | In, Klooger was traded to the White Sox and after posting a 1-1 record with a 4.50 ERA, he was released. 778 | 779 | References 780 | 781 | External links 782 | , or Retrosheet, or Pura Pelota (Venezuelan Winter League) 783 | 784 | Category:1941 births 785 | Category:Living people 786 | Category:Albuquerque Dukes players 787 | Category:American expatriate baseball players in Canada 788 | Category:Baseball players from Connecticut 789 | Category:Birmingham Barons players 790 | Category:Chicago White Sox players 791 | Category:Clinton C-Sox players 792 | Category:Columbus Jets players 793 | Category:Evansville White Sox players 794 | Category:Hawaii Islanders players 795 | Category:Kansas City Athletics players 796 | Category:Major League Baseball pitchers 797 | Category:Miami Marlins (IL) players 798 | Category:Oklahoma City 89ers players 799 | Category:Omaha Royals players 800 | Category:Sportspeople from New London, Connecticut 801 | Category:Portland Beavers players 802 | Category:Rochester Red Wings players 803 | Category:Rojos del Águila de Veracruz players 804 | Category:Salt Lake City Bees players 805 | Category:Savannah White Sox players 806 | Category:Tac 807 | ==================== 808 | def is_bird(img): 809 | """Check whether an image is a bird""" 810 | return [pic1 for pic1 in img if pic1.type == "bird"] 811 | 812 | def is_frog(img): 813 | """Check whether an image is a frog""" 814 | return [pic1 for pic1 in img if pic1.type == "frog"] 815 | 816 | def is_clown(img): 817 | """Check whether an image is a clown""" 818 | return [pic1 for pic1 in img if pic1.type == "clown"] 819 | 820 | def is_woman(img): 821 | """Check whether an image is a woman""" 822 | return [pic1 for pic1 in img if pic1.type == "woman"] 823 | 824 | def is_panda(img): 825 | """Check whether an image is a panda""" 826 | return [pic1 for pic1 in img if pic1.type == "panda"] 827 | 828 | def is_bear(img): 829 | """Check whether an image is a bear""" 830 | return [pic1 for pic1 in img if pic1.type == "bear"] 831 | 832 | def is_goat(img): 833 | """Check whether an image is a goat""" 834 | return [pic1 for pic1 in img if pic1.type == "goat"] 835 | 836 | def is_moose(img): 837 | """Check whether an image is a moose""" 838 | return [pic1 for pic1 in img if pic1.type == "moose"] 839 | 840 | def is_drum(img): 841 | """Check whether an image is a drum""" 842 | return [pic1 for pic1 in img if pic1.type == "drum"] 843 | 844 | def is_elephant(img): 845 | """Check whether an image is an elephant""" 846 | return [pic1 for pic1 in img if pic1.type == "elephant"] 847 | 848 | def is_polar(img): 849 | """Check whether an image is a polar bear""" 850 | return [pic1 for pic1 in img if pic1.type == "polar"] 851 | 852 | def is_wolf(img): 853 | """Check whether an image is a wolf""" 854 | ==================== 855 | def is_bird(img): 856 | """Check whether an image is a bird""" 857 | bird_dict = { 858 | 'chicken': [0.91, 0.9], 859 | 'cow': [0.8, 0.8], 860 | 'duck': [0.5, 0.9], 861 | 'goose': [0.6, 0.7], 862 | 'rooster': [0.5, 0.8] 863 | } 864 | 865 | return any(bird_dict.get(c, [0.0, 0.0]) > 0.4 for c in img) 866 | 867 | The function works, but it's really slow. It takes about a minute on the computer I am using to test it (a thinkpad x200 with 2 gig of RAM). Is there a faster way to detect birds in an image? 868 | 869 | A: 870 | 871 | I would just use OpenCV for that. There is a tutorial for it on their website. There you can specify various features that you want to detect and even the models to use if needed. Once you've done that, and you're happy with the results, OpenCV's HoughLines will find you the lines in an image, and you can use that to determine whether or not the image contains birds. 872 | 873 | <|endoftext|> they were more familiar with the 874 | 875 | situation on the ground on February 4, 2014 than on February 4, 2014. 876 | 877 | (Doc. 67, Vol. 2 at 27-29). In addition, because of the inconsistency 878 | 879 | between the state’s and Mr. Sparks’s accounts, the police could not 880 | 881 | determine whether Mr. Sparks was really armed with a gun. (Id.). 882 | 883 | Further, an individual’s clothing can conceal a weapon, but a 884 | 885 | warrantless search of the outer clothing of a suspect is valid only if 886 | 887 | the police had reason to believe that the suspect was armed. United 888 | 889 | States v. Smith, 264 F.3d 1012, 1021 (10th Cir. 2001) (“It is also 890 | 891 | inconceivable that an individual’s outer clothing could completely 892 | 893 | disclose whether he is armed or not 894 | ==================== 895 | def is_bird(img): 896 | """Check whether an image is a bird""" 897 | return True in bird_extensions 898 | 899 | def convert_keras_to_tensorflow(x_input): 900 | """Convert keras to tensorflow""" 901 | inputs = tf.keras.Input(name="keras", data_format='channels_last', shape=(None, None, None, 3)) 902 | x_output = inputs.send(x_input) 903 | return x_output 904 | 905 | def convert_tensorflow_to_keras(x_output): 906 | """Convert tensorflow to keras""" 907 | input = tf.keras.Input(name='tensorflow', data_format='channels_last', shape=(None, None, None, 3)) 908 | x_input = input.send(x_output) 909 | return x_input 910 | 911 | def convert_tf_model_to_keras(keras_model): 912 | """Convert tensorflow model to keras model""" 913 | input_layer = keras_model.layers[0] 914 | output_layer = keras_model.layers[-1] 915 | x_input = tf.keras.Input(name='tensorflow', data_format='channels_last', shape=(None, None, None, 3)) 916 | input = x_input 917 | # Apply keras model to x_input 918 | output = keras_model.predict(x_input) 919 | x_output = tf.keras.backend.reshape(output, shape=(None, None, None, 3)) 920 | # Apply tensorflow model to x_output 921 | output = output_layer(output) 922 | output = tf.keras.backend.reshape(output, shape=(None, None, None, 3)) 923 | x_input = x_output 924 | return x_input 925 | 926 | def preprocess(x_input, output_path): 927 | """Preprocess images""" 928 | # Preprocess with keras-style crop layer: x_input[..., :-5, :, :3] 929 | 930 | ==================== 931 | def is_bird(img): 932 | """Check whether an image is a bird""" 933 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 934 | return (0 0 and bird_amount % bird_count!= 0 1048 | # Shrink it by one pixel 1049 | image = img2im.draw_image(image, size=((image.shape[0]-2), 1050 | (image.shape[1]-2))) 1051 | # If bird is outside sea of pixels, extract image 1052 | if outside_bird: 1053 | img = img2im.draw_image(image[outside_bird:bird_amount+outside_bird], 1054 | (bird_count - bird_amount) % bird_count) 1055 | return img 1056 | 1057 | def main(): 1058 | """Read an image from a directory and get the bird count""" 1059 | for root, dirs, filenames in os.walk('data'): 1060 | # Iterate through the filenames 1061 | for filename in filenames: 1062 | # Open image 1063 | 1064 | ==================== 1065 | def is_bird(img): 1066 | """Check whether an image is a bird""" 1067 | with ImageFilter(img, ['FALCON.BIRD']): 1068 | return True 1069 | 1070 | In the function is_bird, I want to perform some operation on img to check if it is a bird, but something like "with ImageFilter(img, ['FALCON.BIRD'])" doesn't work. 1071 | How do I write the code? 1072 | 1073 | A: 1074 | 1075 | ImageFilter.filter is an object. You can't call it directly, you should call it on the img object. For example: 1076 | with ImageFilter(img, 'FALCON.BIRD'): 1077 | print(img) 1078 | 1079 | <|endoftext|>So i've looked for answers to this for a while, most seem to say, "just turn it down", but i want to be able to hear it on keystroke level. 1080 | 1081 | Ackk... 1082 | 1083 | also i just found this: 1084 | 1085 | http://www.audiomedia.com/au/listen.php?list=12 1086 | 1087 | ... 1088 | 1089 | "User convenience: FM mode and PCM volume control via keyboard were added as you can change between them with the Fn button. In FM mode, key-lock is included which allows you to use it as a portable radio. In PCM mode, a pair of arrows are available for manually changing the volume and muting/speaker setting of selected channels. After start or resume of the station program, FM data is automatically updated." 1090 | 1091 | i guess that if you press "PM" on the keyboad, you can change volume. 1092 | 1093 | I think that turning the PCM volume all the way up just adjusts the automatic volume. If that's so, just make sure you adjust it to match your volume knob. And also, this just adjusts the automatic volume, so if you don't want to change the current volume when you switch to AM radio or whatever, don't turn the PCM volume up all the way! And of course, if you press Fn+Up or Fn+Down to change channels, you still have to use the arrow keys. 1094 | 1095 | First of all, I'm going to say that your car is not a Dodge Magnum. The RM6 doesn't work well in that car for 3 reasons: 1096 | 1097 | 1. Windows 2000 is incompatible with the OEM AM Radio on the cars, even if they upgraded to WinXP. Notable hardware problems are also a factor here. 2. 1098 | ==================== 1099 | def is_bird(img): 1100 | """Check whether an image is a bird""" 1101 | # Load the image and convert it to grayscale 1102 | img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 1103 | 1104 | # Threshold the grayscale image, and create a binary image 1105 | lower_gray = 0 1106 | upper_gray = 255 1107 | img_threshed = cv2.threshold(img_gray, lower_gray, upper_gray, cv2.THRESH_BINARY_INV) 1108 | 1109 | # Detect the bird via a template matching approach 1110 | # Template matching uses the bird template to match it in every 1111 | # frame. If the ratio between bird and background (non-bird) 1112 | # pixels is above some threshold (the value is determined in the 1113 | # function), then the frame is declared as containing a bird. 1114 | bird = cv2.matchTemplate(img_threshed, bird_template, cv2.TM_CCOEFF_NORMED) 1115 | bird = bird / bird.max() 1116 | # Display the image with the results of the bird detection 1117 | cv2.imshow("detected birds", bird) 1118 | cv2.waitKey(0) 1119 | return bird.any() > 0.2 1120 | 1121 | image = cv2.imread('cifar10_bird.jpg') 1122 | cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 1123 | is_bird = is_bird(image) 1124 | if is_bird == 1: 1125 | print('Got a bird!') 1126 | else: 1127 | print('No bird here!') 1128 | 1129 | Fully zoom in the first column, you should see one very distinct pair of white round dots at the far left end. You can see the template matching matched on image, as they're detected with an extremely high score. If you want to do some more research on how to improve detection in the context of this project (i.e. detection accuracy), please read this post, which is related to my above link. 1130 | 1131 | <|endoftext|> img_h - (h *.85)): 1232 | return True 1233 | return False 1234 | 1235 | However, when I try to run the is_bird function like so: 1236 | for img_path in sorted(image_list): 1237 | if is_bird(img_path): 1238 | print("Image contains a bird") 1239 | break 1240 | 1241 | I get this error: 1242 | if is_bird(img_path): 1243 | TypeError: 'NoneType' object is not callable 1244 | 1245 | I understand that None is not callable but I don't understand why this is not a function. 1246 | I did some research online and discovered that the turtle library was making a python turtle object of the canvas and then overriding the apply() method. But I was wondering if there's a better way to do this. 1247 | 1248 | A: 1249 | 1250 | This is not related to any class of python. It is because SURF doesn't return a class but rather a dict with necessary information. For eg: 1251 | SURF(image_list[0],1,1,3) 1252 | 1253 | Return a dictionary such as: 1254 | {'image_x':0, 'image_y':0, 'feat_size':5, '_pixel_loc':[0, 0, 0]} 1255 | 1256 | A dict object is not callable hence your error. 1257 | 1258 | <|endoftext|>Editor's note: This story has been updated with additional reporting. 1259 | 1260 | SALT LAKE CITY — Attorney General Sean Reyes said Tuesday that he would be meeting with some of Utah's federal agents on Wednesday to discuss their strategy for dealing with a number of high-profile drug cases, a meeting he was surprised to learn about through media reports. 1261 | 1262 | Federal and state officials previously planned 1263 | ==================== 1264 | def is_bird(img): 1265 | """Check whether an image is a bird""" 1266 | 1267 | numpy.histogram(img, nbins=8, normed=1) 1268 | 1269 | scores = np.array([0, 0, 0, 1, 0, 0, 0, 0], dtype=np.float32) 1270 | 1271 | i = 0 1272 | while (scores[i] >= 0.5): 1273 | i += 1 1274 | 1275 | return scores[i] == 1 1276 | 1277 | def is_cat(img): 1278 | """Check whether an image is a cat""" 1279 | 1280 | eigen_cat = np.einsum('iik,ijkl->ijk', img, img) 1281 | 1282 | numpy.histogram(eigen_cat, nbins=8, normed=1) 1283 | 1284 | scores = np.array([0, 0, 0, 1, 0, 0, 0, 0], dtype=np.float32) 1285 | 1286 | i = 0 1287 | while (scores[i] >= 0.5): 1288 | i += 1 1289 | 1290 | return scores[i] == 1 1291 | 1292 | def is_dog(img): 1293 | """Check whether an image is a dog""" 1294 | 1295 | eigen_dog = np.einsum('iik,ijkl->ijk', img, img) 1296 | 1297 | numpy.histogram(eigen_dog, nbins=8, normed=1) 1298 | 1299 | scores = np.array([0, 0, 0, 1, 0, 0, 0, 0], dtype=np.float32) 1300 | 1301 | i = 0 1302 | while (scores[i] >= 0.5): 1303 | i += 1 1304 | 1305 | return scores[i] == 1 1306 | 1307 | def get_support_images(dtype=np.float32): 1308 | """Get image support from dtype, returns a list of images 1309 | This function is primarily intended for dtype=np.float32""" 1310 | 1311 | if dtype == np.float32: 1312 | support = list() 1313 | 1314 | img_ 1315 | ==================== 1316 | def is_bird(img): 1317 | """Check whether an image is a bird""" 1318 | 1319 | if img.area_name()!= "elephant": 1320 | return False 1321 | 1322 | # Check 3 rounds of translation, where only translational shifts remain 1323 | for i in range(3): 1324 | for t in range(6): 1325 | ret = img.translate_row_tiles(i, t) 1326 | if ret.area_name() == "birder": 1327 | return True 1328 | 1329 | return False 1330 | 1331 | Here's a short Python test-suite on real images that you might want to run. 1332 | import numpy as np 1333 | import cv2 1334 | 1335 | filenames = [] 1336 | 1337 | # Grab some more image filenames 1338 | filenames.append("img/elephant-with-words.jpg") 1339 | filenames.append("img/eagle-with-headphones.jpg") 1340 | filenames.append("img/eagle-with-wings.jpg") 1341 | filenames.append("img/knot.jpg") 1342 | 1343 | img_list = [] 1344 | for filename in filenames: 1345 | img = cv2.imread(filename) 1346 | if img is None: 1347 | print("cannot read", filename) 1348 | continue 1349 | if not is_bird(img): 1350 | print("Not a bird:", filename) 1351 | continue 1352 | img_list.append(img) 1353 | 1354 | np.random.seed(1234) 1355 | 1356 | # Build up a random bitmask image of all zeros and ones 1357 | # 5% of the pixels should be ones 1358 | all_ones = np.random.randint(0, 100, size=(256, 256, 3)) > 99 1359 | 1360 | # A very simple colour descriptor 1361 | # pixels are all in range [0, 255] and ones = green 1362 | frozenset(map(lambda p: (0, 255, 0), all_ones)) 1363 | 1364 | # Apply a brightness transform that cycles over values from 0 to 255 1365 | # and reduces the contrast 1366 | transform = 1367 | ==================== 1368 | def is_bird(img): 1369 | """Check whether an image is a bird""" 1370 | bird_train_path = "Data/bird.jpg" 1371 | bird_train_png = open(bird_train_path, 'rb').read() 1372 | bird_test_png = open(bird_test_path, 'rb').read() 1373 | # for predicting.img: 1374 | # train_png, _ = imageio.imread(bird_train_png) 1375 | # test_png, _ = imageio.imread(bird_test_png) 1376 | 1377 | p1, p2, p3 = bird_train_png.split(' ') 1378 | # p1: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x00\x01\x01\x00\x00\x00\x00' 1379 | # p2: b'\x89\x01\x00\x02\x00\x00\x00\x00\x04\x00\x00\x01\x00\x01\x00\x00\x00\x00\x00' 1380 | # p3: b'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' 1381 | # print("p1:", p1) 1382 | # print("p2:", p2) 1383 | # print("p3:", p3) 1384 | # return p1==p2 and p2==p3 1385 | 1386 | img_list = [img] 1387 | idx_list = np.array(idx, dtype='uint8') 1388 | # print(idx_list) 1389 | img_idx = 0 1390 | idx_list = img_idx + idx_list 1391 | # img_list = img_list[idx_list] 1392 | ==================== 1393 | def is_bird(img): 1394 | """Check whether an image is a bird""" 1395 | bird_char = [4,2,6,1,7,1,6,2,7,3,2,7,4,6,6,7,7,2,3,4,5,3,5,4,2,6,6,7,4,6,5,4,5,4,6,2,4,4,5,4,6,5,4,7,7,3,2,4,2,5,3,2,6,2,2,4,3,4,6,4,3,3,3,2,4,4,4,4,3,3,4,5,5,2,4,3,3,2,3,4,3,4,3,5,3,4,2,5,3,5,2,3,2,3,4,4,4,5,4,5,4,4,4,3,5,3,2,4,2,4,2,3,4,2,4,2,3,4,4,5,3,5,4,3,5,3,2,5,3,2,2,4,3,3,3,3,3,4,3,4,3,5,3,4,3,4,4,3,3,2,2,5,2,5,4,4,2,2,2,4,3,2,5,2,3,2,2,4,3,3,3,4,3,2,4,3,4,4,3,3,3,3,3,4,5,4,3,5,3,5,5,5,4,3,2,5,3,4,5,3,2,4,2,4,2,2,4,3,3,4,2,2,4,4,5,5,2,4,3,3,2,5,5,5,3,2,5,5,5,5,5,3,4,5,3,4,2,4,4,4,5,5,4,5,5,5,5,5,5,3,2,3 1396 | ==================== 1397 | def is_bird(img): 1398 | """Check whether an image is a bird""" 1399 | # The first find must not be the bird 1400 | # The second is at the opposite end 1401 | first = img[0] 1402 | second = img[0] 1403 | # Look at the distance of the points on the edge of the bird 1404 | point_diff = (second[1] - first[0]) + (second[2] - first[1]) 1405 | # Check if the distance is greater than the width/height of the image 1406 | if (point_diff > img[0] * img[1]): 1407 | return False 1408 | elif (point_diff < -img[0] * img[1]): 1409 | return True 1410 | return False 1411 | 1412 | b = Image.open('/Users/alex/desktop/bird.jpg') 1413 | w, h = b.size 1414 | 1415 | b1 = b.crop((0,0,w,h)) 1416 | b2 = b.crop((w - w - b.size[0],0,w - b.size[0],h)) 1417 | 1418 | if (b1.mode!= 'RGB' or b2.mode!= 'RGB'): 1419 | b1.convert('RGB') 1420 | b2.convert('RGB') 1421 | 1422 | bird = Image.open('/Users/alex/desktop/bird2.jpg') 1423 | bird_rgb = bird.convert('RGB') 1424 | bird_bgr = bird.convert('BGR') 1425 | 1426 | bird_grey = ImageOps.grey_image(bird_rgb) 1427 | 1428 | bird_bgr = ImageOps.convert(bird_bgr, bird_grey, Image.BGR) 1429 | bird_grays = ImageOps.grey_image(bird_bgr) 1430 | 1431 | bird_gray_delta = bird_grays.getimage() 1432 | 1433 | """These two check if the bird is not rotated or skewed""" 1434 | 1435 | bird_gray_same_size = (bird_gray_delta!= bird_gray) 1436 | bird_gray_skew = bird_gray_delta == (bird_gray + bird_gray.size) 1437 | bird_gray_rotated = bird_gray_skew == (bird_gray 1438 | ==================== 1439 | def is_bird(img): 1440 | """Check whether an image is a bird""" 1441 | image_list = img.split(',') 1442 | for i in image_list: 1443 | print(i) 1444 | # How do i apply OpenCV to the images as strings?? 1445 | # if img.lower() == 'bird': 1446 | # return True 1447 | #else: 1448 | # return False 1449 | return False 1450 | 1451 | Now im having a hard time finding a way to convert the img into a string or something of the like because there are two.tif in the image. 1452 | So how can i do this?? 1453 | 1454 | A: 1455 | 1456 | import cv2 1457 | 1458 | for img in my_img_list: 1459 | if(is_bird(img)): 1460 | print("bird detected") 1461 | 1462 | should work 1463 | 1464 | <|endoftext|>var c3 = {}; 1465 | var global_help = { 1466 | name: 'Navigation', 1467 | description: 'Universal Explorer Controller', 1468 | version: 1 1469 | }; 1470 | 1471 | var click = function(event) { 1472 | c3.focus(event.location); 1473 | } 1474 | 1475 | c3.global_help.click = click; 1476 | c3.document.addEventListener('mousedown', click, false); 1477 | 1478 | c3.create = function() { 1479 | var canvas = document.createElement('canvas'); 1480 | canvas.width = 640; 1481 | canvas.height = 480; 1482 | c3.canvas = canvas; 1483 | 1484 | var context = canvas.getContext('2d'); 1485 | 1486 | // This will register the buttons with the 1487 | // handlers you want 1488 | c3.buttons.register({ 1489 | on: 'Click', 1490 | passEvent: true 1491 | }); 1492 | 1493 | return c3; 1494 | }; 1495 | 1496 | c3.on = function(event, fn) { 1497 | this.events[event] = fn; 1498 | return this; 1499 | }; 1500 | 1501 | c3.register = function(class_name, event, fn) { 1502 | if (this.events[event]) { 1503 | this.events[event].call(this, fn); 1504 | } else { 1505 | console.error( 1506 | ==================== 1507 | def is_bird(img): 1508 | """Check whether an image is a bird""" 1509 | gt_horse = (img[500:1000, 500:1000] == '98') 1510 | gt_bird = (img[500:1000, 1029:1060] == '32') 1511 | return gt_bird or gt_horse 1512 | 1513 | def load_data(dir): 1514 | if os.path.exists(dir): 1515 | df = pd.DataFrame() 1516 | for filename in os.listdir(dir): 1517 | img_path = os.path.join(dir, filename) 1518 | img = cv2.imread(img_path) 1519 | # Make sure we have a bird and a horse 1520 | if not is_bird(img): 1521 | continue 1522 | if not is_horse(img): 1523 | continue 1524 | df = df.append(pd.DataFrame([[img.shape[0], img.shape[1], img.shape[2]], filename, filename], index=[0, 1, 2])) 1525 | return df 1526 | 1527 | train = load_data('/home/ptb/kitti/kitti/trains/bird') 1528 | train.columns = ['roi', 'image', 'label'] 1529 | train.to_csv('bird_train.csv') 1530 | 1531 | test = load_data('/home/ptb/kitti/kitti/test/bird/') 1532 | test.columns = ['roi', 'image', 'label'] 1533 | test.to_csv('bird_test.csv') 1534 | 1535 | train.image.rename(columns={"image": "frame", "label": "label"}, inplace=True) 1536 | test.image.rename(columns={"image": "frame", "label": "label"}, inplace=True) 1537 | 1538 | A: 1539 | 1540 | Adding to @ 1541 | ==================== 1542 | def is_bird(img): 1543 | """Check whether an image is a bird""" 1544 | area = get_area(img) 1545 | return area > 70 and area < 95 1546 | 1547 | 1548 | def extract_peo(image): 1549 | """extracts the pose for each person in the photo""" 1550 | f1, t1, f2, t2 = open_coords(image) 1551 | bird = np.array([[f2, t2, [0, 0, 0], [0, 0, 0]]]) 1552 | areas = image.astype(np.int32) 1553 | labels = np.array([0, 0, 0, 0]) 1554 | for i in range(3): 1555 | for j in range(4): 1556 | labels[i][j] = is_bird(image[areas[i][j] * 2:areas[i][j] * 2 + 1, :]) 1557 | bird = np.concatenate((bird, np.zeros(t1[i], 1, dtype=np.float32)), axis=1) 1558 | bird = np.concatenate((bird, np.zeros(f1[j], 1, dtype=np.float32)), axis=0) 1559 | return labels, bird 1560 | 1561 | 1562 | def pose_rec(image): 1563 | """recognizes the poses for the people in the image""" 1564 | # get the coords 1565 | f1, t1, f2, t2, pose = open_coords(image) 1566 | bird = np.array([[f2, t2, [0, 0, 0], [0, 0, 0]]]) 1567 | areas = image.astype(np.int32) 1568 | # find the people 1569 | people = np.nonzero(np.diff(np.array([[1,2,3], [4,5,6]], dtype=np.int32)) == 0)[0] 1570 | person_colors = np.array([(0,0,0),(0,0,0)]) 1571 | for 1572 | ==================== 1573 | def is_bird(img): 1574 | """Check whether an image is a bird""" 1575 | return os.path.splitext(img)[1].upper() == "BIRD" 1576 | 1577 | def is_fish(img): 1578 | """Check whether an image is a fish""" 1579 | return os.path.splitext(img)[1].upper() == "FISH" 1580 | 1581 | def is_oar(img): 1582 | """Check whether an image is an oar""" 1583 | return os.path.splitext(img)[1].upper() == "OAR" 1584 | 1585 | def is_plant(img): 1586 | """Check whether an image is a plant""" 1587 | return os.path.splitext(img)[1].upper() == "PLANT" 1588 | 1589 | def is_aquatic(img): 1590 | """Check whether an image is an aquatic feature""" 1591 | return os.path.splitext(img)[1].upper() == "AQUATIC" 1592 | 1593 | def is_chasm(img): 1594 | """Check whether an image is a chasm""" 1595 | return os.path.splitext(img)[1].upper() == "CHASM" 1596 | 1597 | def is_aquatic_unknown(img): 1598 | """Check whether an image is an aquatic feature""" 1599 | return os.path.splitext(img)[1].upper() == "AQUATIC_UNKNOWN" 1600 | 1601 | def is_sandbank(img): 1602 | """Check whether an image is a sandbank""" 1603 | return os.path.splitext(img)[1].upper() == "SANDBANK" 1604 | 1605 | def is_sandpit(img): 1606 | """Check whether an image is a sandpit""" 1607 | return os.path.splitext(img)[1].upper() == "SANDPIT" 1608 | 1609 | def is_sea(img): 1610 | """Check whether an image is a sea""" 1611 | return os.path.splitext(img)[1].upper() == "SEA" 1612 | 1613 | def is_boating(img): 1614 | """Check whether an image is boating or sailing""" 1615 | return os.path.splitext(img)[1].upper() == "BOATING" 1616 | ==================== 1617 | def is_bird(img): 1618 | """Check whether an image is a bird""" 1619 | # define the bird's eye box 1620 | A, B = img.shape[:2] 1621 | cA, cB = img.shape[2:] 1622 | 1623 | # - ------------------------- - - ------------------------- - - ------------------------- 1624 | # | | | 1625 | # | | | 1626 | # | | | 1627 | # - ------------------------- - - ------------------------- - - ------------------------- 1628 | 1629 | # - ------------------------- - - ------------------------- - - ------------------------- 1630 | # | | | 1631 | # | | | 1632 | # | | | 1633 | # - ------------------------- - - ------------------------- - - ------------------------- 1634 | 1635 | 1636 | ==================== 1637 | def is_bird(img): 1638 | """Check whether an image is a bird""" 1639 | # This function requires numpy as installed 1640 | bird_coords = np.array(image_as_bird(img)) 1641 | for x in range(bird_coords.shape[0]): 1642 | for y in range(bird_coords.shape[1]): 1643 | if bird_coords[x,y] > 0: 1644 | return True 1645 | return False 1646 | 1647 | 1648 | #--- Generic function for processing: trim, flip, resize etc. ---# 1649 | def trim_and_process(img, size, trim_to_window=False, 1650 | is_bird=is_bird, 1651 | drop_boxes=True, crop_to_window=False, 1652 | generate_mask=True): 1653 | """ 1654 | Convert an image, for example trimming, cropping, or resizing. 1655 | See Note [Img pre-processing] in the INSTALL file. 1656 | :param img: (PIL Image) the original image to be pre-processed 1657 | :param size: (int) number of pixels to be cropped and scaled by this function 1658 | :param trim_to_window: (bool) whether to trim the original image by removing 1659 | a region of the image in order to make it completely fit the image size 1660 | this applies when img is an image 1661 | :param is_bird: (bool) whether img is a bird (True), or an image of a cat (False) 1662 | :param drop_boxes: (bool) whether to drop the bounding boxes of small pets 1663 | :param crop_to_window: (bool) whether the result should be cropped to the size 1664 | of the image itself, or be completely filled in by the image at that size 1665 | :param generate_mask 1666 | ==================== 1667 | def is_bird(img): 1668 | """Check whether an image is a bird""" 1669 | bird = { 1670 | # a white or gray bird's beak 1671 | "beak": "FFFF0000", 1672 | 1673 | # a white or gray bird's ear 1674 | "ear": "FF00FF00", 1675 | 1676 | # a non-white or non-gray bird's eye 1677 | "eye": "00FF0000", 1678 | 1679 | # a non-white or non-gray beak 1680 | "beak_false": "FF0000FF", 1681 | 1682 | # a white beak when looking straight down 1683 | "beak_down": "FFFFFF00", 1684 | 1685 | # a white beak when looking down at a right angle 1686 | "beak_up": "FF00FF00", 1687 | 1688 | # a white beak when looking to the left 1689 | "beak_left": "FF0000FF", 1690 | 1691 | # a white beak when looking to the right 1692 | "beak_right": "FFFFFF00", 1693 | 1694 | # a black bird's beak 1695 | "beak_black": "FFFF0000", 1696 | 1697 | # a black bird's eye 1698 | "eye_black": "00FF0000", 1699 | 1700 | # a black bird's ear 1701 | "ear_black": "FF00FF00", 1702 | 1703 | # a non-black bird's beak 1704 | "beak_gray": "FF0000FF", 1705 | 1706 | # a non-black bird's eye 1707 | "eye_gray": "00FF0000", 1708 | 1709 | # a non-black bird's ear 1710 | "ear_gray": "FF00FF00", 1711 | 1712 | # a gray bird 1713 | ==================== 1714 | def is_bird(img): 1715 | """Check whether an image is a bird""" 1716 | bird = r'\\BIRD.{}' 1717 | chr = "0123456789ABCDEFabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 1718 | area = "*:{}".format(bird.count('*')) 1719 | main = "*:{}".format(bird.count('*')) 1720 | # the bird detector 1721 | birdDetector = '{}/{}'.format(bird, chr[:4] + area) 1722 | imgDetector = '{}/{}'.format(img, chr[:4] + main) 1723 | # detect the image 1724 | img = img_crop(img, (IMG_SIZE_LARGE[1] *.7, IMG_SIZE_LARGE[0] *.3)) 1725 | return img_crop(img, (IMG_SIZE_LARGE[1] *.3, IMG_SIZE_LARGE[0] *.7)) in [birdDetector, imgDetector] 1726 | 1727 | # load the training set 1728 | train_dir = os.path.join(data_dir, 'train') 1729 | imgs_list = glob.glob(os.path.join(train_dir, '*.png')) 1730 | # plt.imshow(im) 1731 | im_x1 = [] 1732 | im_y1 = [] 1733 | im_x2 = [] 1734 | im_y2 = [] 1735 | for im in imgs_list: 1736 | im_x1.append(len(im_x1)) 1737 | im_x2.append(len(im_x2)) 1738 | im_y1.append(len(im_y1)) 1739 | im_y2.append(len(im_y2)) 1740 | img = cv2.imread(im) 1741 | im_x1.append(len(im_x1)) 1742 | im_y1.append(len(im_y1)) 1743 | if is_bird(img): 1744 | im_x1. 1745 | ==================== 1746 | def is_bird(img): 1747 | """Check whether an image is a bird""" 1748 | try: 1749 | bird = image_in_face.filter_by(tag='bird').all()[0] 1750 | img = image_in_face.filter_by(tag='face')[0] 1751 | return (bird.x_coord > x_coord(img) + img.shape[1] 1752 | and bird.y_coord > y_coord(img) + img.shape[0]) 1753 | except IndexError: 1754 | return False 1755 | 1756 | 1757 | def is_face(img): 1758 | """Check whether an image is a face""" 1759 | try: 1760 | faces = image_in_face.filter_by(tag='face') 1761 | return faces.all() 1762 | except IndexError: 1763 | return False 1764 | 1765 | 1766 | def add_to_folder(dataset, images): 1767 | """Move images to a folder, if they don't already exist""" 1768 | for img in images: 1769 | if not os.path.isdir(dataset.folders[0]): 1770 | os.makedirs(dataset.folders[0]) 1771 | if not os.path.isfile(os.path.join(dataset.folders[0], img.filename)): 1772 | os.rename(os.path.join(dataset.folder, img.filename), 1773 | os.path.join(dataset.folders[0], img.filename)) 1774 | <|endoftext|>Smart and elegant, Orla Kiely's range of home and office accessories for the young professional and young couple, part of Orla Kiely's Americana collection, embody an elevated design that captures the playful, playful and heartfelt at once. 1775 | 1776 | Bringing together the latest trends in home and furniture, Kiely Joris creates for you products and accessories 1777 | ==================== 1778 | def is_bird(img): 1779 | """Check whether an image is a bird""" 1780 | img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 1781 | # Extract the region of interest (ROI) 1782 | roi = cv2.resize(img, (240, 240)) 1783 | # Convert from BGR to RGB color space and Otsu's method to get the 1784 | # threshold. 1785 | rgb_img = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB) 1786 | binary_img = cv2.threshold(rgb_img, 0, 255, cv2.THRESH_BINARY)[1] 1787 | 1788 | return binary_img!= 255 1789 | return binary_img 1790 | 1791 | and the following is the code that is being executed: 1792 | def read_rois(): 1793 | """Read roi from.txt file.""" 1794 | rois = [] 1795 | image = np.loadtxt("{}.txt".format(screenshot[0])) 1796 | # Convert array of points to list of numpy arrays 1797 | image = np.array(image) 1798 | n_rois = len(image) 1799 | for n in range(n_rois): 1800 | img = image[n] 1801 | img = np.array(img) 1802 | roi = img[0:480, 0:480] 1803 | roi = cv2.resize(roi, (240, 240)) 1804 | is_bird = is_bird(roi) 1805 | if is_bird: 1806 | roi_noisy = roi + np.random.randn(roi.shape[0], roi.shape[1]) * 1.0 1807 | roi = cv2.resize(roi_noisy, (240, 240)) 1808 | rois.append(roi) 1809 | return ro 1810 | ==================== 1811 | def is_bird(img): 1812 | """Check whether an image is a bird""" 1813 | 1814 | # The bird classification aspect of this problem is based on a great 1815 | # classification algorithm by Felzenszwalb and Huttenlocher (2010) 1816 | # For more info: 1817 | # http://www.ee.ucla.edu/~juergen/papers/Eccv10_BirdClass.pdf 1818 | # 1819 | # The following code is inspired by that paper. 1820 | # The selection of the last features was changed: 1821 | # (1) They used moments in 12 directions in image space, 1822 | # while we use moments in 8 directions in Fourier space. 1823 | # (2) To have a cleaner code, the feature extraction part 1824 | # is in a function, while in their paper it is done in a 1825 | # loop. We made it a function here in order to be able to 1826 | # use it in other programs. 1827 | # 1828 | # A fast implementation of the implementation can be found here: 1829 | # https://gist.github.com/roeder/8e0a49fc17ff8dee7e1e2f4af74e150f 1830 | # 1831 | # Finally, the code below has also been modified in order to 1832 | # work well with the AlexNet network. 1833 | # 1834 | # Based on the use of Gaussian filters, the 1835 | # approximated kernel function in the Fourier domain reads: 1836 | # 1837 | # k(n) = exp(-*(1/h)*|n|^2) 1838 | # 1839 | # With this function, we can evaluate directly all the moments 1840 | # in Fourier space. 1841 | 1842 | # We start from the DC moment, which is the mean value 1843 | # of the whole image. We just make this equal to zero. 1844 | mean_value = 0 1845 | mean_x = mean_y = mean_value 1846 | 1847 | # The first first order moment is the DC moment. 1848 | # We have that 1849 | # 1850 | 1851 | ==================== 1852 | def is_bird(img): 1853 | """Check whether an image is a bird""" 1854 | c = img.stats.get('cls', 0) 1855 | c = c - c.mean() 1856 | # Random forests and LMT filters are by nature weak on 'Bird' 1857 | if c < 0.75: 1858 | return True 1859 | return False 1860 | 1861 | 1862 | # TESTING DIRECT METHODS ---------------------------------------------------- 1863 | 1864 | def test_by_whole_img_direct(img): 1865 | """Test whether the image is bird-related""" 1866 | return is_bird(img) 1867 | 1868 | def test_by_pix_direct(img): 1869 | """Test whether the pixel has bird-related content""" 1870 | return is_bird(img[100:100+40,100:100+40]) 1871 | 1872 | # TESTING RASMUS/MACHINE LABELING METHODS ----------------------------------------- 1873 | 1874 | def ras_mnist(img, colors): 1875 | """Direct method, using OPIATY""" 1876 | if img.opacity < 0.05: 1877 | return False 1878 | z = list(img.z) 1879 | ras_ops = [] 1880 | for z in z: 1881 | # Use existing colors if necessary 1882 | if colors is None: 1883 | try: 1884 | colors = rgb_to_color(z) 1885 | except ValueError: 1886 | colors = colors_to_rgb(z) 1887 | if len(colors) == 2: 1888 | colors = colors + [None] 1889 | if len(colors) == 4: 1890 | colors = colors + [None] 1891 | colors = [None for _ in range(len(colors))] 1892 | elif len(colors) == 3: 1893 | 1894 | ==================== 1895 | --------------------------------------------------------------------------------