def add_organisms(self, n): """ This function adds n organisms in random locations to the automaton where one organism is infected. """ if n < 1: return if n > self.N * self.M: raise ValueError( "\nOverpopulated environment.\nChoose different N value.") # generate n different locations. locations = set([(random.randrange(self.N), random.randrange(self.M)) for _ in range(n)]) while len(locations) < n: locations.add((random.randrange(self.N), random.randrange(self.M))) # make one infected locations = list(locations) location = random.choice(locations) locations.remove(location) self.organisms.append( Organism(location[0], location[1], states['infected'])) self.infected_count += 1 # add healthy organism for location in locations: self.organisms.append( Organism(location[0], location[1], states['healthy'])) self._update_automaton()
def randomly_add_organisms(game_grid, probability, memories=None): for row in range(len(game_grid)): for column in range(len(game_grid[row])): if decision(probability): if memories: organism = Organism(row, column, memories=memories) else: organism = Organism(row, column) game_grid[row][column] = organism return game_grid
def __init__(self, size, mhcAsrt=False): self.organisms = [] self.mhc = mhcAsrt for i in range(0, size / 2): self.organisms.append(Organism(0)) self.organisms.append(Organism(1)) self.orgsFile = open('organisms.txt', 'w') self.writeOrganisms("Year\tInit\tAfterDeath\tAfterBirth\tMHC\t") self.paraFile = open('parasites.txt', 'w') self.writeParasites("Year\tReproduce\tAlive") self.year = 0
def crossover(self, parents): (firstParent, secondParent) = parents firstChild = [] secondChild = [] for i in range(8): if random.random() > 0.5: firstChild.append(firstParent.playerParam[i]) else: firstChild.append(secondParent.playerParam[i]) if random.random() > 0.5: secondChild.append(secondParent.playerParam[i]) else: secondChild.append(firstParent.playerParam[i]) return (Organism(firstChild), Organism(secondChild))
def reproduce(parents): children = [] #divide the parents into gorups of two #for each couple, generate two children for i in range(len(parents) / 2): p1 = parents[i] i += 1 p2 = parents[i] s1, s2 = get_structs(p1, p2) n1, n2, n3, n4 = add_noise(p1, p2) child1 = Organism(n1, n2, s1) child2 = Organism(n3, n4, s2) children.append(child1) children.append(child2) return children
def add_organism(self, code): """ Adds a new organism with the given code. The code should be written as a list. Should not be used during the simulation phases and updating of the organisms. """ self.organisms.append(Organism(self.env, CURDL_code(code)))
def load_universe(fn): """ Load dataset file from JSON. Parameters ---------- fn : str Input filename of saved universe dataset. Returns ------- population_dict : dict A dict of Organism objects reconstructed from the saved dataset. world : World World object reconstructed from the saved dataset. """ with open(fn, 'r') as f: universe_dict = json.load(f) world = World(universe_dict['world']) population_dict_json = universe_dict['population'] population_dict = {} for species in population_dict_json: population_dict[species] = {} population_dict[species]['statistics'] = copy.deepcopy( population_dict_json[species]['statistics']) population_dict[species]['organisms'] = [ Organism(organism_dict) for organism_dict in population_dict_json[species]['organisms'] ] return population_dict, world
def load_organism(self, name, grid, position): logger.debug("Loading '%s' from '%s'." % (name, self.__library)) name = name.lower() # Add underscore name = name.replace(" ", "_") organism_file = open("%s/%s.yaml" % (self.__library, name)) data = yaml.load(organism_file, Loader=Loader) organism_file.close() # Read defaults and use them to populate anything not specified. defaults_file = open("%s/defaults.yaml" % (self.__library)) defaults = yaml.load(defaults_file, Loader=Loader) defaults_file.close() # Incorporate the defaults into our original data. merged = _merge_trees(data, defaults) organism = Organism(grid, position) organism.set_attributes(merged) if grid.scale() < 0: # This is the first organism we added. logger.info("Setting grid scale to %f." % (organism.Scale)) grid.set_scale(organism.Scale) elif organism.Scale != grid.scale(): logger.log_and_raise(LibraryError, "Mismatch between object scale %f and grid scale %f." % \ (organism.Scale, grid.scale())) return organism
def test_organism(): print(style(HEADER, "---Start: Organism Class checking---")) erron = 0 o = Organism() if (hasattr(o, "dmg") & hasattr(o, "hp")) == 0: print(style(WARNING, "Your organism class doesn't initialize properly")) return if o.hp != 35: erron += 1 print( style(FAIL, "You don't initialize" " the organism's ") + style(UNDERLINE, "hp") + end_style() + style(FAIL, " to ") + style(BOLD, "35") + end_style()) if o.dmg != 10: erron += 1 print( style(FAIL, "You don't initialize" " the organism's ") + style(UNDERLINE, "dmg") + end_style() + style(FAIL, " to ") + style(BOLD, "10") + end_style()) prev_hp = o.hp o.take_damage(10) if (prev_hp - o.hp) != 10: erron += 1 print( style(FAIL, "The ") + style(UNDERLINE, "take_damage") + end_style() + style(FAIL, " method, doesn't modify the hp properly")) if erron == 0: print(style(OKGREEN, "Organism Class, perfect."))
def createDescendant(self, settings, organism): # If higher than a treshold multipied with 2, it could have a descendant if(organism.fitness >= (settings['fission']*2)): organism.fitness -= settings['fission'] # Copy parameters parameters = organism.get_parameters() # Create descendant with mutation self.organisms.append(Organism(settings, parameters=parameters))
def __init__(self, inputs: list, outputs: list, simulation): super().__init__() self.simulation = simulation god = Organism(inputs, outputs) self.populate(god) for _ in range(config.generations): self.simulate() self.speciate() self.replicate()
def populate(self): for i in range(self.population_size): if random.uniform(0, 1) > self.predator_chance: organism = Organism() organism.randomize() self.population.append(organism) else: predator = Predator() predator.randomize() self.population.append(predator)
def placeOrganisms(self): for i in range(20): a = random.randrange(0, 100) o1 = Organism(self.speed_a, self.sense_a, self.wisdom_a, self.size_a, 0, a) o2 = Organism(self.speed_a, self.sense_a, self.wisdom_a, self.size_a, a, 0) o3 = Organism(self.speed_a, self.sense_a, self.wisdom_a, self.size_a, 100, a) o4 = Organism(self.speed_a, self.sense_a, self.wisdom_a, self.size_a, a, 100) self.originalOrganisms.append(o1) self.originalOrganisms.append(o2) self.originalOrganisms.append(o3) self.originalOrganisms.append(o4) self.originalOrganisms.append(o1) self.originalOrganisms.append(o2) self.originalOrganisms.append(o3) self.originalOrganisms.append(o4)
def createPlayer(self): money = 40 print( 'You have 40 to spend on the four traits: speed, sense, wisdom, size.\nIf you dont follow the limit for traits the program might crash and you might lose the data \n' ) input('press any key to continue') os.system('clear') speedp, sensep, wisdomp, sizep = getFixedInput(5, 15, 40) player = Organism(speed, sensep, wisdomp, sizep, 0, 34, 'player') self.originalOrganisms.append(player) self.organisms.append(player)
def init_organisms(self): screen_width, screen_height = self.screen_bounds.bounds() for x in range(0, 10): rand_pos = Vector(randint(100, screen_width - 100), randint(100, screen_height - 100)) rand_vel = Vector(randint(2, Vector.MAX_SPEED), randint(2, Vector.MAX_SPEED)) rand_organism = Organism( rand_pos, rand_vel, 30, (randint(0, 255), randint(0, 255), randint(0, 255))) self.organisms.add(rand_organism)
def add_organism(cell_screen, chromosome): while True: organism_x = random.randint(0, cell_screen.width - 1 - chromosome.width) organism_y = random.randint( 0, cell_screen.height - 1 - chromosome.height()) organism_candidate = Organism(cell_screen, (organism_x, organism_y), chromosome) if not (organism_candidate.conflicts_with_any_of( cell_screen.organisms)): cell_screen.organisms.append(organism_candidate) return
def __init__(self, settings): SceneBase.__init__(self) self.highestSc = 0 #--- Add food to the map ---------------+ self.foods = [] for i in range(0, settings['food_num']): self.foods.append(Food(settings)) #--- Add organisms to the map ---------------+ self.organisms = [] for i in range(0, settings['pop_size']): self.organisms.append(Organism(settings, name= f'gen[x]-org[{str(i)}]' ))
def initPopulation(self, orgNumber): return [ Organism([ random.uniform(1, 3), random.uniform(1, 3), random.randint(10, 30), random.randint(5, 25), random.randint(10, 30), random.randint(10, 30), random.randint(0, 10), random.randint(0, 20) ]) for _ in range(orgNumber) ]
def Update(self, settings): # Set the default food color. for food in self.foods: if(food.dead == False): food.notInVision() # Array for the organism that we will keep newOrganisms = [] highestScore = 0 # Update location, find foods for organism in self.organisms: # Record highest score if(organism.score > highestScore): highestScore = organism.score organism.color = (220,80,220) else: organism.color = (40,40,220) # Update the location of the organisms organism.update_pos(settings) # Check starvation self.starve(settings, organism, newOrganisms) # Throws the organism to the other side of the map. self.borderControl(settings, organism) # Handles feeding, and in vision coloring target = self.interractWithFood(settings, organism) # Creates a child for the organism if it has enough food self.createDescendant(settings, organism) # TODO # I might want to pass everything or at least # the closes 5 thing to the brain to think about it organism.think(settings, target) self.organisms = newOrganisms # If there are less organism than defined create new ones if(len(self.organisms) < settings['pop_size']): self.organisms.append(Organism(settings)) if(self.highestSc != highestScore): self.highestSc = highestScore print("Highest Score:", self.highestSc)
def update_states(self): """ This function makes every organism decide what's his next state (not location) is going to be. (infected / healthy) """ if self.K == MAX_NEIGHBORS: return for o in self.organisms: if not o.is_healthy(): continue neighbors = [] locations = self.neighbors_locations(o)[:(MAX_NEIGHBORS - self.K)] for x, y in locations: neighbors.append(Organism(x, y, self.automaton[x][y])) o.update_state(neighbors, self) self._update_automaton()
def initialize_pop(): population = [] for i in range(POPULATION_SIZE): rate = rand.random() momentum = rand.random() hidden_layers = rand.randint(1, MAX_HIDDEN_LAYERS) struct = "" first = True for j in range(hidden_layers): if not first: struct += "," first = False struct += str(rand.randint(1, MAX_HIDDEN_NODES)) org = Organism(rate, momentum, struct) population.append(org) return population
def click(self, keys): pos = pygame.mouse.get_pos() result = self.get_organism(pos) # print the contents of the location if result is not None: print(result) else: if keys[pygame.K_o]: new_organism = Organism(pos[0], pos[1]) new_organism.randomize() self.population.append(new_organism) elif keys[pygame.K_f]: new_plant = Plant(pygame.Rect(pos[0], pos[1], 6, 6)) self.vegetation.append(new_plant) elif keys[pygame.K_p]: new_predator = Predator(pos[0], pos[1]) new_predator.randomize() self.population.append(new_predator)
def create_new_organisms(self, number_of_organisms): # Chose the number of new organisms of each category proportionally # to the initial number of organisms of each category: total = 0 for category_name in self.settings['organisms']: total += self.settings['organisms'][category_name][ 'initial number of organisms'] for category_name in self.settings['organisms']: n = (self.settings['organisms'][category_name] ['initial number of organisms'] * number_of_organisms) / total for _ in range(n): new_organism = Organism(parent_ecosystem=self) new_organism.configure_with_category_settings( self.settings['organisms'][category_name]) # This adds new_organism to self.newborns and to self.biotope # in a random location: self.add_organism(new_organism) self.organisms_list += self.newborns self.newborns = []
def create_organisms(species_init_dict, init_world=World({}), position_callback=None): ''' Make organism list from an species_init_dict either provided directly or scraped from parameter file. All organisms are from a single species. ''' organism_list = [] list_field_keys = [] for key in species_init_dict.keys(): if type(species_init_dict[key]) is list: if key != 'custom_module_fns': list_field_keys.append(key) # Generate all organisms initial_population = species_init_dict['population_size'] for i in range(initial_population): organism_init_dict = { key: val for key, val in species_init_dict.items() if not key == 'population_size' } for key in list_field_keys: organism_init_dict[key] = organism_init_dict[key][i] if 'initial_positions' in species_init_dict: position = organism_init_dict['initial_positions'] elif position_callback: position = position_callback(init_world.world_size) elif 'position_callback' in species_init_dict: position = (species_init_dict['position_callback']( init_world.world_size)) else: # Vary organism location randomly position = [] for i in range(init_world.dimensionality): position.append(random.randrange(0, init_world.world_size[i])) organism_init_dict['position'] = position # Add organism to organism list organism_list.append(Organism(organism_init_dict)) return organism_list
def initialize_organisms(self): print 'initialize_organisms' """ PRE-CONDITIONS: This initialization must be called AFTER self.initialize_biotope, because we use here Biotope.seek_free_location """ for category_name in self.settings['organisms']: category_settings = self.settings['organisms'][category_name] number_of_organisms = category_settings[ 'initial number of organisms'] for _ in range(number_of_organisms): new_organism = Organism(parent_ecosystem=self) new_organism.configure_with_category_settings( category_settings) # This adds new_organism to self.newborns and to self.biotope # in a random location: self.add_organism(new_organism) self.organisms_list += self.newborns self.newborns = []
def __init__(self, population=None, size=None, sort=True): """ Generates a list of a given size of Organisms with the genotype that there is only queen per row and column. If no size is given an empty population is created :param population: if not None creates a population from a given (sub) population :param size: int :param sort: if True it will sort the population """ if population: self.population = population self.sort() else: if size is None: self.population = [] else: self.population = [Organism() for _ in range(size)] if sort: self.sort() self.accumulated_fitness_values = [] self.accumulated_fitness_computed = False
def evolve(settings, organisms_old, gen): elitism_num = int(floor(settings['elitism'] * settings['pop_size'])) new_orgs = settings['pop_size'] - elitism_num # --- GET STATS FROM CURRENT GENERATION ----------------+ # stats = defaultdict(int) stats = {'BEST': -1000, 'WORST': 1000, 'SUM': 0, 'COUNT': 0} for org in organisms_old: if org.fitness > stats['BEST']: stats['BEST'] = org.fitness if org.fitness < stats['WORST']: stats['WORST'] = org.fitness stats['SUM'] += org.fitness stats['COUNT'] += 1 stats['AVG'] = stats['SUM'] / stats['COUNT'] # --- ELITISM (KEEP BEST PERFORMING ORGANISMS) ---------+ orgs_sorted = sorted(organisms_old, key=operator.attrgetter('fitness'), reverse=True) organisms_new = [] for i in range(0, elitism_num): organisms_new.append( Organism(settings, wih=orgs_sorted[i].wih, who=orgs_sorted[i].who, name=orgs_sorted[i].name)) # --- GENERATE NEW ORGANISMS ---------------------------+ for w in range(0, new_orgs): # SELECTION (TRUNCATION SELECTION) canidates = range(0, elitism_num) # canidates = range(0, settings['pop_size']-1) random_index = choice(a=canidates, size=2, replace=False) org_1 = orgs_sorted[random_index[0]] org_2 = orgs_sorted[random_index[1]] # CROSSOVER crossover_weight = random() wih_new = (crossover_weight * org_1.wih) + ( (1 - crossover_weight) * org_2.wih) who_new = (crossover_weight * org_1.who) + ( (1 - crossover_weight) * org_2.who) # MUTATION mutate = random() if mutate <= settings['mutate']: # PICK WHICH WEIGHT MATRIX TO MUTATE mat_pick = randint(0, 2) # MUTATE: WIH WEIGHTS if mat_pick == 0: index_row = randint(0, settings['hnodes']) index_col = randint(0, settings['inodes']) wih_new[index_row][ index_col] = wih_new[index_row][index_col] * uniform( 0.9, 1.1) # MUTATE: WHO WEIGHTS if mat_pick == 1: index_row = randint(0, settings['onodes']) index_col = randint(0, settings['hnodes']) who_new[index_row][ index_col] = who_new[index_row][index_col] * uniform( 0.9, 1.1) organisms_new.append( Organism(settings, wih=wih_new, who=who_new, name='gen[' + str(gen) + ']-org[' + str(w) + ']')) return organisms_new, stats
""" Basic tests on the Organism class. """ from organism import Organism from curdl import CURDL_code from environment import Environment if __name__ == "__main__": fake_env = Environment() central_only = Organism(fake_env, CURDL_code()) print("Whether the empty org survived: ", central_only.function()) print("Empty org's resources: ", central_only.stock.get_resources()) basic = Organism(fake_env, CURDL_code(['R', '', '', '', '', '', ''])) print("Whether the basic org survived: ", basic.function()) print("Basic org's resources: ", basic.stock.get_resources())
from run import settings # print(np.dot(np.random.uniform(-1, 1, (5, 4)), [1, 2, 3, 4])) a, b = [2, 3] print(a) print(b) print((8 in [])) organisms = [] for i in range(0, 5): wih_init = np.random.uniform( -1, 1, (settings['hnodes'], settings['inodes'])) # mlp weights (input -> hidden) who_init = np.random.uniform( -1, 1, (settings['onodes'], settings['hnodes'])) # mlp weights (hidden -> output) organisms.append( Organism(settings, wih_init, who_init, name='gen[x]-org[' + str(i) + ']')) print(organisms[0]) print(organisms[0].name == organisms[0].name) print(organisms[0].name == organisms[1].name) print(organisms[0] is organisms[0]) print(organisms[0] is organisms[1]) print(organisms[0] == organisms[0]) print(organisms[0] == organisms[1])
def acr_homolog(FAA_FILE, GFF_FILE, FNA_FILE, MIN_PROTEINS_IN_LOCUS, AA_THRESHOLD, DISTANCE_THRESHOLD, DIAMOND_ACRHOMOLOG_FILE, OUTPUT_DIR, isProdigalUsed): ORGANISM_SUBJECT = Organism( [GFF_FILE, FAA_FILE], FNA_FILE, isProdigalUsed, bufferSize=30720, twoFileParse=True) # creates Organism object used to parse gff file GCF = ORGANISM_SUBJECT.GCF # obtaions GCF ID that corresponds to subject acr_hit_record = dict() record_dict = SeqIO.to_dict(SeqIO.parse(FAA_FILE, 'fasta')) HOMOLOGY_FINAL_RESULT_FILE = OUTPUT_DIR + GCF + '_homology_based.out' candidate_loci = second_and_third_filter( first_filter(ORGANISM_SUBJECT, MIN_PROTEINS_IN_LOCUS), GCF, AA_THRESHOLD, DISTANCE_THRESHOLD, MIN_PROTEINS_IN_LOCUS) WP_Maps_Protein = { protein.id: protein for _, proteinList in ORGANISM_SUBJECT.get_ncid_contents().items() for protein in proteinList } Protein_Maps_Loci = { protein.id: loci for loci in candidate_loci for protein in loci } with open(DIAMOND_ACRHOMOLOG_FILE, 'r', 512) as handle: for line in handle: cols = line.rstrip().split('\t') acr, wp, pident, evalue = cols[0], cols[1], cols[2], float( cols[10]) if isProdigalUsed: protein_info_list = record_dict[wp].description.split('#') protein_start = protein_info_list[1].strip() protein_end = protein_info_list[2].strip() protein = 'Protein({0}-{1})'.format(protein_start, protein_end) nc_id = wp[0:wp.rfind('_')] _id = '-'.join([nc_id, protein]) if _id in acr_hit_record: if evalue < acr_hit_record[_id]['evalue']: acr_hit_record[_id] = { 'record': record_dict[wp], 'evalue': evalue, 'nc_id': nc_id, 'protein_id': protein, 'pident': pident, 'acr': acr } else: acr_hit_record[_id] = { 'record': record_dict[wp], 'evalue': evalue, 'nc_id': nc_id, 'protein_id': protein, 'pident': pident, 'acr': acr } else: if wp in acr_hit_record: if evalue < acr_hit_record[wp]['evalue']: acr_hit_record[wp] = { 'record': record_dict[wp], 'evalue': evalue, 'protein_id': wp, 'pident': pident, 'acr': acr } else: acr_hit_record[wp] = { 'record': record_dict[wp], 'evalue': evalue, 'protein_id': wp, 'pident': pident, 'acr': acr } output = '#GCF\tNC ID\tStart\tEnd\tStrand\tProtein ID\taa Length\tGenome_Loci|start|end\tAcr_Hit|pident\tSequence\n' used_wp = set() if len(acr_hit_record) > 0: for wp in acr_hit_record: if wp in Protein_Maps_Loci: if wp not in used_wp: startList = [] endList = [] loci_list = [] for loci_protein in Protein_Maps_Loci[wp]: loci_list.append(str(loci_protein.wp)) startList.append(loci_protein.start) endList.append(loci_protein.end) start = min(startList) end = max(endList) for loci_protein in Protein_Maps_Loci[wp]: protein = loci_protein output += "{}\t{}\t{}\t{}\t{}\t{}\t{}\t".format( GCF, protein.nc, protein.start, protein.end, protein.strand, protein.wp, str(int(((protein.end - protein.start + 1) / 3)))) output += "{}|{}|{}\t".format('-'.join(loci_list), start, end) if loci_protein.id in acr_hit_record: output += "{}|{}\t".format( acr_hit_record[protein.id]['acr'], acr_hit_record[protein.id]['pident']) else: output += "---\t" output += "{}\n".format(protein.sequence) used_wp.add(protein.id) output += "\n" else: protein = WP_Maps_Protein[wp] output += "{}\t{}\t{}\t{}\t{}\t{}\t{}\t".format( GCF, protein.nc, protein.start, protein.end, protein.strand, protein.wp, str(int(((protein.end - protein.start + 1) / 3)))) output += "---\t{}|{}\t".format(acr_hit_record[wp]['acr'], acr_hit_record[wp]['pident']) output += "{}\n\n".format(protein.sequence) # protein = WP_Maps_Protein[wp] # output += "{}\t{}\t{}\t{}\t{}\t{}\t{}\t".format(GCF, protein.nc, protein.start, protein.end, protein.strand, protein.wp, str( int(((protein.end - protein.start + 1) / 3)) ) ) # if wp in Protein_Maps_Loci: # startList = []; endList = []; loci_list = [] # for loci_protein in Protein_Maps_Loci[wp]: # loci_list.append(str(loci_protein.wp)) # startList.append(loci_protein.start) # endList.append(loci_protein.end) # start = min(startList); end = max(endList) # output += "{}|{}|{}\t{}|{}\t".format('-'.join(loci_list), start, end, acr_hit_record[wp]['acr'], acr_hit_record[wp]['pident']) # else: # output += "---\t---\t" # output += "{}\n".format(protein.sequence) with open(HOMOLOGY_FINAL_RESULT_FILE, 'w') as out_handle: out_handle.write(output) return acr_hit_record, HOMOLOGY_FINAL_RESULT_FILE else: return acr_hit_record, None