Esempio n. 1
0
def compare(devo_file, outpath, altmode):
    original_org = json_load_file.json_load_file (devo_file)
    genome = original_org.genome
    # This is done to get the potential_locaions list
    new_org = Organism(original_org.generation, original_org.generational_index, original_org.genome_size,
                       2, True, original_org.thread_length, original_org.mutation_rate, parent1=None, parent2=None,genome=genome,alt_mode=altmode)
    xover_locations = new_org.instruction_set.potential_locations
    # set the xover points to 0
    for i in genome:
        i.crossover_point = 0

    counter = 0
    while counter != 2:
        try:
            rand_index = random.choice(xover_locations)
            print(rand_index)
            genome[rand_index].crossover_point = 1
            xover_locations.remove(rand_index)
            counter +=1
        except IndexError:
            pass
    print([i.crossover_point for i in genome])
    restricted_org = Organism(original_org.generation, original_org.generational_index, original_org.genome_size,
                              2, False, original_org.thread_length, original_org.mutation_rate, parent1=None, parent2=None,genome=genome,alt_mode=altmode)

    restricted_org.save_to_file(outpath)
Esempio n. 2
0
 def init_organisms(self, n, attr):
     organisms = []
     for _ in range(n):
         o = Organism(attr[0], attr[1], attr[2], ENV_WIDTH, ENV_HEIGHT)
         o.energy = self.DAY_ENERGY
         organisms.append(o)
     return organisms
Esempio n. 3
0
    def toVerilog(self, filepath, moduleName):
        """
            Writes Organism to a verilog file.
        """
        moduleInputs = ['input%d' % i for i in xrange(self.numInputs)]
        moduleInputsTxt = ','.join(moduleInputs)
        moduleOutputsTxt = ','.join('output%d' % i
                                    for i in xrange(self.numOutputs))
        moduleArgsTxt = '%s,%s' % (moduleOutputsTxt, moduleInputsTxt)

        layerTxts = [
            '\toutput %s;' % moduleOutputsTxt,
            '\tinput %s;' % moduleInputsTxt
        ]

        for idx, tree in enumerate(self.trees):
            # self.gate -> what type of gate it is
            layerTxts.append(tree.toVerilog(idx) + '\n')

        body = '\n'.join(layerTxts)

        fin = open(filepath, 'w')
        fin.write(Organism.verilogFromTemplate(moduleName, moduleArgsTxt,
                                               body))
        fin.close()
Esempio n. 4
0
def nextGeneration(pop, numCoeffs, mutRate, eliteNum):
    #create empty newPop
    newPop = []
    #loop through to create more new children
    for i in range((len(pop) - eliteNum) // 2):
        #randomly select two parents
        parent1 = selection(pop)
        parent2 = selection(pop)
        #use crossover function and mutate
        child1, child2 = crossover(parent1.bits, parent2.bits)
        child1 = mutation(child1, mutRate)
        child2 = mutation(child2, mutRate)
        #append new organisms to population
        newPop.append(Org.Organism(numCoeffs, child1))
        newPop.append(Org.Organism(numCoeffs, child2))
    #append sorted elite number to be saved each iteration
    newPop += pop[:eliteNum]
    return newPop
Esempio n. 5
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 = []
Esempio n. 6
0
   def spawn(self, genome, size):
      for i in range(size):
         newGenome = genome.makeCopy(i)

         newGenome.mutateSynapseWeights(1.0, 1.0, Mutator.GAUSSIAN)

         self.organisms.append(Organism(0.0, newGenome, 1))

         self.currentNeuronId     = newGenome.getLastNeuronId()
         self.currentInnovationId = newGenome.getLastGeneInnovationId()

      self.speciate()
Esempio n. 7
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 = []
Esempio n. 8
0
def initPop(size, numCoeffs):
    # Get size-4 random organisms in a list.
    pop = [Org.Organism(numCoeffs) for x in range(size - 3)]

    # Create the all 0s and all 1s organisms and append them to the pop.
    pop.append(Org.Organism(numCoeffs, [0] * (64 * numCoeffs)))
    pop.append(Org.Organism(numCoeffs, [1] * (64 * numCoeffs)))

    # Create an organism corresponding to having every coefficient as 1.
    bit1 = [0] * 2 + [1] * 10 + [0] * 52
    org = []
    for c in range(numCoeffs):
        org = org + bit1
    pop.append(Org.Organism(numCoeffs, org))

    # Create an organism corresponding to having every coefficient as -1.
    bit1 = [1, 0] + [1] * 10 + [0] * 52
    org = []
    for c in range(numCoeffs):
        org = org + bit1
    pop.append(Org.Organism(numCoeffs, org))

    # Return the population.
    return pop
Esempio n. 9
0
    def toVerilog(self, filepath, moduleName):
        """
            Writes BooleanLogicOrganism to a verilog file.
        """

        moduleInputs = ['input%d' % i for i in xrange(self.numInputs)]
        moduleInputsTxt = ','.join(moduleInputs)
        moduleOutputsTxt = ','.join('output%d' % i
                                    for i in xrange(self.numOutputs))
        moduleArgsTxt = '%s,%s' % (moduleOutputsTxt, moduleInputsTxt)

        layerTxts = [
            '\toutput %s;' % moduleOutputsTxt,
            '\tinput %s;' % moduleInputsTxt
        ]

        layerInputs = moduleInputs
        lastLayerIndex = len(self.layers) - 1
        for layerNum, layer in enumerate(self.layers):

            if layerNum == lastLayerIndex:
                layerOutputs = [
                    'output%d' % i for i in xrange(self.numOutputs)
                ]
                layerOutputsTxt = '\twire %s;' % (','.join(layerOutputs))
            else:
                layerOutputs = [
                    'layer%d_output%d' % (layerNum, i)
                    for i in xrange(len(layer.gates))
                ]
                layerOutputsTxt = '\twire %s;' % (','.join(layerOutputs))

            # call layer with inputs and outputs text
            layerTxt = layer.toVerilog(layerInputs, layerOutputs)
            layerTxts.append('\n%s\n\n%s' % (layerOutputsTxt, layerTxt))

            # at end of loop, the outputs of the last layer are inputs
            # to the new layer
            layerInputs = layerOutputs

        body = '\n'.join(layerTxts)
        fin = open(filepath, 'w')
        fin.write(Organism.verilogFromTemplate(moduleName, moduleArgsTxt,
                                               body))
        fin.close()
Esempio n. 10
0
 def toVerilog(self, filepath, moduleName):
     """
         Writes Organism to a verilog file.
     """        
     moduleInputs = ['input%d'%i for i in xrange(self.numInputs)]
     moduleInputsTxt = ','.join(moduleInputs)
     moduleOutputsTxt = ','.join('output%d'%i for i in xrange(self.numOutputs))
     moduleArgsTxt = '%s,%s'%(moduleOutputsTxt,moduleInputsTxt)
     
     layerTxts = ['\toutput %s;'%moduleOutputsTxt,'\tinput %s;'%moduleInputsTxt]
     
     for idx,tree in enumerate(self.trees):
         # self.gate -> what type of gate it is
         layerTxts.append(tree.toVerilog(idx)+'\n')
     
     body = '\n'.join(layerTxts)
     
     fin = open(filepath,'w')
     fin.write(Organism.verilogFromTemplate(moduleName,moduleArgsTxt,body))
     fin.close()
Esempio n. 11
0
    def parse_study_file(self):
        experiment = Study.Study()
        self.experiment = URIRef(self.graph.reproduce['Experiment' + '_' +
                                                      self.study_number])
        self.g.add((self.experiment, RDF.type,
                    URIRef(self.graph.reproduce["Experiment"])))
        self.parse(self.experiment, experiment.mapping)

        self.imaging_study = URIRef(self.graph.reproduce['ImagingStudy' + '_' +
                                                         self.study_number])
        self.g.add((self.imaging_study, RDF.type,
                    URIRef(self.graph.reproduce["ImagingStudy"])))

        agent = Agent.Agent()
        self.parse_agent(agent.mapping)

        license = License.License()
        self.license = URIRef(self.graph.reproduce['License' + '_' +
                                                   self.study_number])
        self.g.add(
            (self.license, RDF.type, URIRef(self.graph.reproduce["License"])))
        self.parse(self.license, license.mapping)

        publication = Publication.Publication()
        self.publication = URIRef(self.graph.reproduce['Publication' + '_' +
                                                       self.study_number])
        self.g.add((self.publication, RDF.type,
                    URIRef(self.graph.reproduce["Publication"])))
        self.parse(self.publication, publication.mapping)

        organism = Organism.Organism()
        self.organism = URIRef(self.graph.reproduce['Organism' + '_' +
                                                    self.study_number])
        self.g.add((self.organism, RDF.type,
                    URIRef(self.graph.reproduce["Organism"])))
        self.parse(self.organism, organism.mapping)

        self.parse_screen()
        self.parse_assay()
Esempio n. 12
0
    def toVerilog(self, filepath, moduleName):
        """
            Writes BooleanLogicOrganism to a verilog file.
        """
        
        moduleInputs = ['input%d'%i for i in xrange(self.numInputs)]
        moduleInputsTxt = ','.join(moduleInputs)
        moduleOutputsTxt = ','.join('output%d'%i for i in xrange(self.numOutputs))
        moduleArgsTxt = '%s,%s'%(moduleOutputsTxt,moduleInputsTxt)
        
        layerTxts = ['\toutput %s;'%moduleOutputsTxt,'\tinput %s;'%moduleInputsTxt]
        
        layerInputs = moduleInputs
        lastLayerIndex = len(self.layers)-1
        for layerNum,layer in enumerate(self.layers):
            
            if layerNum == lastLayerIndex:
                layerOutputs = ['output%d'%i for i in xrange(self.numOutputs)]
                layerOutputsTxt = '\twire %s;'%(','.join(layerOutputs))
            else:
                layerOutputs = ['layer%d_output%d'%(layerNum,i) for i in xrange(len(layer.gates))]
                layerOutputsTxt = '\twire %s;'%(','.join(layerOutputs))
            
            # call layer with inputs and outputs text
            layerTxt = layer.toVerilog(layerInputs,layerOutputs)
            layerTxts.append('\n%s\n\n%s'%(layerOutputsTxt,layerTxt))

            # at end of loop, the outputs of the last layer are inputs
            # to the new layer
            layerInputs = layerOutputs
        
        body = '\n'.join(layerTxts)
        fin = open(filepath,'w')
        fin.write(
            Organism.verilogFromTemplate(moduleName,moduleArgsTxt,body)
            )
        fin.close()
Esempio n. 13
0
            genomes_colors_map[b["DNAIdentifier"]] = (b["Color"], "Bacteria")

        genome_to_use = None
        for gen in genome_types:
            if gen[1] == b["Color"]:
                genome_to_use = gen[0]
                param["IndividualBacteriaParameters"][
                    "Basal Reproduction Probability"][b["Name"]] = b["Growth"]

        for b_individual in range(
                0, int(param["World Size"] * param["World Size"] * b["Freq"])):
            if b["Color"] == None:
                print(b_individual, b)
                new_bacteria = Organism.Bacteria(b["Name"],
                                                 copy(genome_to_use),
                                                 b["Color"],
                                                 ar_locus=[0, 0, 0],
                                                 movement=1)

            if b["AntRes"] != "NA":
                for res in b["AntRes"]:
                    for idx, gene in enumerate(new_bacteria.genome):
                        if "AR_" + res in gene[0]:
                            new_bacteria.genome[idx] = (gene[0], gene[1],
                                                        gene[2], "Resistant")
                        new_bacteria.resistances[gene[0].split(":")[1]] = True

            if b["PhageRes"][0] != "NA":
                new_bacteria.phage_receptor_resistances = [
                    int(recept) for recept in b["PhageRes"]
                ]
Esempio n. 14
0
   def reproduce(self, generation, population, species):
      poolSize = len(self.organisms) - 1

      if poolSize >= 0:
         champion = self.organisms[0]

         championDone = False

         mutationPower = Configuration.weightMutationPower

         for i in range(int(self.expectedOffspring)):
            mom  = None
            baby = None

            if champion.superChampionOffspring > 0:
               mom       = champion
               newGenome = mom.genome.makeCopy(i)

               if champion.superChampionOffspring > 1:
                  if randfloat() < 0.8 or Configuration.mutateAddSynapseProbability == 0.0:
                     newGenome.mutateSynapseWeights(Mutator.GAUSSIAN, mutationPower, 1.0)
                  else:
                     newGenome.genesis(generation)
                     newGenome.mutateAddSynapse(population, Configuration.synapseAddTries)

               baby = Organism(0.0, newGenome, generation)

               if champion.superChampionOffspring == 1:
                  if champion.populationChampion:
                     baby.populationChampionChild = True
                     baby.maxFitness              = mom.originalFitness

               champion.superChampionOffspring -= 1

            elif not championDone and self.expectedOffspring > 5:
               mom       = champion
               newGenome = mom.genome.makeCopy(i)

               baby         = Organism(0.0, newGenome, generation)
               championDone = True

            elif poolSize == 0 or randfloat() < Configuration.mutateOnlyProbability:
               mom          = self.organisms[random.randint(0, poolSize)]
               newGenome    = mom.genome.makeCopy(i)

               if randfloat() < Configuration.mutateAddNeuronProbability:
                  newGenome.mutateAddNeuron(population)
               elif randfloat() < Configuration.mutateAddSynapseProbability:
                  newGenome.genesis(generation)
                  newGenome.mutateAddSynapse(population, Configuration.synapseAddTries)
               else:
                  newGenome.tryAllMutations(mutationPower)

               baby = Organism(0.0, newGenome, generation)

            else:
               mom = self.organisms[random.randint(0, poolSize)]
               dad = None

               if randfloat() > Configuration.interspeciesMateRate:
                  dad = self.organisms[random.randint(0, poolSize)]
               else:
                  otherSpecies = None

                  for tries in range(5):
                     randMultiplier = random.gauss(0, 1) / 4.0
                     if randMultiplier > 1.0:
                        randMultiplier = 1.0

                     speciesIndex = int(math.floor((randMultiplier * (len(species) - 1.0)) + 0.5))
                     otherSpecies = species[speciesIndex]
                     if self != otherSpecies:
                        break
                     else:
                        otherSpecies = None

                  if otherSpecies is not None:
                     dad = otherSpecies.organisms[0]
                  else:
                     dad = mom

               if randfloat() < Configuration.mateMultipointProbability:
                  newGenome = mom.genome.crossover(Crossover.MULTIPOINT, dad.genome, i, mom.originalFitness, dad.originalFitness)
               elif randfloat() < (Configuration.mateMultipointAveProbability / (Configuration.mateMultipointAveProbability + Configuration.mateSinglepointProbability)):
                  newGenome = mom.genome.crossover(Crossover.MULTIPOINT_AVG, dad.genome, i, mom.originalFitness, dad.originalFitness)
               else:
                  newGenome = mom.genome.crossover(Crossover.SINGLEPOINT, dad.genome, i)

               if randfloat() > Configuration.mateOnlyProbability or \
                  dad.genome.id == mom.genome.id or \
                  dad.genome.getCompatibility(mom.genome) == 0.0:
                  if randfloat() < Configuration.mutateAddNeuronProbability:
                     newGenome.mutateAddNeuron(population)
                  elif randfloat() < Configuration.mutateAddSynapseProbability:
                     newGenome.genesis(generation)
                     newGenome.mutateAddSynapse(population, Configuration.synapseAddTries)
                  else:
                     newGenome.tryAllMutations(mutationPower)

               baby = Organism(0.0, newGenome, generation)

            # try mom's species first, then iterate through all other species
            # optimization proposed in the NEAT FAQ
            if baby.isCompatibleWith(mom):
               mom.species.addOrganism(baby)
               baby.species = mom.species
            else:
               found = False

               for specie in population.species:
                  for organism in specie.organisms:
                     if baby.isCompatibleWith(organism):
                        specie.addOrganism(baby)
                        baby.species = specie
                        found = True
                        break
                  if found:
                     break

               if not found:
                  newSpecies = Species(len(population.species) + 1, novel=True)
                  newSpecies.addOrganism(baby)
                  baby.species = newSpecies
                  population.species.append(newSpecies)
Esempio n. 15
0
        # make a jump
        organism.v_y = 10


def click_handler(event, organism):
    print "i have been saved!"
    organism.being_held = True


def move_handler(event, organism):
    organism.x = event.x_root
    organism.y = event.y_root


def release_handler(event, organism):
    organism.being_held = False
    print "oh no, out of control again!!"


if __name__ == '__main__':

    # setup the sprite
    gif_names = ["gifs/bird_right.gif", "gifs/bird_left.gif"]
    organism = Organism.Organism(update_func, 60, 60, gif_names, click_handler,
                                 move_handler, release_handler)
    organism.frame_interval = 50

    # setup and run the world
    w = World.World()
    w.add_organism(organism)
    w.start()
Esempio n. 16
0
from Organism import *
import pickle

cuscuta = Organism('Plantae', 'Angiosperms-Eudicots-Asterids', 'Solanales',
                   'Convolvulaceae', 'Cuscuta', 'C. pentagona', 'Dodder')

kingdom = cuscuta.kingdom
species = cuscuta.species

# Save a variable into a pickle file.
file = open('C:/Users/louie/Desktop/mylist.pickle', 'wb')
pickle.dump([kingdom, species], file)
file.close()

# Get the info back from a pickle file
with open('C:/Users/louie/Desktop/mylist.pickle', 'rb') as pickle_file:
    content = pickle.load(pickle_file)
print(content)
Esempio n. 17
0
def new_organism():
    return Organism()
Esempio n. 18
0
                                 name="")

    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(15, 5))
    history_data.plot(ax=axes[0])
    axes[0].set_title("History")
    current_data.hist(bins=30, ax=axes[1])
    axes[1].set_title("Generation {0} Distances".format(i))
    species_data.plot.pie(ax=axes[2])
    axes[2].set_title("Generation {0} Species".format(i))
    plt.tight_layout()
    plt.show()


if __name__ == "__main__":
    population_size = 200
    starting_organisms = [Organism() for _ in range(population_size)]
    population = Generation(starting_organisms)

    history = []

    for i in range(0, 100000000000000):
        population.run_tests()
        population.sort()

        best, median, worst = population.get_best(), population.get_median(
        ), population.get_worst()
        species_distribution = population.get_species_distribution()

        print(
            "Generation {0}: best = {1}    median = {2}    worst = {3}    species = {4}"
            .format(i, int(best.fitness), int(median.fitness),
Esempio n. 19
0
def refresh(screen):
    org_a = Organism()
    org_b = Organism()
    org_c = Organism()

    screen.fill(white)

    org_a.draw_on(screen, (100, -300))
    org_b.draw_on(screen, (400, -300))
    org_c.draw_on(screen, (700, -300))

    pg.display.update()
 def chooseTwoToCross(path_to_new_gen):
     org1 = None
     org2 = None
     #This horribly ugly blcok of code handles the selection of the orgs
     #To be crossed. The algorithm always looks two cross orgs in the higher
     #lists first (i.e. threes then twos then ones). Once an organism has been
     #crossed, they are put into a lower list (Threes-->twos, etc), or are
     #removed altogether from the lists (ones --> n/a)
     try:
         print 'fours %s' % [i.filename for i in fours]
         print 'threes %s' % [i.filename for i in threes]
         print 'twos %s' % [i.filename for i in twos]
         print 'ones %s' % [i.filename for i in ones]
     except IndexError:
         pass
     if len(fours) > 0:
         org1 = random.choice(fours)
         fours.remove(org1)
         threes.append(org1)
     elif len(threes) > 0:
         org1 = random.choice(threes)
         threes.remove(org1)
         twos.append(org1)
     elif len(twos) > 0:
         org1 = random.choice(twos)
         ones.append(org1)
         twos.remove(org1)
     elif len(ones) > 0:
         org1 = random.choice(ones)
         ones.remove(org1)
     if len(fours) > 0:
         fours_sans_org1 = filter(lambda y:y != org1, fours)
         org2 = random.choice(fours_sans_org1)
         fours.remove(org2)
         threes.append(org2)
     elif len(threes) > 0:
         try:
             threes_sans_org1 = filter(lambda y:y != org1, threes)
             org2 = random.choice(threes_sans_org1)
             threes.remove(org2)
             twos.append(org2)
         except IndexError:
             pass
     elif len(filter(lambda y:y != org1, twos)) > 0:
         try:
             twos_sans_org1 = filter(lambda y:y != org1, twos)
             org2 = random.choice(twos_sans_org1)
             ones.append(org2)
             twos.remove(org2)
         except IndexError:
             pass
     elif len(filter(lambda y:y != org1, ones)) > 0:
         try:
             ones_sans_org1 = filter(lambda y:y != org1, ones)
             org2 = random.choice(ones_sans_org1)
             ones.remove(org2)
         except IndexError:
             pass
             #print 'one filtered list %s' % ones_sans_org1
     print 'org1 %s, org2 %s' % (org1.filename, org2.filename)
     if org1 is not None and  org2 is not None:
         print 'crossing org1:%s with org2:%s\n' % (org1.filename, org2.filename, 
                                                            )
         Organism.reproduce(org1, org2, path_to_new_gen)
         return True
     else:
         return False
Esempio n. 21
0
            organism[item] = organism_settings[item]

    mutability = {
        'will mutate?': make_function(organism_settings['actions sequence']['mutability']['will mutate?'], 1),                    
        'new value': make_function(organism_settings['actions sequence']['mutability']['new value'], 1)}
        
    print "mutability['will mutate?'] =", mutability['will mutate?'](organism)
    print "mutability['new value'] =", mutability['new value'](organism)

if test7:
    from Organism import *
    
    organism_settings = {
            'speed': 3.0,
            'attack capacity': 5.0,
            'defense capacity': 2.0,
            'photosynthesis capacity': 10.0,
            'age': 120,    
            'color': ['speed', 7, {'+': ('speed', 100)}]
    }
    
    all_genes = extract_genes_names(organism_settings)
    organism = Organism({}, {})
    for gene in organism_settings:
        organism.add_gene(gene, organism_settings[gene], all_genes)
    
    print_dictionary( organism)
                    
    color = make_function(organism_settings['color'])
    print color(organism)
    print organism['color'](organism)