예제 #1
0
 def test_createAlleles_default(self):
     _alleles = GAllele.GAlleles(allele_list=None)
     self.assertTrue(hasattr(_alleles, 'allele_list'), True)
     self.assertTrue(hasattr(_alleles, 'homogeneous'), True)
     self.assertEqual(_alleles.allele_list, [])
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3])
     self.assertEqual(_alleles.allele_list, [1, 2, 3])
     _alleles = GAllele.GAlleles(homogeneous=True)
     self.assertEqual(_alleles.homogeneous, True)
예제 #2
0
def main_run():

    global cm, coords

    # load the tsp data file
    filehandle = open("instancias.txt", "r+")
    coords = read_file(filehandle)
    cm = cartesian_matrix(coords)

    # set the alleles to the cities numbers
    setOfAlleles = GAllele.GAlleles(homogeneous=True)
    lst = [i for i in xrange(len(coords))]
    a = GAllele.GAlleleList(lst)
    setOfAlleles.add(a)

    genome = G1DList.G1DList(len(coords))
    genome.setParams(allele=setOfAlleles)

    genome.evaluator.set(eval_func)
    genome.mutator.set(Mutators.G1DListMutatorSwap)
    genome.crossover.set(Crossovers.G1DListCrossoverOX)
    genome.initializator.set(G1DListTSPInitializator)
    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(1000)
    ga.setMinimax(Consts.minimaxType["minimize"])
    ga.setCrossoverRate(1.0)
    ga.setMutationRate(0.03)
    ga.setPopulationSize(80)

    ga.evolve(freq_stats=100)
    best = ga.bestIndividual()

    write_tour_to_img(coords, best, "tsp_result.png")
예제 #3
0
    def _make_alleles(self): 
        """ Returns a GAllelle.Galleles instance with alleles corresponding to 
        the parameters specified by the user"""
        
        alleles = GAllele.GAlleles()
        count = 0
        for param in self.get_parameters().values():
            allele = None
            count += 1
            val = param.evaluate() #now grab the value 
            low = param.low
            high = param.high
      
            metadata = param.get_metadata()[0][1]
            
            #then it's a float or an int, or a member of an array
            if ('low' in metadata or 'high' in metadata) or array_test.search(param.targets[0]): 
                if isinstance(val, real_types):                
                    #some kind of float
                    allele = GAllele.GAlleleRange(begin=low, end=high, real=True)
                #some kind of int    
                if isinstance(val, int_types):
                    allele = GAllele.GAlleleRange(begin=low, end=high, real=False)
                    
            elif "values" in metadata and isinstance(metadata['values'], iterable_types):
                allele = GAllele.GAlleleList(metadata['values'])

            if allele:
                alleles.add(allele)
            else: 
                self.raise_exception("%s is not a float, int, or enumerated \
                datatype. Only these 3 types are allowed"%(param.targets[0]),ValueError)
        
        self.count = count
        return alleles
예제 #4
0
def run_ga(fast):
    """Initialize and run the genetic algorithms."""
    alleles = GAllele.GAlleles()  # create list of all alleles
    alleles.add(GAllele.GAlleleRange(1, 1000))  # range for the number of days
    alleles.add(GAllele.GAlleleRange(1, 20))  # range for hidden nodes
    alleles.add(GAllele.GAlleleRange(1, 10))  # number of epochs
    alleles.add(GAllele.GAlleleList([True, False]))  # bias
    alleles.add(
        GAllele.GAlleleList([float(x * Decimal("0.1"))
                             for x in range(0, 10)]))  # momentum
    alleles.add(GAllele.GAlleleList([TanhLayer, SigmoidLayer]))  # tanh/sigmoid

    genome = G1DList.G1DList(len(alleles))
    genome.setParams(allele=alleles, fast=fast)
    genome.evaluator.set(eval_func)

    genome.mutator.set(Mutators.G1DListMutatorAllele)
    genome.initializator.set(Initializators.G1DListInitializatorAllele)

    gen_alg = GSimpleGA.GSimpleGA(genome)
    gen_alg.setMultiProcessing(not fast)
    gen_alg.selector.set(Selectors.GRouletteWheel)
    gen_alg.setGenerations(20)

    gen_alg.evolve(freq_stats=0)
    return gen_alg.bestIndividual()
예제 #5
0
def new_genome(results_path, **kwargs):
    '''
    *new_genome : takes a set of alleles [function_alleles, leaves_alleles] 
                and options that define initializator, mutator, crossover, evaluator 
                and returns a genome with those options
                
                possible initializator : "grow" : "grow" algorithm of network = recursive and possibly incomplete
                possible mutator : "simple" : change genomic alleles with possible alleles with probability pmut
                possible crossover :
                possible evaluator : "degree_distribution", "2distributions"
                possible network-type : "directed_weighted", "directed_unweighted", "undirected_weighted", "undirected_unweighted"
                possible tree_type : "with_constants"
     '''
    evaluation_method = kwargs.get("evaluation_method")
    network_type = kwargs.get("network_type")
    data_path = kwargs.get("data_path")
    name = kwargs.get("name")
    dynamic = kwargs.get("dynamic")
    extension = kwargs.get("extension")

    choices = emo.get_alleles(evaluation_method, network_type)
    genome = py.GTree.GTree()

    #genome.setParams(nb_nodes=ne.get_number_of_nodes(results_path))
    #genome.setParams(nb_edges=ne.get_number_of_edges(results_path))
    genome.setParams(data_path=data_path)
    genome.setParams(results_path=results_path)
    genome.setParams(name=name)
    genome.setParams(extension=extension)

    #defines alleles : one array containing possible leaves and one containing possible functions
    alleles = gall.GAlleles()
    lst = gall.GAlleleList(choices)
    alleles.add(lst)
    genome.setParams(allele=alleles)

    #defines the way to construct a random tree
    genome.setParams(max_depth=int(kwargs.get("max_depth", "3")))
    genome.setParams(max_siblings=int(kwargs.get("max_siblings", "2")))

    genome.setParams(tree_type=kwargs.get("tree_type", "default"))
    genome.initializator.set(tree_init)

    #defines the how to evaluate a genome
    genome.setParams(evaluation_method=evaluation_method)
    if dynamic:
        genome.evaluator.set(eval_func_dynamic)
    else:
        genome.evaluator.set(eval_func)

    #defines the crossover function - default now

    #defines the function that mutates trees
    genome.mutator.set(mutate_tree)

    #defines the network_type
    genome.setParams(network_type=network_type)

    #tree_init(genome)
    return genome
예제 #6
0
def solve():

    setOfAlleles = GAllele.GAlleles(homogeneous=True)
    lst = [i for i in xrange(len(points))]
    a = GAllele.GAlleleList(lst)
    setOfAlleles.add(a)

    genome = G1DList.G1DList(len(points))
    genome.setParams(allele=setOfAlleles)

    genome.evaluator.set(eval_func)
    genome.mutator.set(Mutators.G1DListMutatorSwap)
    genome.crossover.set(Crossovers.G1DListCrossoverOX)
    genome.initializator.set(tsp_initializator)

    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(1000)
    ga.setMinimax(Consts.minimaxType["minimize"])
    ga.setCrossoverRate(1.0)
    ga.setMutationRate(0.03)
    ga.setPopulationSize(80)

    ga.evolve(freq_stats=100)
    best = ga.bestIndividual()

    best.append(best[0])
    for i in range(len(best) - 1):
        canvas.create_line(points[best[i]].x, points[best[i]].y,
                           points[best[i + 1]].x, points[best[i + 1]].y)
예제 #7
0
def run_main():
    # Genome instance
    setOfAlleles = GAllele.GAlleles()

    for i in xrange(1000):
        # You can even add objects instead of strings or
        # primitive values
        a = GAllele.GAlleleList(['UP', 'DOWN', 'LEFT', 'RIGHT'])
        setOfAlleles.add(a)

    # Genome instance
    genome = G1DList.G1DList(300)
    #genome.setParams(rangemin=0, rangemax=10)
    genome.setParams(allele=setOfAlleles)

    # The evaluator function (objective function)
    genome.evaluator.set(eval_func)
    # This mutator and initializator will take care of
    # initializing valid individuals based on the allele set
    # that we have defined before
    genome.mutator.set(Mutators.G1DListMutatorAllele)
    genome.initializator.set(Initializators.G1DListInitializatorAllele)
    # Genetic Algorithm Instance
    ga = GSimpleGA.GSimpleGA(genome)
    ga.selector.set(Selectors.GRouletteWheel)
    ga.setGenerations(800)
    ga.stepCallback.set(evolve_callback)

    # Do the evolution
    ga.evolve()

    # Best individual
    print ga.bestIndividual()
 def setUp(self):
     self.alleles = GAllele.GAlleles()
     self.alleles.add(MappedAlleleRange(10, 100))
     self.alleles.add(MappedAlleleRange(0, 2, real=True))
     self.alleles.add(MappedAlleleList([2, 4, 12]))
     self.alleles.add(MappedAlleleList([-1]))
     self.genome = G1DList.G1DList(len(self.alleles))
     self.genome.setParams(allele=self.alleles, rangemin=-1, rangemax=1)
예제 #9
0
 def test_Alleles_slicing(self):
     # includes slice operation, getitem and setitem
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3])
     self.assertEqual(_alleles[1], 2)
     with self.assertRaises(Exception):
         _ = _alleles[4]
     _alleles[1] = 5
     self.assertEqual(_alleles[1], 5)
     self.assertEqual(_alleles[0:2], [1, 5])
예제 #10
0
def main_run(path):
   global cm, coords

   # write_random(filename, number of the cities, max width, max height)
   #write_random("tsp_coords.txt", 50, 400, 400)

   # load the tsp data file
   filehandle = open("tsp_coords.txt", "r")
   coords = path
   cm = cartesian_matrix(coords)

   # set the alleles to the cities numbers
   setOfAlleles = GAllele.GAlleles(homogeneous=True)
   lst = [ i for i in xrange(len(coords)) ]
   a = GAllele.GAlleleList(lst)
   setOfAlleles.add(a)
      
   genome = G1DList.G1DList(len(coords))
   genome.setParams(allele=setOfAlleles)

   genome.evaluator.set(eval_func)
   genome.mutator.set(Mutators.G1DListMutatorSwap)
   genome.crossover.set(Crossovers.G1DListCrossoverOX)
   genome.initializator.set(G1DListTSPInitializator)

   ga = GSimpleGA.GSimpleGA(genome)
   ga.setGenerations(300)
   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.setCrossoverRate(1.0)
   ga.setMutationRate(0.03)
   ga.setPopulationSize(80)

   #sqlite_adapter = DBAdapters.DBSQLite(identify="tsp", commit_freq=1000, frequency=500)
   #ga.setDBAdapter(sqlite_adapter)

   # This is to make a video
   # ga.stepCallback.set(evolve_callback)

   ga.evolve(freq_stats=100)
   best = ga.bestIndividual()
   best.fitness_list = fitness_list
   if PIL_SUPPORT:
      write_tour_to_img(coords,cm, best, "tsp_result_%d.png")
   else:
      print "No PIL detected, cannot plot the graph !"
   return [best.getRawScore(), fitness_list]
예제 #11
0
def run_simulation(pset, max_generations, initial_list=None):
    # Genome instance
    setOfAlleles = GAllele.GAlleles()
    setOfAlleles.add(GAllele.GAlleleRange(0, 51))
    setOfAlleles.add(GAllele.GAlleleRange(0, 6))
    setOfAlleles.add(GAllele.GAlleleRange(0, 51))

    # Genome instance, 1D List of 50 elements
    genome = G1DList.G1DList(3)
    genome.setParams(allele=setOfAlleles)

    #Fitness function

    fe = FitnessEvaluator(pset.fitness_fnc, pset.fitness_temp)
    Consts.CDefScaleLinearMultiplier = pset.fitness_temp

    application = "OS" if "oxide" in pset.fitness_fnc.__name__ else "LS"

    st = StatTrack(fe, pset.mutation_rate, pset.tournament_rate, include_ridiculous=pset.include_ridiculous, application=application)

    genome.crossover.set(pset.crossover_fnc)
    genome.mutator.set(pset.mutation_fnc)
    genome.evaluator.set(fe.array_to_score)
    genome.initializator.set(pset.initialization_fnc)

    ga = GSimpleGA.GSimpleGA(genome)

    ga.selector.set(pset.selection_fnc)
    ga.terminationCriteria.set(AllFoundCriteria)
    ga.stepCallback.set(st.evolve_callback)
    ga.setPopulationSize(pset.popsize)
    ga.setGenerations(max_generations)

    if pset.elitism_num > 0:
        ga.setElitism(True)
        ga.setElitismReplacement((int)(math.ceil(pset.elitism_num * pset.popsize)))
    else:
        ga.setElitism(False)

    ga.setMutationRate(pset.mutation_rate)
    # TODO: figure out niching
    stats_freq = 0
    ga.evolve(freq_stats=stats_freq)

    return st
예제 #12
0
def main_run(distancesFileName,
             fragmentFileName,
             crossover_rate=1.0,
             mutation_rate=0.03,
             population_size=80):
    """
    @param distancesFileName String The file containing the pairwise distances of all
                                fragments
    """
    global cm, coords, fragments

    # Load the fragments
    fragmentFile = open(fragmentFileName, "r")
    fragments = readFragmentFile(fragmentFile)

    # load the tsp data file
    filehandle = open(distancesFileName, "r")
    coords = read_coords(filehandle)
    cm = coords

    # set the alleles to the cities numbers
    setOfAlleles = GAllele.GAlleles(homogeneous=True)
    lst = [i for i in xrange(len(coords))]
    a = GAllele.GAlleleList(lst)
    setOfAlleles.add(a)

    genome = G1DList.G1DList(len(coords))
    genome.setParams(allele=setOfAlleles)

    genome.evaluator.set(eval_func)
    genome.mutator.set(Mutators.G1DListMutatorSwap)
    genome.crossover.set(Crossovers.G1DListCrossoverOX)
    genome.initializator.set(G1DListTSPInitializator)

    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(5000)  # 10000 is a good "real" value
    ga.setMinimax(Consts.minimaxType["minimize"])
    ga.setCrossoverRate(crossover_rate)
    ga.setMutationRate(mutation_rate)
    ga.setPopulationSize(population_size)

    ga.evolve(freq_stats=100)
    best = ga.bestIndividual()

    return eval_func(best), best.getInternalList()
예제 #13
0
def run_main():
    # Genome instance
    setOfAlleles = GAllele.GAlleles()

    # From 0 to 10 we can have only some
    # defined ranges of integers
    for i in xrange(11):
        a = GAllele.GAlleleRange(0, i)
        setOfAlleles.add(a)

    # From 11 to 19 we can have a set
    # of elements
    for i in xrange(11, 20):
        # You can even add objects instead of strings or
        # primitive values
        a = GAllele.GAlleleList(['a', 'b', 'xxx', 666, 0])
        setOfAlleles.add(a)

    print setOfAlleles
    genome = G1DList.G1DList(20)
    genome.setParams(allele=setOfAlleles)

    # The evaluator function (objective function)
    genome.evaluator.set(eval_func)

    # This mutator and initializator will take care of
    # initializing valid individuals based on the allele set
    # that we have defined before
    genome.mutator.set(Mutators.G1DListMutatorAllele)
    genome.initializator.set(Initializators.G1DListInitializatorAllele)

    # Genetic Algorithm Instance
    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(40)

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

    # Best individual
    print ga.bestIndividual()
예제 #14
0
def run_main():
   print "Starting main()!"
   #sys.stdout.flush()
   global NUM_GENS, NUM_POP, NUM_ELITE, GLOB_COUNT, NO_OF_PARAMS
   setOfAlleles = GAllele.GAlleles()
   sf = GAllele.GAlleleList(strp_fac)
   su = GAllele.GAlleleList(strp_unt)
   cn = GAllele.GAlleleList(cb_nds)
   # cs = GAllele.GAlleleList(cb_buf_size)
   al = GAllele.GAlleleList(alignment)
   sb = GAllele.GAlleleList(siv_buf_size)
   setOfAlleles.add(sf)
   setOfAlleles.add(su)
   setOfAlleles.add(cn)
   # setOfAlleles.add(cs)
   setOfAlleles.add(al)
   setOfAlleles.add(sb)

   genome = G1DList.G1DList(NO_OF_PARAMS)
   genome.setParams(allele=setOfAlleles)

   genome.evaluator.set(eval_func)
   genome.mutator.set(Mutators.G1DListMutatorAllele)
   genome.initializator.set(Initializators.G1DListInitializatorAllele)

   ga = GSimpleGA.GSimpleGA(genome)
   ga.selector.set(Selectors.GRouletteWheel)
   ga.setMutationRate(0.15);
   ga.setGenerations(NUM_GENS)
   #ga.terminationCriteria.set(ConvergenceCriteria)
   ga.setPopulationSize(NUM_POP)
   ga.setMinimax(Consts.minimaxType["minimize"])
   ga.setElitism(True)
   ga.setElitismReplacement(NUM_ELITE)
   print 'ga.evolve'
   ga.evolve(freq_stats=1)
   print 'closing result'
   result_output.close()
   print 'Best solution'
   print ga.bestIndividual()
예제 #15
0
    def __init__(self, generations, population, crossover, mutation, elite,
                 experiment, genCallBack, evalFunc, drivers):
        self.experiment = experiment
        self.population = population
        self.crossoverProb = crossover
        self.elite = elite
        self.mutationProb = mutation
        self.generations = generations
        self.genCallBack = genCallBack
        self.evalFunc = evalFunc
        self.drivers = drivers

        # sets pyevolve
        # create alleles to make a GA model. each driver is represented as an allele
        # each driver can take k different routes which is modelled by the different
        # values each allele can take
        driversAlleles = GAllele.GAlleles()
        for dr in drivers:
            lst = GAllele.GAlleleList(range(dr.od.numPaths))
            driversAlleles.add(lst)
        # define a genome with length = length of drivers
        genome = G1DList.G1DList(len(drivers))
        genome.setParams(allele=driversAlleles)
        genome.evaluator.set(self.evalFuncCallback)
        genome.initializator.set(self.initGenome)
        # Genetic Algorithm Instance
        self.ga = GSimpleGA.GSimpleGA(genome)
        self.ga.setMinimax(Consts.minimaxType["minimize"])
        self.ga.selector.set(Selectors.GRankSelector)
        self.ga.setGenerations(self.generations)
        self.ga.stepCallback.set(self.genCallBack)
        self.ga.setMutationRate(self.mutationProb)
        self.ga.setCrossoverRate(self.crossoverProb)
        self.ga.setPopulationSize(self.population)
        self.ga.terminationCriteria.set(GSimpleGA.RawStatsCriteria)
        self.ga.setElitism(True)
        self.ga.setElitismReplacement(self.elite)
        self.ga.setSortType(Consts.sortType["raw"])
예제 #16
0
    def run(self):
        # Allele define valid chromosome value
        alleles = GAllele.GAlleles()

        # Define gene with 2 chromosomes
        # MA type
        alleles.add(GAllele.GAlleleList([0, 1, 2, 3, 4]))
        # MA range
        alleles.add(GAllele.GAlleleRange(1, 99))

        # Genome instance, 1D List
        genome = G1DList.G1DList(len(alleles))
        # Sets the range max and min of the 1D List
        genome.setParams(allele=alleles)
        # The evaluator function (evaluation function)
        genome.evaluator.set(self.fitness)
        # This mutator and initializator will take care of
        # initializing valid individuals based on the allele set
        # that we have defined before
        genome.mutator.set(Mutators.G1DListMutatorAllele)
        genome.initializator.set(Initializators.G1DListInitializatorAllele)

        # Genetic Algorithm Instance
        ga = GSimpleGA.GSimpleGA(genome)
        # Set the Roulette Wheel selector method, the number of generations and
        # the termination criteria
        ga.selector.set(Selectors.GRouletteWheel)
        ga.setGenerations(self.gen)
        ga.setPopulationSize(self.pop)
        ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria)

        pop = ga.getPopulation()
        pop.scaleMethod.set(Scaling.SigmaTruncScaling)

        ga.evolve(freq_stats=10)
        # Best individual
        self.best = ga.bestIndividual()
예제 #17
0
 def test_Alleles_iter(self):
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3])
     self.assertIsInstance(iter(_alleles), Iterable)
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3], homogeneous=True)
     self.assertIsInstance(iter(_alleles), Iterable)
예제 #18
0
def run_main():
    # Global runner instance that will also be used by eval_func
    global runner
    global log

    # "Settings"
    working_dir = '../work'
    log_dir = '../log'
    compare_values = '../ext/Detalierte Mechanismus.csv'
    log = Logger()
    log.setLogLevel('debug')

    # load parameter format defines from parameters.py
    import parameters
    pformat = parameters.parameter_format

    # load KivaRunner
    l = Logger()
    l.setLogLevel('info')
    runner = KivaRunner(working_dir, log_dir, compare_values, pformat, l)
    if runner.error:
        return

    # Genome instance
    setOfAlleles = GAllele.GAlleles()

    # loop trough parameter format to create correct alleles
    for p in pformat:
        minimum = p[2]
        maximum = p[3]
        # log.debug("maximum: %s, minimum: %s" % (maximum, minimum))
        a = GAllele.GAlleleRange(minimum, maximum,
                                 not isinstance(minimum, int))
        setOfAlleles.add(a)

    genome = G1DList.G1DList(len(pformat))
    genome.setParams(allele=setOfAlleles)

    # The evaluator function (objective function)
    genome.evaluator.set(eval_func)

    # This mutator and initializator will take care of
    # initializing valid individuals based on the allele set
    # that we have defined before
    genome.mutator.set(Mutators.G1DListMutatorAllele)
    # genome.initializator.set(G1DListInitializatorAlleleKiva)
    genome.initializator.set(Initializators.G1DListInitializatorAllele)

    # Genetic Algorithm Instance
    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(10)
    ga.setPopulationSize(20)
    ga.setMinimax(Consts.minimaxType["minimize"])
    # ga.setCrossoverRate(1.0)
    ga.setMutationRate(0.1)
    ga.selector.set(Selectors.GRouletteWheel)

    sqlite_adapter = DBAdapters.DBSQLite(identify="ex1", resetDB=True)
    ga.setDBAdapter(sqlite_adapter)

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

    # Best individual
    best = ga.bestIndividual()
    print "\nBest individual score: %.2f" % (best.getRawScore(), )
    print best
예제 #19
0
    def generateDecision(self):
        setOfAlleles = GAllele.GAlleles(homogeneous=True)
        #raw_input("Press ENTER to exit")
        # prepare indices

        #print "Preparing indices..."

        indicesContainer = IndicesContainer(self.training_low_prices,
                                            self.training_high_prices,
                                            self.training_close_prices,
                                            self.training_volumes)
        indicesContainer.computeIndices()
        indicesList = indicesContainer.getIndicesList()

        # prepare sell trend and buy trend vectors

        #print "Preparing sell trend and buy trend vectors..."

        #normalizedIndicesList = indices.indicesNormalizer().normalize(indicesContainer.getIndicesList())
        tradingGA.sellTrendBeginning, tradingGA.buyTrendBeginning = simpleTrendBeginningsFinder(
            self.training_close_prices, indicesList).findTrendBeginnings()

        # prepare individual

        #print "Preparing first individual..."

        a = GAllele.GAlleleList(indicesList)
        setOfAlleles.add(a)

        genome = G1DList.G1DList()
        genome.setParams(allele=setOfAlleles)

        genome.evaluator.set(eval_func)
        genome.mutator.set(G1DListStockMutator)
        genome.crossover.set(G1DListStockCrossoverOperator)
        genome.initializator.set(G1DListStockInitializator)

        # prepare engine

        #print "Preparing Genetic Algorithm engine..."

        ga = GSimpleGA.GSimpleGA(genome)
        ga.setGenerations(self.generations)
        ga.setMinimax(Consts.minimaxType["maximize"])
        ga.setCrossoverRate(1.0)
        ga.setMutationRate(0.1)
        ga.setElitismReplacement(3)
        ga.selector.set(Selectors.GUniformSelector)
        ga.setPopulationSize(self.population_size)

        #print "Executing indices subset search..."

        ga.evolve(freq_stats=0)
        best = ga.bestIndividual()

        #print "Generating trading signal..."

        #print "Preparing prediction set indices..."

        predictionIndicesContainer = IndicesContainer(
            self.prediction_low_prices, self.prediction_high_prices,
            self.prediction_close_prices, self.prediction_volumes)
        predictionIndicesContainer.computeIndices()
        predictionIndicesList = predictionIndicesContainer.getIndicesList()

        # prepare sell trend and buy trend vectors

        #print "Preparing prediction set sell trend and buy trend vectors..."

        sell = computeClusterCentre(best.getInternalList(),
                                    tradingGA.sellTrendBeginning)
        buy = computeClusterCentre(best.getInternalList(),
                                   tradingGA.buyTrendBeginning)
        predictionIndicesList = pickIndices(predictionIndicesList,
                                            best.getInternalList())
        prediction = computeClusterCentre(
            predictionIndicesList, len(predictionIndicesList[0].getResult(
            )))  #trend beginning to ostatni element listy z danymi

        d1 = numpy.linalg.norm(numpy.asarray(buy) - numpy.asarray(prediction))
        d2 = numpy.linalg.norm(numpy.asarray(sell) - numpy.asarray(prediction))

        if d1 < d2:
            #print "Time for Buyin'"
            return 1
        elif d1 > d2:
            #print "Time for Sellin'"
            return -1

        return 0
예제 #20
0
def Grid_Constructor(numline, numParm, data):
    alleles = GAllele.GAlleles()
    for i in range(0, numline * numParm):
        alleles.add(GAllele.GAlleleRange(data[i][0], data[i][1]))
    return alleles
예제 #21
0
 def test_Alleles_repr(self):
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3])
     self.assertIsInstance(repr(_alleles), str)
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3], homogeneous=True)
     self.assertIsInstance(repr(_alleles), str)
예제 #22
0
 def test_Alleles_slicing_homogeneous(self):
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3], homogeneous=True)
     self.assertEqual(_alleles[2], 1)
     _alleles[1] = 5
     self.assertEqual(_alleles[0], 5)
예제 #23
0
 def test_Alleles_add(self):
     _alleles1 = GAllele.GAlleles(allele_list=[1, 2, 3])
     _alleles1.add(4)
     self.assertEqual(_alleles1.allele_list, [1, 2, 3, 4])
예제 #24
0
        list_ += value
    return list_

def convert_to_dict(chromosome):
    dict_ = {}
    keys = init_cutpoints.keys()
    i = 0
    for key in keys:
        dict_[key] = chromosome[i:i+3]
        i += 3
    return dict_


chromosome_ = convert_to_list(init_cutpoints)

setOfAlleles = GAllele.GAlleles()
keys = init_cutpoints.keys()
for key in keys:
    for _ in range(0, 3):
        if key != 'cip':
            a = GAllele.GAlleleRange(int(df[key].min()), int(df[key].max()))
            setOfAlleles.add(a)
        else:
            a = GAllele.GAlleleRange(0, 10)
            setOfAlleles.add(a)

df_actual = pd.read_csv("data/Cust_Actual.csv", index_col=['index'])

genome = G1DList.G1DList(len(chromosome_))
genome.setParams(allele=setOfAlleles)
예제 #25
0
 def test_Alleles_len(self):
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3])
     self.assertEqual(len(_alleles), 3)
     _alleles = GAllele.GAlleles(allele_list=[1, 2, 3], homogeneous=True)
     self.assertEqual(len(_alleles), 1)