def setUp(self): self.t1 = TraitCard("horns", 3) self.t2 = TraitCard("ambush", 1) self.t3 = TraitCard("carnivore", 2) self.t4 = TraitCard("fat-tissue", 0) self.t5 = TraitCard("foraging", 3) self.t6 = TraitCard("herding", 0) self.defSpec = Species(0, 0, 1, [], 0) self.specWGrownBody = Species(0, 1, 1, [], 0) self.specW3t = Species(0, 0, 1, [self.t3, self.t4, self.t5], 0) self.specWAll = Species(0, 1, 2, [self.t4], 0) self.playerWithManyCards = PlayerState( 1, 0, [], [self.t1, self.t2, self.t3, self.t4, self.t5, self.t6]) self.playerForAll = PlayerState(1, 0, [self.specWAll], []) self.playerFor3t = PlayerState(1, 0, [self.specW3t], [self.t6]) self.playerForDefSpec = PlayerState(1, 0, [self.defSpec], [self.t5, self.t6]) self.playerForBodyNewspec = PlayerState( 1, 0, [self.specWGrownBody], [self.t3, self.t4, self.t5, self.t6]) self.noAct = Action4(0, [], [], [], []) self.actGP = Action4(0, [GainPopulation(0, 1)], [], [], []) self.actGB = Action4(0, [], [GainBodySize(0, 1)], [], []) self.actRT = Action4(0, [], [], [ReplaceTrait(0, 1, 1)], []) self.actBT0t = Action4(0, [], [], [], [BuySpeciesBoard(1, [])]) self.actBT1t = Action4(0, [], [], [], [BuySpeciesBoard(1, [2])]) self.actBT2t = Action4(0, [], [], [], [BuySpeciesBoard(1, [2, 3])]) self.actBT3t = Action4(0, [], [], [], [BuySpeciesBoard(1, [2, 3, 4])]) self.actBT4t = Action4(0, [], [], [], [BuySpeciesBoard(1, [2, 3, 4, 5])]) self.addBodyToNewSpec = Action4(0, [GainPopulation(1, 1)], [], [], [BuySpeciesBoard(2, [3])]) self.actAll = Action4(0, [GainPopulation(0, 1)], [GainBodySize(0, 2)], [ReplaceTrait(0, 0, 3)], [BuySpeciesBoard(4, [5])])
def initialize_species(X, Y, positive_examples, negative_examples, minority_flag): # Positive Species species_a = Species(X, Y, positive_examples, negative_examples, 1, 100, minority_flag) # Negative Species species_b = Species(X, Y, negative_examples, positive_examples, 0, 100, not minority_flag) return [species_a, species_b]
def situationFromJson(situation): defend = JsonParsing.speciesFromJson(situation[0]) attack = JsonParsing.speciesFromJson(situation[1]) if not attack or not defend: quit() lNeighbor = JsonParsing.speciesFromJson(situation[2]) or Species(0, 0, 0, [], 0) rNeighbor = JsonParsing.speciesFromJson(situation[3]) or Species(0, 0, 0, [], 0) return defend, attack, lNeighbor, rNeighbor
def readXYZ(xyz, bonds=None, cluster_bond=None, fixed_atoms=None): # extract molecule information from xyz mol = next(pb.readfile('xyz', xyz)) reactant_atom = [a.OBAtom.GetAtomicNum() for a in mol] # Manually give bond information # (Because in metal system the bond information detect by openbabel usually have some problem) if bonds or cluster_bond: m = Molecule(pb.ob.OBMol()) obmol = m.OBMol obmol.BeginModify() for atom in mol: coords = [coord for coord in atom.coords] atomno = atom.atomicnum obatom = ob.OBAtom() obatom.thisown = 0 obatom.SetAtomicNum(atomno) obatom.SetVector(*coords) obmol.AddAtom(obatom) del obatom if cluster_bond: bonds = [(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx(), bond.GetBondOrder()) for bond in pb.ob.OBMolBondIter(mol.OBMol)] #bonds = imaginary_bond(bonds, reactant_atom, fixed_atoms) bonds.extend(cluster_bond) for bond in bonds: obmol.AddBond(bond[0], bond[1], bond[2]) # obmol.ConnectTheDots() obmol.PerceiveBondOrders() # obmol.SetTotalSpinMultiplicity(1) obmol.SetTotalCharge(int(mol.charge)) obmol.Center() obmol.EndModify() mol_obj = gen3D.Molecule(obmol) reactant_graph = Species(xyz_file_to_atoms(xyz)) reactant_bonds = [(i[0] - 1, i[1] - 1) for i in bonds] make_graph(reactant_graph, bond_list=reactant_bonds) else: mol_obj = gen3D.Molecule(mol.OBMol) reactant_graph = Species(xyz_file_to_atoms(xyz)) reactant_bonds = tuple( sorted([(bond.GetBeginAtomIdx() - 1, bond.GetEndAtomIdx() - 1) for bond in pb.ob.OBMolBondIter(mol.OBMol)])) make_graph(reactant_graph, bond_list=reactant_bonds) return mol_obj, reactant_graph
def breed_new_generation(self): self.calculate_genome_adjusted_fitness() self.remove_weak_genomes_from_species() self.remove_stale_species() survived_species: List[Species] = [] children: List[Genome] = [] total_adjusted_fitness: float = self.calculate_total_adjusted_fitness() carry_over: float = 0 for species in self.species: fchild: float = self.population * ( species.get_total_adjusted_fitness() / total_adjusted_fitness) nchild: int = int(fchild) carry_over += fchild - nchild if carry_over >= 1: carry_over -= 1 nchild += 1 if nchild < 1: continue new_species: Species = Species(species.get_top_genome()) new_species.previous_top_fitness = species.previous_top_fitness new_species.staleness = species.staleness survived_species.append(new_species) for _ in range(1, nchild): children.append(species.breed_child()) self.species: List[Species] = survived_species for child in children: self.add_to_species(child)
def speciesFromJson(jsonSpecies): # If the if statement errors out, the input is ill shaped try: if jsonSpecies is False: return False if jsonSpecies[0][0] == "food" and jsonSpecies[1][0] == "body" and jsonSpecies[2][0] == "population" and jsonSpecies[3][0] == "traits": food = jsonSpecies[0][1] body = jsonSpecies[1][1] population = jsonSpecies[2][1] traits = [] hasFatTissue = False for trait in jsonSpecies[3][1] : if JsonParsing.checkTrait(trait): traits.append(trait) if trait == "fat-tissue": hasFatTissue = True if len(jsonSpecies) == 5 and hasFatTissue and jsonSpecies[4][0] == "fat-food": fatFood = jsonSpecies[4][1] else: fatFood = 0 return Species(food, body, population, traits, fatFood) else: pass # TODO: what should actually happen when the labels for an array are wrong? except Exception as e: raise e
def reproduction(self, fitness_array): def check_species(g): for s in self.species: if s.check_if_member(g): return True return False for i, g in enumerate(self.genoms): g.fitness = fitness_array[i] if not check_species(g): self.species.append(Species(g)) n_extint = 0 new_species = [] for s in self.species: s.sort() extinct = s.kill() if extinct: n_extint += 1 else: new_species.append(s.reproduce()) self.species = new_species n_extra = self.clients - len(self.genoms) for i in range(n_extra): random.choice(self.genoms).reproduce_extra()
def __init__(self): self.species_list = [Species("Blob")] self.biome_list = [] #todo: make a graph self.id_to_player = {} #placeholder, set up empty player self.add_player(Player("placeholder"))
def getSpecies(self): self.category = 'species' result_d = json.loads( SwapiService.getSwapi(self.category, self.getId())) self.species = Species(result_d['name'], result_d['classification']) print("Name: {} Classification: {}".format( self.species.name, self.species.classification))
def getSpecies(self): self.category = 'species' self.callServiceThread() self.species = Species(self.result_d['name'], self.result_d['classification']) print("Name: {} Classification: {}".format( self.species.name, self.species.classification))
def setUp(self): self.attacker = Species() self.attacker.traits = [TraitCard(CARNIVORE)] self.defender = Species() self.left_neighbor = Species() self.right_neighbor = Species() self.species_1 = Species(4, 4, 4) self.species_2 = Species(4, 4, 4) self.species_3 = Species(4, 4, 3) self.species_4 = Species(4, 3, 3) self.species_5 = Species(3, 3, 3) self.species_list = [self.species_2, self.species_4, self.species_3, self.species_5, self.species_1]
def add_to_species(self, genome: Genome): for species in self.species: if Genome.is_same_species(species.genomes[0], genome): species.genomes.append(genome) species.previous_top_fitness = max( species.previous_top_fitness, genome.fitness) return self.species.append(Species(genome))
def add_species(self, add_card_list): """ :effect Adds a new species to the right of this Player State's current species :param add_card_list: List of Nat representing indicies of Trait Cards in this Player State's hand to add to the new species. """ trait_list = [self.hand[i] for i in add_card_list] self.species.append(Species(traits=trait_list))
def initializeModels(): model = newModel() board = [0 for x in range(10)] board = [list(board) for x in range(20)] species = Species(model,[board]*2,[[1,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0]],0) assert (len(species.intake) == len(species.output)) species.create() return species
def species(self): map = self._readmap('classes') results = [] for id in map: results.append(Species(id=int(id), name=map[id])) return sorted(results, key=lambda x: x.id)
def setUp(self): self.carnivore = TraitCard(CARNIVORE, 3) self.burrowing = TraitCard(BURROWING, 2) self.fattissue = TraitCard(FATTISSUE, 4) self.foraging = TraitCard(FORAGING, 2) self.horns = TraitCard(HORNS, 6) self.cooperation = TraitCard(COOPERATION, 1) self.scavenger = TraitCard(SCAVENGER, 2) self.species_1 = Species(4, 4, 4, []) self.species_2 = Species(4, 4, 4) self.species_3 = Species(4, 4, 3) self.species_4 = Species(4, 3, 3) self.species_5 = Species(3, 1, 3) self.species_6 = Species(4, 3, 3) self.species_7 = Species(4, 4, 4) self.species_list = [ self.species_2, self.species_4, self.species_3, self.species_5, self.species_1 ] self.player_1 = PlayerState( species=[self.species_4, self.species_5, self.species_6], hand=[self.carnivore]) self.player_2 = PlayerState(species=[self.species_1], hand=[self.carnivore, self.fattissue]) self.player_3 = PlayerState( species=[self.species_2, self.species_3, self.species_7], hand=[self.foraging])
def speciate(self): curgenome: Genome # For stepping through Population curspecies: Species # Steps through species comgenome: Genome # Organism for comparison newspecies: Species # For adding a new species counter: int = 0 # Species counter # Step through all existing organisms for curgenome in self.genomes: # search a species for each genome if len(self.species) == 0: # Create the first species counter += 1 newspecies = Species().new_species(counter) self.species.append(newspecies) newspecies.add_genome(curgenome) # add current genome curgenome.species = newspecies else: for curspecies in self.species: if len(curspecies.genomes) > 0: for comgenome in curspecies.genomes: if curgenome.compatibility( comgenome) < Neat.compat_thresh: # Found compatible species, so add this organism to it curspecies.add_genome(curgenome) curgenome.species = curspecies comgenome = 0 # mark search over break else: # Keep searching for a matching species break if comgenome == 0: break # If we didn't find a match, create a new species if comgenome != 0: counter += 1 newspecies = Species().new_species(counter) self.species.append(newspecies) newspecies.add_genome(curgenome) curgenome.species = newspecies self.last_species = counter # Keep track of highest species return True
def start(self, player): """ Handles the start of a turn by dealing cards and a new Species (if necessary) to the given PlayerState :param player: the PlayerState being dealt to :effect: Updates given PlayerState with additional TraitCards and possible Species """ new_cards = self.cards_to_deal(player) opt_species = (False if player.species else Species()) player.start(opt_species, new_cards)
def mutation_step(self): """Mutates a random node.""" # pick a random node in the graph, i.e. an integer node = random.randint(0, self.N - 1) # get the species currently living on that node species = self.State[node] # mutate the species and add it to the node in question. new_genome = species.mutated_genome() self.State[node] = Species(new_genome, self.fitness(new_genome))
def setUp(self): # Traits (Trait, Food-value) self.carnivore = TraitCard(CARNIVORE, 3) self.burrowing = TraitCard(BURROWING, 2) self.fattissue = TraitCard(FATTISSUE, 4) self.foraging = TraitCard(FORAGING, 2) self.horns = TraitCard(HORNS, 6) self.cooperation = TraitCard(COOPERATION, 1) self.scavenger = TraitCard(SCAVENGER, 2) # Species (Population, Food, Body, Traits, Fat-Storage) self.species1 = Species(1, 0, 2, [self.cooperation]) self.species2 = Species(6, 2, 1, [self.carnivore]) self.species3 = Species(3, 3, 3, [self.fattissue], 0) self.species4 = Species(5, 5, 5, [self.burrowing]) self.species5 = Species(5, 3, 4, [self.foraging]) self.species6 = Species( 2, 1, 7, [self.carnivore, self.fattissue, self.scavenger], 0) self.species7 = Species(7, 1, 6, [self.horns]) self.player1_species = [self.species1, self.species2] self.player2_species = [self.species3, self.species4, self.species5] self.player3_species = [self.species6, self.species7] # Players (Name, Bag, Hand, Species) self.player1 = PlayerState(1, 0, [self.fattissue], self.player1_species) self.player2 = PlayerState(2, 3, [self.fattissue, self.carnivore], self.player2_species) self.player3 = PlayerState(3, 6, [self.burrowing], self.player3_species) self.public_player1 = PlayerState(1, False, False, self.player1_species) self.public_player2 = PlayerState(2, False, False, self.player2_species) self.public_player3 = PlayerState(3, False, False, self.player3_species) self.list_of_players = [self.player1, self.player2, self.player3] # Dealer (List of Players, Watering Hole, Deck) self.dealer1 = Dealer(self.list_of_players, 10, []) # Actions self.food_card_action1 = FoodCardAction(0) self.food_card_action2 = FoodCardAction(1) self.grow_action_pop = GrowAction(POPULATION, 0, 0) self.grow_action_body = GrowAction(BODY, 1, 1) self.add_species_action1 = AddSpeciesAction(0, [1]) self.add_species_action2 = AddSpeciesAction(0, []) self.replace_trait_action1 = ReplaceTraitAction(0, 0, 0) self.replace_trait_action2 = ReplaceTraitAction(2, 0, 1) self.replace_trait_action3 = ReplaceTraitAction(0, 2, 0) # Action4 self.action4_1 = Action4(self.player1, [self.food_card_action1]) self.action4_2 = Action4( self.player2, [self.food_card_action2, self.grow_action_pop])
def setUp(self): # Traits (Trait, Food-value) self.carnivore = TraitCard(CARNIVORE, 3) self.burrowing = TraitCard(BURROWING, 2) self.fattissue = TraitCard(FATTISSUE, 2) self.foraging = TraitCard(FORAGING, 2) self.horns = TraitCard(HORNS, 0) self.cooperation = TraitCard(COOPERATION, 1) self.scavenger = TraitCard(SCAVENGER, 2) # Species (Population, Food, Body, Traits, Fat-Storage) self.species1 = Species(1, 0, 2, [self.cooperation]) self.species2 = Species(6, 2, 1, [self.carnivore]) self.species3 = Species(3, 3, 3, [self.fattissue], 0) self.species4 = Species(5, 5, 5, [self.burrowing]) self.species5 = Species(5, 3, 4, [self.foraging]) self.species6 = Species( 2, 1, 7, [self.carnivore, self.fattissue, self.scavenger], 0) self.species7 = Species(7, 1, 6, [self.horns]) self.player1_species = [self.species1, self.species2] self.player2_species = [self.species3, self.species4, self.species5] self.player3_species = [self.species6, self.species7] # Players (Name, Bag, Hand, Species) self.player1 = PlayerState(1, 0, [self.horns, self.foraging], self.player1_species, ext_player=Player()) self.player2 = PlayerState(2, 3, [self.carnivore, self.fattissue], self.player2_species, ext_player=Player()) self.player3 = PlayerState(3, 6, [self.burrowing], self.player3_species, ext_player=Player()) self.public_player1 = PlayerState(1, False, False, self.player1_species) self.public_player2 = PlayerState(2, False, False, self.player2_species) self.public_player3 = PlayerState(3, False, False, self.player3_species) self.list_of_players = [self.player1, self.player2, self.player3] # Dealer (List of Players, Watering Hole, Deck) self.dealer1 = Dealer(self.list_of_players, 10, []) # Action self.action4_1 = Action4(FoodCardAction(1), [GrowAction(POPULATION, 0, 0)], [], [], []) self.action4_2 = Action4(FoodCardAction(0), [], [], [], [ReplaceTraitAction(1, 0, 1)]) self.action4_3 = Action4(FoodCardAction(0), [], [], [], []) self.action4_list = [self.action4_1, self.action4_2, self.action4_3]
def speciate(self): self.update_threshold() randomized = list(chain.from_iterable(self)) shuffle(randomized) self.clear() for organism in randomized: for species in self: if organism in species: break else: self.append(Species(organism))
def __init__(self, pop_size, pop_cut, pic_size, poly_num, t_img): self.species = [] self.population_size = pop_size self.pop_cut = pop_cut self.tensor_img = t_img self.image_size = pic_size self.number_of_polygons = poly_num for i in range(pop_size): self.species.append( Species(self.image_size, self.number_of_polygons, self.tensor_img))
def __init__(self, Graph: nx.Graph, mutation_ratio: int, uncertainty: float, surrender_option_on: bool): self.Graph = Graph self.N = Graph.number_of_nodes() self.State = [ Species([]) ] * self.N # The state will contain a mapping of nodes to the species that currently lives on it. self.mutation_ratio = mutation_ratio self.uncertainty = uncertainty self.surrender_option_on = surrender_option_on self.surrender_fight_ratio = None
def setUp(self): self.species1J = [["food", 3], ["body", 4], ["population", 5], ["traits", ["carnivore"]]] self.species1 = Species(3, 4, 5, ["carnivore"], 0) self.species2J = [["food", 1], ["body", 3], ["population", 4], ["traits", ["warning-call", "fat-tissue"]], ["fat-food", 1]] self.species2 = Species(1, 3, 4, ["warning-call", "fat-tissue"], 1) self.avgSpeciesJ = [["food", 3], ["body", 4], ["population", 5], ["traits", ["carnivore"]]] self.avgSpecies = Species(3, 4, 5, ["carnivore"], 0) self.fatTissueSpeciesJ = [["food", 1], ["body", 3], ["population", 4], ["traits", ["warning-call", "fat-tissue"]], ["fat-food", 1]] self.fatTissueSpecies = Species(1, 3, 4, ["warning-call", "fat-tissue"], 1) self.fatTraitNoFoodJ = [["food", 1], ["body", 3], ["population", 4], ["traits", ["warning-call", "fat-tissue"]]] self.fatTraitNoFood = Species(1, 3, 4, ["warning-call", "fat-tissue"], 0) self.onePlayerJ = [["id", 1], ["species", [self.species1J, self.species2J]], ["bag", 0]] self.onePlayer = PlayerState(1, 0, [self.species1, self.species2], []) self.twoPlayerJ = [["id", 2], [ "species", [self.avgSpeciesJ, self.fatTissueSpeciesJ] ], ["bag", 0]] self.twoPlayer = PlayerState(2, 0, [self.avgSpecies, self.fatTissueSpecies], []) self.threePlayerJ = [["id", 3], ["species", [self.fatTraitNoFoodJ]], ["bag", 0]] self.threePlayer = PlayerState(3, 0, [self.fatTraitNoFood], [])
def __init__(self, config, population=500, mutation_rate=0.5): self.inputs = 0 self.output = 0 self.model = config self.agents = [] self.population = population self.mutation_rate = mutation_rate self.generation = 1 self.outdated_agents = [] # history agents for i in range(population): self.agents.append(Species(self.model))
def speciate(self): for s in self.species: s.players = [] for player in self.players: species_found = False for s in self.species: if s.same_species(player.brain): s.add_to_species(player) species_found = True break if not species_found: self.species.append(Species(player))
def speciate(self): for s in self.species: del s.genomes[:] for genome in self.genomes: speciesFound = False for s in self.species: if s.belongsTo(genome): s.add(genome) speciesFound = True break if not speciesFound: self.species.append(Species(genome))
def testReplaceTraits(self): playerForReplacingTraits = PlayerState(1, 0, [ Species(0, 0, 1, [TraitCard("foraging"), TraitCard("herding")], 0) ], [TraitCard("carnivore"), TraitCard("horns")]) dealerForReplacingTraits = Dealer([playerForReplacingTraits], 0, []) dealerForReplacingTraits.replaceTraits(0, self.actRT) # the card is still in hand -- it will be removed in the step4 method, not here self.assertEqual(dealerForReplacingTraits.players[0].hand, [TraitCard("carnivore"), TraitCard("horns")]) self.assertEqual( dealerForReplacingTraits.players[0].species[0].traits, [TraitCard("foraging"), TraitCard("horns")])
def add_genome(self, g): for s in self.species: rep = s.get_representitive() if g.distance(rep) < self.neat.config['distance_threshold']: g.species = s s.genomes.append(g) self.genomes.append(g) return new_species = Species(self.neat) g.species = new_species new_species.genomes.append(g) self.genomes.append(g) self.species.append(new_species)