Ejemplo n.º 1
0
def run_main():
    initialPopulationSize = 51
    generations = 1500
    conf = LoadSystemConfiguration() #TODO make an object to encapsulate this kind of information
    # Genome instance
    genome = G2DList.G2DList(400, 18)
    genome.setParams(rangemin=0, rangemax=360)

    # The evaluator function (objective function)
    genome.evaluator.set(eval_func)
    genome.crossover.set(Crossovers.G2DListCrossoverSingleHPoint)
    #genome.mutator.set(Mutators.G2DListMutatorIntegerRange)
    genome.mutator.set(Mutators.G2DListMutatorIntegerGaussian)

    # Genetic Algorithm Instance
    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(generations)    #TODO class atribute
    ga.setPopulationSize(initialPopulationSize) #TODO class atribute
    ga.setMutationRate(0.2)
    ga.selector.set(Selectors.GRankSelector)
    #ga.selector.set(Selectors.GTournamentSelector)
    #ga.selector.set(Selectors.GRouletteWheel)
    ga.setElitism(True)
    ga.setElitismReplacement(initialPopulationSize/3)
    #ga.terminationCriteria.set(ConvergenceCriteria)

    # Create DB Adapter and set as adapter
    sqlite_adapter = DBAdapters.DBSQLite(identify="Lucy walk", resetDB=True)
    ga.setDBAdapter(sqlite_adapter)
                        
    #callback to persist best individual of each generation
    ga.stepCallback.set(generationCallback)

    #keep a reference to the genetic algorithm engine
    global gaEngine
    gaEngine = ga

    # Do the evolution, with stats dump
    # frequency of 2 generations
    ga.evolve(freq_stats=1)

    # Best individual
    best = ga.bestIndividual()
    score = best.getRawScore()
    timestr = time.strftime("%Y%m%d-%H%M%S")
    filename = str(score) + "-" + timestr + "-" + str(generations) + ".xml"
    prop = DTIndividualPropertyVanilla() #TODO create a vanilla property as default argument in Individual constructor
    bestIndividual = Individual(prop, DTIndividualGeneticMatrix(chromosomeToLucyGeneticMatrix(best)))
    geneticPoolDir = os.getcwd()+conf.getDirectory("Genetic Pool")
    bestIndividual.persist(geneticPoolDir + filename)
    
    #TODO store all the population, not only the fitest

    print ga.getStatistics()
Ejemplo n.º 2
0
def generationCallback(ga_engine):
    # persist best individual at the moment
    conf = LoadSystemConfiguration() #TODO make an object to encapsulate this kind of information
    geneticPoolDir = os.getcwd()+conf.getDirectory("Genetic Pool")
    gen = ga_engine.getCurrentGeneration()
    best = ga_engine.bestIndividual()
    score = best.getRawScore()
    timestr = time.strftime("%Y%m%d-%H%M%S")
    filename = str(score) + "-" + timestr + "-" + str(gen) + ".xml"
    prop = DTIndividualPropertyVanilla() #TODO create a vanilla property as default argument in Individual constructor
    bestIndividual = Individual(prop, DTIndividualGeneticMatrix(chromosomeToLucyGeneticMatrix(best)))
    bestIndividual.persist(geneticPoolDir + filename)
    ga_engine.getDBAdapter().commit()
    ##population = ga_engine.getPopulation()
    ##averagePopulation = getPopulationAverage(population)
    #averageGeneration = getPopulationAverage(gen)
    ##print "current population raw score average: ", averagePopulation
    #print "current generation raw score average: ", averageGeneration
    return False
Ejemplo n.º 3
0
def generationCallback(ga_engine):
    # persist best individual at the moment
    conf = LoadSystemConfiguration() #TODO make an object to encapsulate this kind of information
    geneticPoolDir = os.getcwd()+conf.getDirectory("Genetic Pool")
    gen = ga_engine.getCurrentGeneration()
    best = ga_engine.bestIndividual()
    score = best.getRawScore()

    #check if the convergence criteria has been reached
    global max_score, max_score_generation, convergenceCriteria
    if score > max_score:
        max_score = score
        max_score_generation = gen
    else:
        #if the score doesn't improve in NUMBER_GENERATIONS_CONVERGENCE_CRITERIA generations then there is no reason to continue and we have reach a convergence
        if gen - max_score_generation > NUMBER_GENERATIONS_CONVERGENCE_CRITERIA:
            convergenceCriteria = True

    timestr = time.strftime("%Y%m%d-%H%M%S")
    filename = str(score) + "-" + timestr + "-" + str(gen) + ".xml"

    #at generation 0 is the firs time to create de directory and store the GA parameters
    if gen == 0:
        global experimentDir
        experimentDir = geneticPoolDir + timestr
        global experimentTime
        experimentTime = timestr
        os.mkdir(experimentDir)
        storeExperimentGAparameters()

    prop = DTIndividualPropertyVanilla()
    bestIndividual = Individual(prop, DTIndividualGeneticMatrix(chromosomeToLucyGeneticMatrix(best)))
    bestIndividual.persist(os.path.join(experimentDir, filename))
    ga_engine.getDBAdapter().commit()

    #population = ga_engine.getPopulation()
    #popSize = len(population)
    print "generation executed!, best fit of generation: ", score, "fittest: ", max_score, "reached in generation: ", max_score_generation

    return False
Ejemplo n.º 4
0
def run_main():
    conf = LoadSystemConfiguration()
    initialPopulationSize = int(conf.getProperty("Population size"))
    generations = int(conf.getProperty("Number of generations"))
    # Genome instance
    framesQty = sysConstants.GENOMA_MAX_LENGTH
    genome = G2DList.G2DList(framesQty, 18)
    genome.setParams(rangemin=0, rangemax=360)
    genome.setParams(gauss_sigma=sysConstants.MUTATION_SIGMA, gauss_mu=0)

    # The evaluator function (objective function)
    genome.evaluator.set(eval_func)
    if conf.getProperty("Crossover operator") == "crossovers.G2DListCrossoverSingleNearHPoint":
        genome.crossover.set(crossovers.G2DListCrossoverSingleNearHPoint)
    elif conf.getProperty("Crossover operator") == "Crossovers.G2DListCrossoverSingleHPoint":
        genome.crossover.set(Crossovers.G2DListCrossoverSingleHPoint)

    #genome.crossover.set(crossovers.G2DListCrossoverSingleNearHPointImprove)
    #genome.crossover.set(crossovers.G2DListCrossoverSingleHPoint)
    
    # Genetic Algorithm Instance
    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(generations)
    ga.setPopulationSize(initialPopulationSize)

    #genome.mutator.set(Mutators.G2DListMutatorIntegerRange)
    if conf.getProperty("Mutator operator") == "mutators.G2DListMutatorRealGaussianSpline":
        genome.mutator.set(mutators.G2DListMutatorRealGaussianSpline)
    elif conf.getProperty("Mutator operator") == "Mutators.G2DListMutatorRealGaussianGradient":
        genome.mutator.set(Mutators.G2DListMutatorRealGaussianGradient)

    
    ga.setMutationRate(float(conf.getProperty("MutationRate")))
    
    if conf.getProperty("Selection operator") == "Selectors.GRankSelector" :
        ga.selector.set(Selectors.GRankSelector)
    elif conf.getProperty("Selection operator") == "Selectors.GTournamentSelector" :
        ga.selector.set(Selectors.GTournamentSelector)
    elif conf.getProperty("Selection operator") == "Selectors.GRouletteWheel" :
        ga.selector.set(Selectors.GRouletteWheel)
    elif conf.getProperty("Selection operator") == "Selectors.GUniformSelector" :
        ga.selector.set(Selectors.GUniformSelector)

    '''For crossover probability, maybe it is the ratio of next generation population born by crossover operation. 
    While the rest of population...maybe by previous selection or you can define it as best fit survivors'''
    ga.setCrossoverRate(float(conf.getProperty("CrossoverRate")))

    elitism = float(conf.getProperty("Elitism replacement percentage")) > 0
    ga.setElitism(True)
    '''Set the number of best individuals to copy to the next generation on the elitism'''
    if elitism:
        numberIndividualsForNextGen = int(initialPopulationSize*float(conf.getProperty("Elitism replacement percentage")))
        ga.setElitismReplacement(numberIndividualsForNextGen)

    if int(conf.getProperty("Convergence criteria enable?"))==True:
        ga.terminationCriteria.set(ConvergenceCriteria)

    # Create DB Adapter and set as adapter
    sqlite_adapter = DBAdapters.DBSQLite(identify="Lucy walk", resetDB=True)
    ga.setDBAdapter(sqlite_adapter)
                        
    #callback to persist best individual of each generation
    ga.stepCallback.set(generationCallback)

    #keep a reference to the genetic algorithm engine
    global gaEngine
    gaEngine = ga

    # Do the evolution, with stats dump
    # frequency of every generation
    ga.evolve(freq_stats=0)

    # Best individual
    best = ga.bestIndividual()
    score = best.getRawScore()
    timestr = time.strftime("%Y%m%d-%H%M%S")
    filename = str(score) + "-" + timestr + "-" + str(generations) + ".xml"
    prop = DTIndividualPropertyVanilla()
    bestIndividual = Individual(prop, DTIndividualGeneticMatrix(chromosomeToLucyGeneticMatrix(best)))

    bestIndividual.persist(os.path.join(experimentDir,filename))

    #store all the final population, not only the fitest
    population = ga.getPopulation()
    popSize = len(population)
    for pos in range(popSize):
        individual = Individual(prop, DTIndividualGeneticMatrix(chromosomeToLucyGeneticMatrix(population[pos])))
        timestr = time.strftime("%Y%m%d-%H%M%S")
        filename = "final-" + str(pos) + "-" + timestr + ".xml"
        individual.persist(os.path.join(experimentDir, filename))
    #ga.getDBAdapter().commit()
    
    shutil.copy2('pyevolve.db', experimentDir)
    shutil.copy2(conf.getProperty("System Log"), experimentDir)
    os.system("pyevolve_graph.py -i \"Lucy walk\" -3 -o gene_pool/experiment_img/" + experimentTime + " -e png")
    
    #do the stats    
    print ga.getStatistics()
Ejemplo n.º 5
0
from parser.LoadPoses                           import LoadPoses
from datatypes.DTIndividualProperty             import DTIndividualProperty, DTIndividualPropertyCMUDaz, DTIndividualPropertyVanilla, DTIndividualPropertyBaliero, DTIndividualPropertyVanillaEvolutive, DTIndividualPropertyPhysicalBioloid
from datatypes.DTIndividualGeneticMaterial      import DTIndividualGeneticMaterial, DTIndividualGeneticTimeSerieFile, DTIndividualGeneticMatrix
from Pose                                       import Pose
from configuration.LoadSystemConfiguration      import LoadSystemConfiguration
from simulator.LoadRobotConfiguration           import LoadRobotConfiguration
from Individual                                 import Individual

import os
import glob
import time
import sys

propCMUDaz = DTIndividualPropertyCMUDaz()
propVanilla = DTIndividualPropertyVanilla()
balieroProp = DTIndividualPropertyBaliero()
physicalProp = DTIndividualPropertyPhysicalBioloid()
geneticVanillaProp = DTIndividualPropertyVanillaEvolutive()

conf = LoadSystemConfiguration()

CMUxmlDir = os.getcwd()+conf.getDirectory("Transformed CMU mocap Files")


for filename in glob.glob(os.path.join(CMUxmlDir, '*.xml')):
    walk = Individual(propCMUDaz, DTIndividualGeneticTimeSerieFile(filename))
    fitness = walk.execute()
    length = walk.getLength()
    walk.persist("/tmp/"+str(fitness)+".xml")
    print "individual: ", filename, "fitness: ", fitness, "length: ", length