Exemple #1
0
  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
Exemple #2
0
    def __init__(self, ecosystem, location=None):
        Organism.__init__(self, ecosystem, location)
        self.population = 10000000

        # coccolithophores fight an interminable war with viruses:
        self.virusWaxWane = -1  # starts waning strength virus
        self.virusEfficiency = 5000  # relatively weak
Exemple #3
0
    def __init__(self, rps, mutation_tendency = 0.3, potency = 0.5):
        Organism.__init__(self, mutation_tendency, potency)

# calculate the new tuple indicating the chromosone's RPS strategy
        rps_tuple = tuple([self.post_mutation_value(mutation_tendency, i) for i
            in rps]) 
        self.rps = normalize_tuple(rps_tuple)
Exemple #4
0
    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 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."))
Exemple #6
0
 def __init__(self, root=None, **kw):
     """
     Creates this organism
     """
     Organism.__init__(self, **kw)
     if root == None:
         root = self.genNode()
 
     self.tree = root
Exemple #7
0
 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)
Exemple #8
0
 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
Exemple #9
0
    def __init__(self, ecosystem, location=None, isNewborn=False):
        Organism.__init__(self, ecosystem, location)

        self.lifespanTicks = 35 * 365 * 24 * 60  # years * days * hours * mins
        self.maturityTicks = 5 * 365 * 24 * 60
        self.hunger = 50
        self.starvationLevel = 100
        self.survivalProbability = .95  # they can regenerate, after all
        self.movementImpact = .1  # slowly crawl along the ocean floor
        self.__initializeAgeAndMaturity(isNewborn)
        self.__initializeSex()
Exemple #10
0
 def test_fitness(self):
     rules = [
         Rule("A", 0, 1, True, "B"),
         Rule("B", 0, 1, False, "A"),
         Rule("C", 0, 1, False, "B"),
         Rule("A", 1, 1, False, "C"),
         Rule("B", 1, 1, True, "B"),
         Rule("C", 1, 1, True, "HALT"),
     ]
     o = Organism(rules)
     self.assertEqual(o.fitness(), 14)
Exemple #11
0
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
Exemple #12
0
def make_kid(env, folder, orgfrom, kidnum, breedernum):
    org = Organism(orgfrom.genesequence) # create a new organism based off parent
    org.folder = folder.path # set organism folder
    org.logloc = "P_"+str(kidnum+1)+"_B_"+str(breedernum+1) # set log file representation of folder
    org.lineage_id = orgfrom.lineage_id
    org.is_primeval = False # Did not come from random, not primeval
    folder.org = org # place org in folder
    mutate(folder.org, env.mutations+env.adds*kidnum, env.weight, env.maxgenes) # mutate the gene and write mutation to file
    writec(folder.path, folder.org)
    if env.debug == True:
        call('g++ '+ folder.path + '*.cpp ./habitat/biosort.o -o ' + folder.path + 'organism.out -g -O0', shell = True) 
    else:
        call('g++ '+ folder.path + '*.cpp ./habitat/biosort.o -o ' + folder.path + 'organism.out -O0', shell = True) 
Exemple #13
0
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
Exemple #14
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))
Exemple #15
0
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
Exemple #16
0
    def __init__(self,
                 ecosystem,
                 lifespanYears,
                 maturityYears,
                 location=None,
                 isNewborn=False):
        Organism.__init__(self, ecosystem, location)

        self.lifespanTicks = lifespanYears * 365 * 24 * 60  # convert to mins
        self.maturityTicks = maturityYears * 365 * 24 * 60
        self.hunger = 10
        self.starvationLevel = 20

        self.__initializeSex()
        self.__initializeAgeAndMaturity(isNewborn)
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
Exemple #18
0
 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)))
Exemple #19
0
    def evolution(self):

        population = self.initPopulation(self.populationSize)
        generations = self.numberOfGenerations
        searchDepth = self.searchDepth

        for generation in range(generations):
            print("Generation " + str(generation) + "\n")
            (parents, population) = self.selection(population)
            children = self.crossover(parents)
            population.append(children[0])
            population.append(children[1])
            population = self.mutation(population)
            Organism.pickleOrganisms(population,
                                     'generation' + str(generation) + '.pkl')

        return population
 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))
Exemple #21
0
 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)
Exemple #22
0
 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()
Exemple #23
0
 def crossover(parent1: Organism, parent2: Organism, method: str) -> Tuple:
     """
     Convenience function for computing two children via crossover
     :param parent1: Organism
     :param parent2: Organism
     :param method: 'pmx', 'order_based', 'position_based' or 'random'
     :return: two children
     """
     return parent1.crossover(parent2, method=method)
Exemple #24
0
 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 = []
Exemple #25
0
 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)
Exemple #26
0
 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)
Exemple #27
0
 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)
Exemple #28
0
    def __init__(self, ecosystem, location=None, isNewborn=False):
        Organism.__init__(self, ecosystem, location)

        if isNewborn:
            self.ticksAlive = 0
        else:  # Give insantiated manatee random age
            self.ticksAlive = random.randint(0, 60)

        # Set gender
        self.sex = "M" if random.randint(0, 1) == 0 else "F"

        # Only needed for random age setter, but either way, check maturity
        self.checkMaturity()

        # Who knew? Manatees can live up to 60 years old
        self.lifespanTicks = 60 * 365 * 24 * 60  # years * days * hours * mins
        self.survivalProbability = 0.2  # don't think they are the best survivors
        self.movementImpact = .1
        self.hunger = 50
        self.ticksSinceLastChild = 0
Exemple #29
0
 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, 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)}]' ))
Exemple #31
0
 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)
Exemple #33
0
 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()
class TestOrganism(TC):
    def setUp(self):
        self.value = bitstring.Bitstring("100")
        lookup = [{0: 1, 1: 0.5}, {0: 0.2, 1: 0.4}, {0: 0.1, 1: 0.8}]
        deps = [[0], [1], [2]]
        model = nk_model.NKModelSimple(deps, lookup)
        self.org = Organism(self.value, nk_model=model)

    def test_init(self):
        self.assertEqual(self.org.value, self.value)

    def test_mutate(self):
        self.assertNotEqual(self.org, self.org.mutate())

    def test_without_nk_model(self):
        with self.assertRaises(ValueError):
            Organism(self.value)

    def test_fitness(self):
        expected_fit = (1 + 0.2 + 0.8) / float(3)
        self.assertEqual(expected_fit, self.org.fitness)
 def reproduce(self):
     self.children = [Organism.reproduce(p1, p2) for (p1, p2) in zip(self.parents1, self.parents2)]
     self.population += self.children
     self.population = sorted(self.population, key=lambda org: org.fitness, reverse=True)[:self.pop_size]
class TestPopulation(unittest.TestCase):
    def setUp(self):
        self.col = Colicin(0)
        self.imm = Immunity(-5, 5)
        self.org = Organism([self.col], [self.imm])
        self.pop = Population([self.org.duplicate() for _ in range(10)])

    def test_len(self):
        self.assertEqual(len(self.pop), 10)

    def test_replicate(self):
        self.pop.replicate()
        self.assertEqual(self.pop.pop.count(self.org), 10)
        self.assertEqual(len(self.pop), 20)

    def test_iter(self):
        for org in self.pop:
            self.assertEqual(org, self.org)
        else:
            return
        self.fail()

    def test_remove_self_toxic(self):
        org_toxic = Organism([Colicin(0)], [Immunity(10, 5)])
        org_not_toxic = Organism([Colicin(0)], [Immunity(0, 5)])
        self.pop.pop = [org_not_toxic, org_toxic]
        self.assertEqual(len(self.pop), 2)

        self.pop.remove_self_toxic()
        self.assertEqual(len(self.pop), 1)
        self.assertSequenceEqual(self.pop.pop, [org_not_toxic])

    def test_cull_by_all_colicins(self):
        org_winner = Organism([Colicin(5)], [Immunity(0, 5)])
        self.pop.pop.append(org_winner)
        self.pop.cull_by_all_colicins()
        self.assertSequenceEqual(self.pop.pop, [org_winner])

    def test_cull_by_all_colicins_extinction(self):
        org_other = Organism([Colicin(5)], [Immunity(10, 5)])
        self.pop.pop.append(org_other)
        self.pop.cull_by_all_colicins()
        self.assertEqual(len(self.pop), 0)

    def test_cull_by_single_colicin(self):
        org_other = Organism([Colicin(100)], [Immunity(100, 5)])
        self.pop.pop.extend(org_other for _ in range(10))
        self.pop.cull_by_single_colicin()
        self.assertEqual(len(self.pop), 10)

    def test_cull_by_single_colicin_extinction(self):
        self.pop.cull_by_single_colicin(Colicin(5))
        self.assertEqual(len(self.pop), 0)

    def test_cull_by_iterative_colicin(self):
        org_winner = Organism([Colicin(5)], [Immunity(0, 5)])
        self.pop.pop.append(org_winner)
        self.pop.cull_by_iterative_colicin()
        self.assertSequenceEqual(self.pop.pop, [org_winner])

    def test_cull_by_iterative_colicin_extinction(self):
        org_other = Organism([Colicin(5)], [Immunity(10, 5)])
        self.pop.pop.extend(org_other for _ in range(10))
        self.pop.cull_by_iterative_colicin()
        self.assertEqual(len(self.pop), 10)

    def test_colicins_produced(self):
        colicins = set(self.pop.colicins_produced())
        self.assertSetEqual({self.col}, colicins)

        other_colicin = Colicin(5)
        self.pop.pop.append(Organism([other_colicin], [Immunity(0, 5)]))
        colicins = set(self.pop.colicins_produced())
        self.assertSetEqual({self.col, other_colicin}, colicins)

    def test_sample_with_replacement(self):
        self.pop.pop.extend(self.org for _ in range(20))
        self.assertEqual(len(self.pop), 30)
        self.pop.sample_with_replacement()
        self.assertEqual(len(self.pop), 10)

        self.pop.pop = self.pop.pop[::2]
        self.assertEqual(len(self.pop), 5)
        self.pop.sample_with_replacement()
        self.assertEqual(len(self.pop), 10)

        self.assertEqual(self.pop.carrying_capacity, 10)

    def test_advance_generation(self):
        self.pop.advance_generation()
        self.assertEqual(len(self.pop), 10)
 def setUp(self):
     self.col = Colicin(0)
     self.imm = Immunity(-5, 5)
     self.org = Organism([self.col], [self.imm])
     self.pop = Population([self.org.duplicate() for _ in range(10)])
Exemple #38
0
import subprocess
from organism import Organism
import random as rand


TRAIN_SPLIT = 75
MAX_GENERATIONS = 20
MAX_EPOCHS = 1000000
VALIDATION_PERCENT = 15
POPULATION_SIZE = 10
MAX_HIDDEN_LAYERS = 3
MAX_HIDDEN_NODES = 15
BSSF = Organism(0, 0, 0)
BSSF.set_score(0)


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)
Exemple #39
0
def update_BSSF(org):
    global BSSF
    BSSF = Organism(org.rate, org.momentum, org.structure)
    BSSF.set_score(org.score)
    print org.rate, org.momentum, org.structure, org.score
Exemple #40
0
 def spawn_organism(self):
     org = Organism(self.genome.get_genes())
     org.species = self
     return org
Exemple #41
0
 def test_fitness_not_halt(self):
     rules = [Rule("A", 0, 1, True, "A"), Rule("A", 1, 1, True, "A")]
     o = Organism(rules)
     self.assertEqual(o.fitness(), 0)
Exemple #42
0
 def __init__(self, genotype, parasites, mhc):
     Organism.__init__(self, genotype, parasites)
filename = argv[1]
fasta = open(filename,"r")


def parse_fasta(filename):
    sequence = ""
    for line in filename:
        if (not line.startswith(">")):
            sequence = sequence + line
    
    sequence.replace("\n", "")
    return sequence

sequence = parse_fasta(fasta)
environment = Environment(0.000000001, 10)
organism = Organism(sequence) 
environment.population_list.append(organism)

start = time.clock()
for organism in environment.population_list:
    
    print "-" * 20
    print "Current organism: ", organism
    organism.transcribe()
    organism.translate()
    environment.population_list.append(organism.reproduce())
    print "Population:", len(environment.population_list)
    print environment.population_list
    print "-" * 20
    if len(environment.population_list) >= environment.carrying_capacity:
        break
Exemple #44
0
    def reproduce(self, generation, pop, sorted_species):
        champ_done = False
        mut_power = neat.weight_mut_power
        total_fitness = 0.0
        
        if self.expected_offspring > 0 and len(self.organisms) == 0:
            return False

        poolsize = len(self.organisms) - 1
        thechamp_i = 0
        for count in range(0, self.expected_offspring):
            mut_struct_baby = False
            mate_baby = False
            outside = False
            mom = dad = None

            if self.organisms[thechamp_i].super_champ_offspring > 0:
                dprint(DEBUG_CHECK, "super_champ_offspring()")
                mom_i = thechamp_i
                mom = self.organisms[mom_i]
                new_genome = mom.gnome.duplicate(count)
                if self.organisms[thechamp_i].super_champ_offspring == 1:
                    pass
                if self.organisms[thechamp_i].super_champ_offspring > 1:
                    if neat.randfloat() < 0.8 or neat.mutate_add_link_prob == 0.0:
                        new_genome.mutate_link_weights(mut_power, 1.0, Genome.GAUSSIAN)
                    else:
                        net_analogue = new_genome.genesis(generation)
                        ok, pop.cur_innov_num = \
                            new_genome.mutate_add_link(pop.innovations, pop.cur_innov_num, neat.newlink_tries)
                        net_analogue = None
                        mut_struct_baby = True
                #
                baby = Organism()
                baby.SetFromGenome(0.0, new_genome, generation)
                if self.organisms[thechamp_i].super_champ_offspring == 1:
                    if self.organisms[thechamp_i].pop_champ:
                        baby.pop_champ_child = True
                        baby.high_fit = mom.orig_fitness
                #
                self.organisms[thechamp_i].super_champ_offspring -= 1
                self.verify_baby(baby, mom, dad)

                # super_champ_offspring > 0
            elif (not champ_done) and (self.expected_offspring > 5):
                dprint(DEBUG_CHECK, "champ()")
                mom_i = thechamp_i
                mom = self.organisms[mom_i]
                new_genome = mom.gnome.duplicate(count)
                baby = Organism()
                baby.SetFromGenome(0.0, new_genome, generation)
                champ_done = True
                self.verify_baby(baby, mom, dad)

                # (not champ_done) and (self.expected_offspring > 5)
            elif (neat.randfloat() < neat.mutate_only_prob) or (poolsize == 0):
                dprint(DEBUG_CHECK, "mutate_only()")
                mom_i = neat.randint(0, poolsize)
                mom = self.organisms[mom_i]
                new_genome = mom.gnome.duplicate(count)
                self.verify_genome(new_genome)

                if neat.randfloat() < neat.mutate_add_node_prob:
                    dprint(DEBUG_INTEGRITY, "a: pop.cur_node_id:", pop.cur_node_id)
                    ok, pop.cur_node_id, pop.cur_innov_num = \
                        new_genome.mutate_add_node(pop.innovations, pop.cur_node_id, pop.cur_innov_num)
                    dprint(DEBUG_INTEGRITY, "b: pop.cur_node_id:", pop.cur_node_id)
                    mut_struct_baby = True
                    self.verify_genome(new_genome)

                elif neat.randfloat() < neat.mutate_add_link_prob:
                    net_analogue = new_genome.genesis(generation)
                    ok, pop.cur_innov_num = \
                        new_genome.mutate_add_link(pop.innovations, pop.cur_innov_num, neat.newlink_tries)
                    net_analogue = None
                    mut_struct_baby = True
                    self.verify_genome(new_genome)

                else:
                    if neat.randfloat() < neat.mutate_random_trait_prob:
                        new_genome.mutate_random_trait()
                        self.verify_genome(new_genome)
                    if neat.randfloat() < neat.mutate_link_trait_prob:
                        new_genome.mutate_link_trait(1)
                        self.verify_genome(new_genome)
                    if neat.randfloat() < neat.mutate_node_trait_prob:
                        new_genome.mutate_node_trait(1)
                        self.verify_genome(new_genome)
                    if neat.randfloat() < neat.mutate_link_weights_prob:
                        new_genome.mutate_link_weights(mut_power, 1.0, Genome.GAUSSIAN)
                        self.verify_genome(new_genome)
                    if neat.randfloat() < neat.mutate_toggle_enable_prob:
                        new_genome.mutate_toggle_enable(1)
                        self.verify_genome(new_genome)
                    if neat.randfloat() < neat.mutate_gene_reenable_prob:
                        new_genome.mutate_gene_reenable()
                        self.verify_genome(new_genome)

                baby = Organism()
                baby.SetFromGenome(0.0, new_genome, generation)
                self.verify_baby(baby, mom, dad)

                # (neat.randfloat() < neat.mutate_only_prob) or (poolsize == 0)
            else:
                mom_i = neat.randint(0, poolsize)
                mom = self.organisms[mom_i]

                if neat.randfloat() > neat.interspecies_mate_rate:
                    # within species
                    dad_i = neat.randint(0, poolsize)
                    dad = self.organisms[dad_i]

                else:
                    # outside species
                    randspecies = self

                    giveup = 0
                    while (randspecies == self) and (giveup < 5):
                        randmult = neat.gaussrand() / 4.
                        if randmult > 1.0:
                            randmult = 1.0
                        randspeciesnum = int(math.floor( (randmult * (len(sorted_species) - 1.0)) + 0.5 ))
                        randspecies = sorted_species[randspeciesnum]
                        giveup += 1

                    dad = randspecies.organisms[0]
                    outside = True

                if neat.randfloat() < neat.mate_multipoint_prob:
                    dprint(DEBUG_CHECK, "mate_multipoint()")
                    new_genome = mom.gnome.mate_multipoint(dad.gnome, count, mom.orig_fitness, dad.orig_fitness, outside)
                elif neat.randfloat() < neat.mate_multipoint_avg_prob / (neat.mate_multipoint_avg_prob+neat.mate_singlepoint_prob):
                    dprint(DEBUG_CHECK, "mate_multipoint_avg()")
                    new_genome = mom.gnome.mate_multipoint_avg(dad.gnome, count, mom.orig_fitness, dad.orig_fitness, outside)
                else:
                    dprint(DEBUG_CHECK, "mate_singlepoint()")
                    new_genome = mom.gnome.mate_singlepoint(dad.gnome, count)

                mate_baby = True

                if ((neat.randfloat() > neat.mate_only_prob) or
                    (dad.gnome.genome_id == mom.gnome.genome_id) or
                    (dad.gnome.compatibility(mom.gnome) == 0.0)):
                    dprint(DEBUG_CHECK, "mate_and_mutate()")
                    if neat.randfloat() < neat.mutate_add_node_prob:
                        dprint(DEBUG_INTEGRITY, "a: pop.cur_node_id:", pop.cur_node_id)
                        ok, pop.cur_node_id, pop.cur_innov_num = \
                            new_genome.mutate_add_node(pop.innovations, pop.cur_node_id, pop.cur_innov_num)
                        dprint(DEBUG_INTEGRITY, "b: pop.cur_node_id:", pop.cur_node_id)
                        mut_struct_baby = True
                    elif neat.randfloat() < neat.mutate_add_link_prob:
                        net_analogue = new_genome.genesis(generation)
                        ok, pop.cur_innov_num = \
                            new_genome.mutate_add_link(pop.innovations, pop.cur_innov_num, neat.newlink_tries)
                        net_analogue = None
                        mut_struct_baby = True
                    else:
                        if neat.randfloat() < neat.mutate_random_trait_prob:
                            new_genome.mutate_random_trait()
                        if neat.randfloat() < neat.mutate_link_trait_prob:
                            new_genome.mutate_link_trait(1)
                        if neat.randfloat() < neat.mutate_node_trait_prob:
                            new_genome.mutate_node_trait(1)
                        if neat.randfloat() < neat.mutate_link_weights_prob:
                            new_genome.mutate_link_weights(mut_power, 1.0, Genome.GAUSSIAN)
                        if neat.randfloat() < neat.mutate_toggle_enable_prob:
                            new_genome.mutate_toggle_enable(1)
                        if neat.randfloat() < neat.mutate_gene_reenable_prob:
                            new_genome.mutate_gene_reenable()

                    baby = Organism()
                    baby.SetFromGenome(0.0, new_genome, generation)
                    self.verify_baby(baby, mom, dad)

                else:
                    dprint(DEBUG_CHECK, "mate_only()")
                    baby = Organism()
                    baby.SetFromGenome(0.0, new_genome, generation)
                    self.verify_baby(baby, mom, dad)

                # else

            baby.mut_struct_baby = mut_struct_baby
            baby.mate_baby = mate_baby
            
            curspecies_i = 0
            found = False
            while (curspecies_i < len(pop.species)) and (not found):
                comporg = pop.species[curspecies_i].first()
                if comporg == None:
                    curspecies_i += 1
                elif baby.gnome.compatibility(comporg.gnome) < neat.compat_threshold:
                    pop.species[curspecies_i].add_Organism(baby)
                    baby.species = pop.species[curspecies_i]
                    found = True
                else:
                    curspecies_i += 1
            #
            if not found:
                pop.last_species += 1
                newspecies = Species()
                newspecies.SetFromIdAndNovel(pop.last_species, True)
                pop.species.append(newspecies)
                newspecies.add_Organism(baby)
                baby.species = newspecies
                    

            # for count in self.expected_offspring

        return True
Exemple #45
0
 def start(self, movers, eaters, stroke):
     self.eaters = eaters
     self.movers = movers
     self.stroke = stroke
     self.organisms = Organism.generate(self.gui.organisms, self.lower_grid.max_x, self.lower_grid.max_y, self)
 def setUp(self):
     self.value = bitstring.Bitstring("100")
     lookup = [{0: 1, 1: 0.5}, {0: 0.2, 1: 0.4}, {0: 0.1, 1: 0.8}]
     deps = [[0], [1], [2]]
     model = nk_model.NKModelSimple(deps, lookup)
     self.org = Organism(self.value, nk_model=model)
 def init_random(size=10, mutation=0.3, solve_method="logistic"):
     new_pop = Population(size, mutation)
     new_pop.population = [Organism.init_random(np.random.randint(5, Organism.count), solve_method) for _ in xrange(size)]
     return new_pop