示例#1
0
    def family_competition(self, k=2):

        parent_fitness = [(solution,
                           Fitness.get_fitness(solution,
                                               function=self.fitness_function))
                          for solution in self.parent]
        child_fitness = [(solution,
                          Fitness.get_fitness(solution,
                                              function=self.fitness_function))
                         for solution in self.children]
        failed_reproduction = [
            baby_fitness[1] <= max(parent_fitness, key=itemgetter(1))[1]
            for baby_fitness in child_fitness
        ]

        family_fitness = parent_fitness + child_fitness
        sorted_family = sorted(family_fitness,
                               key=lambda x: x[1],
                               reverse=True)
        kth_best, kth1_best = sorted_family[k - 1], sorted_family[k]

        if kth_best[1] == kth_best[1]:
            if kth1_best[0] in self.parent and not kth_best in self.parent:
                sorted_family[k - 1] = kth1_best
                sorted_family[k] = kth_best

        return [solution[0]
                for solution in sorted_family[:k]], failed_reproduction
示例#2
0
 def set_best(self):
     self._best_fitness = Fitness.calculate(self.best_position)
     for particle in self.swarm:
         this_fitness = Fitness.calculate(particle.position)
         if this_fitness < self._best_fitness:
             self._best_fitness = this_fitness
             self.best_position = copy.deepcopy(particle.position)
示例#3
0
    def testEvalIndividualCapacityNotZero(self):
        ''' test that no one's perfect
        '''
        pop = toolBox.toolbox.population(n=2)
        fit = Fitness()

        self.assertGreater(fit.evalIndividualCapacity(pop[0]), 0)
示例#4
0
    def testEvalIndividualCapacity(self):
        ''' test to check that no individual is assigned a fitness value less than 0
        '''
        pop = toolBox.toolbox.population(n=2)
        fit = Fitness()

        self.assertFalse(fit.evalIndividualCapacity(pop[0]) < 0)
示例#5
0
 def __init__(self, app_list, pe_list):
     self.app_list = app_list
     self.pe_list = pe_list
     self.layer_list = [l for app in app_list for l in app.layer_list]
     self.num_layer = len(self.layer_list)
     self.num_pe = len(pe_list)
     self.fitness = Fitness(app_list, pe_list)
示例#6
0
    def xtest_evaluate(self):
        ind = ConvIndividual()
        ind.randomInit()
        print(ind)

        fit = Fitness("data/mnist2d.train")
        print("evaluating")
        print(fit.evaluate(ind))
示例#7
0
文件: test.py 项目: JiriVanek/GAKeras
 def xtest_evaluate(self):
     ind = ConvIndividual()
     ind.randomInit()
     print(ind)
     
     fit = Fitness("data/mnist2d.train")
     print("evaluating")
     print( fit.evaluate(ind) )
示例#8
0
    def testEvalIndividualCapacityZeroCapacity(self):
        ''' test worst case scenario - individual with zero capacity has the worst fitness
        '''
        pop = toolBox.toolbox.population(n=2)
        fit = Fitness()
        ind1 = pop[0]
        ind2 = pop[1]
        
        for i, item in enumerate(ind1):
            ind1[i][1] = 0

        self.assertGreater(fit.evalIndividualCapacity(ind1), fit.evalIndividualCapacity(ind2))
示例#9
0
    def testEvalIndividualCapacitySufficient(self):
        ''' test on individual that offers more than enough capacity to handle all requests
        '''
        pop = toolBox.toolbox.population(n=2)
        fit = Fitness()
        ind1 = pop[0]
        ind2 = pop[1]
        
        for i, item in enumerate(ind1):
            ind1[i][1] = 120

        self.assertGreater(fit.evalIndividualCapacity(ind2), fit.evalIndividualCapacity(ind1))
示例#10
0
文件: main.py 项目: puzanov/monad
def main():
    # Generate the population
    pop = toolBox.toolbox.population(n=POPULATION_SIZE)

    hof = tools.HallOfFame(1)

    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)

    pop, log = algorithms.eaSimple(pop,
                                   toolBox.toolbox,
                                   cxpb=CROSS_OVER_PROB,
                                   mutpb=MUTATION_PROB,
                                   ngen=NO_OF_GENERATION,
                                   stats=stats,
                                   halloffame=hof,
                                   verbose=True)

    ## Evaluate the entire population
    #fitnesses = list(map(toolBox.toolbox.evaluate, pop))
    #for ind, fit in zip(pop, fitnesses):

    #    ind.fitness.values = fit

    # Iterate trough a number of generations
    # for g in range(NGEN):
    #    print("-- Generation %i --" % g)
    #    # Select individuals based on their fitness
    #    offspring = toolBox.toolbox.select(pop, len(pop))
    #    # Cloning those individuals into a new population
    #    offspring = list(map(toolBox.toolbox.clone, offspring))

    #    # Calling the crossover function
    #    crossover(offspring)
    #    mutation(offspring)

    #    invalidfitness(offspring)

    # The Best Individual found
    best_ind = tools.selBest(pop, 1)[0]
    individual = sorted(best_ind, key=itemgetter(3))
    individual = sorted(individual, key=itemgetter(0))
    #print "InsertBusTrip and TimeTable......"
    print("Best individual is %s, %s" % (individual, best_ind.fitness.values))
    print("Length of best individual: " + str(len(best_ind)))
    fitnessClass = Fitness()
    timetable = fitnessClass.genTimetable(best_ind)
    databaseClass = DB()
    #databaseClass.insertBusTrip(timetable)
    evaluate_timetable.eval(best_ind)
示例#11
0
    def Gera_PopInic(self, caracter, TAM_Pop,
                     NUM_CROM):  # Gera uma população inicial

        for x in range(0, TAM_Pop):  # Laço para
            IND = Individuo(caracter)  # Variável recebe indivíduo
            F = Fitness(
                self.Frase,
                NUM_CROM)  # A Variável F recebe instancia da classe fitness
            self.listPop.append(
                F.Calc_Fitness(IND.Gera_Individuo(NUM_CROM))
            )  # Adiciona o individuo na lista de populações e calcula o Fitness
            print(self.listPop[x])  # imprimi o indivíduo
        return self.listPop  # retorna a lista de indivíduos
示例#12
0
文件: main.py 项目: 4sp1r3/monad
def main():
    # Generate the population
    pop = toolBox.toolbox.population(n=POPULATION_SIZE)

    hof = tools.HallOfFame(1)

    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)

    pop, log = algorithms.eaSimple(pop, toolBox.toolbox, cxpb=CROSS_OVER_PROB,
                                   mutpb=MUTATION_PROB, ngen=NO_OF_GENERATION, stats=stats,
                                   halloffame=hof, verbose=True)



    ## Evaluate the entire population
    #fitnesses = list(map(toolBox.toolbox.evaluate, pop))
    #for ind, fit in zip(pop, fitnesses):

    #    ind.fitness.values = fit

    # Iterate trough a number of generations
    # for g in range(NGEN):
    #    print("-- Generation %i --" % g)
    #    # Select individuals based on their fitness
    #    offspring = toolBox.toolbox.select(pop, len(pop))
    #    # Cloning those individuals into a new population
    #    offspring = list(map(toolBox.toolbox.clone, offspring))

    #    # Calling the crossover function
    #    crossover(offspring)
    #    mutation(offspring)

    #    invalidfitness(offspring)

    # The Best Individual found
    best_ind = tools.selBest(pop, 1)[0]
    individual = sorted(best_ind, key=itemgetter(3))
    individual = sorted(individual, key=itemgetter(0))
    #print "InsertBusTrip and TimeTable......"
    print("Best individual is %s, %s" % (individual, best_ind.fitness.values))
    print ("Length of best individual: " + str(len(best_ind)))
    fitnessClass = Fitness()
    timetable = fitnessClass.genTimetable(best_ind)
    databaseClass = DB()
    #databaseClass.insertBusTrip(timetable)
    evaluate_timetable.eval(best_ind)
示例#13
0
    def localSearch(self, solution, solution_fitness, materials_changed):
        new_concept_coverage = solution
        new_best_fitness = solution_fitness

        for j in range(self.local_search_size):
            fitness_improved = False
            for material in materials_changed:
                for concept in range(num_concepts):
                    step_concept_coverage = new_concept_coverage.copy()
                    step_concept_coverage[
                        material,
                        concept] = ~step_concept_coverage[material, concept]
                    step_fitness = sum([
                        Fitness.get_fitnessConcepts(student_id,
                                                    step_concept_coverage.T)
                        for student_id in range(num_students)
                    ]) / num_students

                    if new_best_fitness > step_fitness:
                        new_best_fitness = step_fitness
                        new_concept_coverage = step_concept_coverage
                        fitness_improved = True

            if not fitness_improved:
                break
        return new_concept_coverage, new_best_fitness
示例#14
0
 def __start__(self):
     for i in self.tqdm:
         for p in self.population:
             fitness = Fitness(self.population[p])
             selection = self.__selection__(self.population[p])
             crossover = self.__crossover__(selection, self.population[p])
             mutation = self.__mutation___(crossover)
示例#15
0
    def run(self, X, Y):

        self.fitfun = Fitness(X, Y)
        self.evolops = Evol_operators(self.degree_range, 1, self.max_terms)
        self.pop = self._create_init_pop()

        for g in range(self.gens):

            ftournament = lambda x, y: x if x.fitness < y.fitness else y

            childs = self.pop

            #crossover
            #childs = self._apply_crossover(childs, ftournament)

            #mutação
            childs = self._apply_mutation(childs)

            self.pop = self._apply_tourn_sel(childs + self.pop, ftournament)

            self.printInfo(g)

        if self.log != None:
            df = pd.DataFrame(self.results)
            df.to_csv(self.log, index=False)

        return self
def rankRoutes(population):
    fitnessResults = {}
    for i in range(0, len(population)):
        fitnessResults[i] = Fitness(population[i]).routeFitness()
    return sorted(fitnessResults.items(),
                  key=operator.itemgetter(1),
                  reverse=True)
 def rank_routes(self, population):
     # Calcula o custo de cada rota e ranqueia do melhor(menor) pro pior(maior)
     fitness_results = {}
     for i in range(0, len(population)):
         fitness_results[i] = Fitness(population[i]).route_fitness()
     return sorted(fitness_results.items(),
                   key=lambda x: x[1],
                   reverse=True)
示例#18
0
def rankRoutes(
        population):  #kanoume rank ta routes/inidividuals TOU population
    fitnessResults = {}  #edo mesa exei ta routes taksinomimena
    for i in range(0, len(population)):
        fitnessResults[i] = Fitness(population[i]).routeFitness()
    return sorted(fitnessResults.items(),
                  key=operator.itemgetter(1),
                  reverse=True)
示例#19
0
 def __init__(self, position):
     self._position = position
     self._dimensions = len(position)
     self._best_position = position
     self._best_fitness = Fitness.calculate(position)
     self._velocity = [
         self.get_random_velocity() for _ in range(self._dimensions)
     ]
示例#20
0
def main():
    fitnessClass =Fitness()
    # Generate the population
    pop = toolBox.toolbox.population(n=POPULATION_SIZE)

    fitnessClass.evalIndividualCapacity(pop[0])
    hof = tools.HallOfFame(1)

    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)

    pop, log = algorithms.eaSimple(pop, toolBox.toolbox, cxpb=CROSS_OVER_PROB,
                                   mutpb=MUTATION_PROB, ngen=NO_OF_GENERATION, stats=stats,
                                   halloffame=hof, verbose=True)



    ## Evaluate the entire population
    #fitnesses = list(map(toolBox.toolbox.evaluate, pop))
    #for ind, fit in zip(pop, fitnesses):

    #    ind.fitness.values = fit

    # Iterate trough a number of generations
    # for g in range(NGEN):
    #    print("-- Generation %i --" % g)
    #    # Select individuals based on their fitness
    #    offspring = toolBox.toolbox.select(pop, len(pop))
    #    # Cloning those individuals into a new population
    #    offspring = list(map(toolBox.toolbox.clone, offspring))

    #    # Calling the crossover function
    #    crossover(offspring)
    #    mutation(offspring)

    #    invalidfitness(offspring)

    # The Best Individual found
    best_ind = tools.selBest(pop, 1)[0]
    print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))
    generateTimeTable(best_ind)
示例#21
0
文件: weather.py 项目: 4sp1r3/monad
 def generateBusTrip(self, trip):
     fitness = Fitness()
     db = DB()
     line = 0
     count = 0
     chromosome = []
     for tripInstance in trip:
         for busInstance in tripInstance[3]:
             if line != busInstance["line"] and count != 0:
                 chromosome.append([line, capacity, self.calculateFrequency(count), startTime])
                 count = 0
             if count == 0:
                 capacity = busInstance["capacity"]
                 startTime = busInstance["startTime"]
             line = busInstance["line"]
             count += 1
     chromosome.append([line, capacity, self.calculateFrequency(count), startTime])
     individual = fitness.genTimetable(chromosome)
     db.insertBusTrip2(individual)
 def test(self):
     seq = [[[16, 94], [41, 75], [25, 116], [29, 91], [28, 78], [35, 75]],
            [[22, 53], [32, 116], [43, 106]],
            [[38, 105], [37, 43], [18, 109], [12, 82], [50, 75]],
            [[6, 120], [54, 70], [32, 98], [50, 97], [26, 80]],
            [[13, 105], [30, 112], [31, 100]],
            [[23, 71], [32, 89], [29, 91], [22, 59]],
            [[38, 91], [38, 98], [11, 203], [24, 105], [25, 111], [54, 78],
             [44, 85], [49, 82], [58, 72], [30, 86], [22, 112]]]
     f = Fitness(DNA(seq))
     print(f.fitness)
示例#23
0
    def __init__(self,
                 max_generations: int,
                 start_population: int,
                 base_gene_chain: GeneChain,
                 crosser: Crosser,
                 selector: Selector,
                 mutator: Mutator,
                 verbose: bool = True):

        self._selector = selector
        self._crosser = crosser
        self._mutator = mutator
        self._fitness = Fitness()
        self._max_generations = max_generations
        self._verbose = verbose
        # Create random individuals
        self._individuals = [
            deepcopy(base_gene_chain) for i in range(start_population)
        ]
        for individ in self._individuals:
            individ.random()
示例#24
0
def rankRoutes(population):
    ''' rankRoutes function
	'''
    #   Initial dict
    fitnessResutsDict = dict()

    for i in xrange(0, len(population)):
        fitnessResutsDict[i] = Fitness(population[i]).routeFitness()

    return sorted(fitnessResutsDict.items(),
                  key=operator.itemgetter(1),
                  reverse=True)
示例#25
0
 def __convert_fitness_j_to_p(self, f):
     return Fitness(value=get_field(f, "value"),
                    u_sell=get_field(f, "uSell"),
                    u_buy=get_field(f, "uBuy"),
                    noop=get_field(f, "noop"),
                    realised_profit=get_field(f, "realisedProfit"),
                    mdd=get_field(f, "MDD"),
                    ret=get_field(f, "Return"),
                    wealth=get_field(f, "wealth"),
                    no_of_transactions=get_field(f, "noOfTransactions"),
                    no_of_short_selling_transactions=get_field(
                        f, "noOfShortSellingTransactions"))
示例#26
0
class Heuristic(MapFunc):
    def __init__(self, app_list, pe_list):
        self.app_list = app_list
        self.pe_list = pe_list
        self.layer_list = [l for app in app_list for l in app.layer_list]
        self.num_layer = len(self.layer_list)
        self.num_pe = len(pe_list)
        self.fitness = Fitness(app_list, pe_list)

    def do_schedule(self):
        self.mapping = [0] * len(self.layer_list)
        self._set_initial_mapping()
        if self._pass_constraint():
            self.fitness.calculate_fitness(self.mapping)
            return [self.mapping]
        else:
            return []  # no solution

    def _set_initial_mapping(self, mapping):
        raise NotImplementedError

    def _pass_constraint(self, mapping):
        raise NotImplementedError
    def run(self, concept_coverage, fitnessConcepts_total, DATFILE=None):
        best_solution = concept_coverage
        best_fitness = fitnessConcepts_total

        current_temperature = self.initial_temperature
        current_solution = concept_coverage
        current_fitness = fitnessConcepts_total

        self.get_orderOfModifiedMaterials()
        fitness_progress = np.empty(self.max_iterations)

        for i in range(self.max_iterations):
            for l in range(self.cycle):
                next_solution = self.get_randNeighbor(best_solution)
                next_fitness = sum([
                    Fitness.get_fitnessConcepts(student_id, current_solution.T)
                    for student_id in range(num_students)
                ]) / num_students

                deltaE = next_fitness - current_fitness
                if (deltaE < 0.0):
                    current_solution = next_solution
                    current_fitness = next_fitness

                    if (next_fitness < best_fitness):
                        best_solution = next_solution
                        best_fitness = next_fitness
                else:
                    if (random.uniform(0, 1) < math.exp(
                            -deltaE / current_temperature)):
                        current_solution = next_solution
                        current_fitness = next_fitness

            current_temperature = self.decreaseTemperature(current_temperature)
            fitness_progress[i] = best_fitness

        # print("current_temperature: ", current_temperature)
        if (DATFILE):
            with open(DATFILE, 'w') as f:
                f.write(str(best_fitness))
        else:
            with open('results_SA.pickle', 'wb') as file:
                pickle.dump(
                    {
                        "fitness_progress": fitness_progress,
                        "sa_concept_coverage": best_solution,
                        "sa_fitness": best_fitness
                    }, file)

            return best_solution, best_fitness
示例#28
0
class Genetic:
    def __init__(self,
                 max_generations: int,
                 start_population: int,
                 base_gene_chain: GeneChain,
                 crosser: Crosser,
                 selector: Selector,
                 mutator: Mutator,
                 verbose: bool = True):

        self._selector = selector
        self._crosser = crosser
        self._mutator = mutator
        self._fitness = Fitness()
        self._max_generations = max_generations
        self._verbose = verbose
        # Create random individuals
        self._individuals = [
            deepcopy(base_gene_chain) for i in range(start_population)
        ]
        for individ in self._individuals:
            individ.random()

    def _next_generation(self):
        # cross individ
        self._individuals = self._crosser.cross(self._individuals)
        # add mutatation
        self._individuals += self._mutator.mutate(self._individuals)
        # calculate fitness function for each indidivid
        for individ in self._individuals:
            individ.score = self._fitness.calc(individ)
        # sort individ by score
        self._individuals.sort(key=lambda i: i.score, reverse=True)
        # get best individ
        self._individuals = self._selector.select(self._individuals)

    def run(self):
        start_time = time()

        for i in range(self._max_generations):
            self._next_generation()
            if self._verbose:
                print("Generation:", i + 1, "| Fitness:",
                      round(self._individuals[0].score),
                      "(%ss.)" % round(time() - start_time))
                start_time = time()

    def best(self):
        return self._individuals[0]
示例#29
0
 def generateBusTrip(self, trip):
     fitness = Fitness()
     db = DB()
     line = 0
     count = 0
     chromosome = []
     for tripInstance in trip:
         for busInstance in tripInstance[3]:
             if line != busInstance["line"] and count != 0:
                 chromosome.append([
                     line, capacity,
                     self.calculateFrequency(count), startTime
                 ])
                 count = 0
             if count == 0:
                 capacity = busInstance["capacity"]
                 startTime = busInstance["startTime"]
             line = busInstance["line"]
             count += 1
     chromosome.append(
         [line, capacity,
          self.calculateFrequency(count), startTime])
     individual = fitness.genTimetable(chromosome)
     db.insertBusTrip2(individual)
示例#30
0
    def gera_Mutacao(self, Frase):                 # Método para gerar mutação no filhos
        listaTmp = []
        listaFin = []
        listaFinal = []
        TX_Mut_A = round(random.random())          # Número aleatorio entre 0 e 1
        for x in self.lista_Filho:
            
            if(TX_Mut_A  <= self.TX_Mutac):       # Se o número aleatorio for menor e igual que taxa de mutação, o indivíduo sofre a mutação em 2 duas posições aleatorias
                x1 = random.randint(0, self.NUM_CROM-1)  # x1 = valor de posição aleatoria
                x2 = random.randint(0, self.NUM_CROM-1)  # x2 = valor de posição aleatoria
                I = Individuo(self.Caract)               # instancia clase indivíduo
                x[x1] = I.get_caracter()                 # Modifica o caracter na posição x1 por um novo caracter na mesma posição
                x[x2] = I.get_caracter()                 # Modifica o caracter na posição x2 por um novo caracter na mesma posição
                F =  Fitness(Frase, self.NUM_CROM)       # Recalcula o Fitness
                listaTmp.append(F.Calc_Fitness(x))
            else:                                        # Caso a condição não seja aceita
                listaTmp.append(x)                       # Adicione o indivíduo na lista sem alteração

        print('Mutação nos Filhos')                      # imprimi os filhos com ou sem mutação
        for y in listaTmp:
            print(y)

        for z in self.lista_Selec:                      # Adiciona os filhos e pais dentro de uma lista
            listaFin.append(z)
        for z in listaTmp:
            listaFin.append(z)

        listaFin.sort(key=lambda x: x[self.NUM_CROM]) # Ordena a lista de pais e filhos
        for x in range(self.TAM_Pop, len(listaFin)):  # gera uma lista com o melhor dos pais e filhos
            listaFinal.append(listaFin[x])

        print('Nova População')                       # imprimi a lista com os melhores
        for y in listaFinal:
            print(y)

        return listaFinal                             # retorna a lista com nova população
示例#31
0
    def greadyRandomizedConstruction(self):
        student_yes = np.matmul(
            recommendation.astype(int), objectives.astype(int)
        )  #quantos alunos receberam o material E o tem como objetivo
        student_no = np.matmul(
            recommendation.astype(int), (~objectives).astype(int)
        )  #quantos alunos receberam o material E não o tem como objetivo
        student_difference = student_no - student_yes  #(quantos alunos querem ter o conveito adicionado) - (quantos alunos querem ter o conceito removido)
        scaled_coverage = (concept_coverage * 2 - 1
                           )  # concept_coverage, onde False é -1 e True é 1
        conflicts = student_difference * scaled_coverage
        change_potential = np.maximum(0, conflicts).sum(axis=1)

        materials_changed = []
        new_concept_coverage = concept_coverage.copy()
        change_potential_order = np.argsort(-change_potential).tolist()

        for j in range(int(self.max_materials_changes * num_materials)):
            # Select a material and remove from the list
            selected_material_index = random.randrange(
                int(len(change_potential_order) * self.alpha_m))
            material = change_potential_order[selected_material_index]
            materials_changed.append(material)
            del change_potential_order[selected_material_index]

            # print('[', material, change_potential[material], ']')
            # print(conflicts[material])

            conflicts_order = np.argsort(-conflicts[material]).tolist()
            for k in range(int(self.max_concepts_changes * num_concepts)):
                # Select a concept from the material and remove from the list
                selected_concept_index = random.randrange(
                    int(len(conflicts_order) * self.alpha_c))
                concept = conflicts_order[selected_concept_index]
                del conflicts_order[selected_concept_index]

                # print(material, concept)
                if conflicts[material, concept] > 0:
                    new_concept_coverage[
                        material,
                        concept] = ~new_concept_coverage[material, concept]

        new_best_fitness = sum([
            Fitness.get_fitnessConcepts(student_id, new_concept_coverage.T)
            for student_id in range(num_students)
        ]) / num_students
        return new_concept_coverage, new_best_fitness, materials_changed
示例#32
0
def calculate_average_fitness(tfitnesses, log_path):
    Avalue = 0
    Au_sell = 0
    Au_buy = 0
    Anoop = 0
    Arealised_profit = 0
    Amdd = 0
    Aret = 0
    Awealth = 0
    Ano_of_transactions = 0
    n_runs = len(tfitnesses)
    """
        Calculates an average fitness and logs it to file
    """
    for f in tfitnesses:
        Avalue += tfitnesses[f].value
        Au_sell += tfitnesses[f].u_sell
        Au_buy += tfitnesses[f].u_buy
        Anoop += tfitnesses[f].noop
        Arealised_profit += tfitnesses[f].realised_profit
        Amdd += tfitnesses[f].mdd
        Aret += tfitnesses[f].ret
        Awealth += tfitnesses[f].wealth
        Ano_of_transactions += tfitnesses[f].no_of_transactions

    Af = Fitness(value=Avalue / n_runs,
                 u_sell=Au_sell / n_runs,
                 u_buy=Au_buy / n_runs,
                 noop=Anoop / n_runs,
                 realised_profit=Arealised_profit / n_runs,
                 mdd=Amdd / n_runs,
                 ret=Aret / n_runs,
                 wealth=Awealth / n_runs,
                 no_of_transactions=Ano_of_transactions / n_runs)

    open(log_path + 'results.txt', 'w').close()
    with open(log_path + 'results.txt', 'a') as f:
        f.write(
            "file\tnumber of runs\tavg wealth\tavg return\tavg value\tavg profit\tavg mdd\tavg transactions\tavg short transactions\n"
        )
        f.write("%s\t%d\t%s" % (log_path, n_runs, Af))
    pickle.dump(Af.__dict__,
                open(log_path + "pickles/average_fitness.pickle", "wb"))
示例#33
0
    def inferBestCMu(self, samples, currentGraph):
        #import threading
        import time
        start_time = time.time()
        fitness = Fitness()
        threads = []
        #can we run the method for each sample in parallel? This would speed up the process by a lot. THe samples are not dependent on each other!
        for sampleInd in range(
                1, len(samples)):  #Skip the first 'dummy' precursor sample
            self.inferBestCMuPerSample(samples, sampleInd, currentGraph,
                                       fitness)
            #t = threading.Thread(target=self.inferBestCMuPerSample, args=[samples,sampleInd,currentGraph, fitness])
            #threads.append(t)
            #t.start()
        #for thread in threads:
        #	thread.join()

        #After we have inferred the best C and mu for each sample, we can update the best C and mu in the samples.
        for sample in range(0, len(samples)):

            samples[sample].originalCMu = samples[sample].bestCMu
            if samples[sample].bestCMu is None:
                measurementLength = len(samples[0].measurements.measurements)
                samples[sample].Mu = Mu(0)  #assume 100% tumor
                #Set a default bestCMu in this case, we don't know the solution.
                print "sample ", sample, " setting CMu to 2"
                samples[sample].bestCMu = [
                    CMuCombination(C([2, 2]), Mu(0), self.eventDistances)
                ] * measurementLength
            else:
                if samples[sample].bestCMu[0] is not None:
                    print "setting mu to: ", samples[sample].bestCMu[
                        0].mu.mu, " in sample: ", samples[sample].name
                    samples[sample].Mu = samples[sample].bestCMu[0].mu
                else:  #without a successfully inferred C and mu the sample is so complex it is most likely 100% tumor or contains a lot of subclones.
                    print sample, " Assuming 100% tumor"

                    samples[sample].Mu = Mu(0)  #assume 100% tumor

        print("--- %s seconds for all samples of 1 patient ---" %
              (time.time() - start_time))
        return samples
示例#34
0
    def __init__(self, app_list, pe_list):
        # about app
        self.app_list = app_list
        self.layer_list = [l for app in app_list for l in app.layer_list]
        self.pe_list = pe_list
        self.num_app = len(app_list)
        self.num_layer = len(self.layer_list)
        self.num_pe = len(pe_list)

        # about scheduling
        self.optimistic_cost_table = list()
        # for speed up
        self.optimistic_cost_hash = dict()
        self.processor_available_time_list = [0] * self.num_pe
        self.mapped_layers_per_pe = [[] for _ in range(self.num_pe)]
        self.fitness = Fitness(app_list, pe_list)
        self.mappings = list()
        self.target_range_divider = 5
        # XXX: generate maximum 1+n (= initial + moving_coverate) mappings
        self.moving_coverage = 2
        self.interference_fortify = 2
示例#35
0
文件: GA.py 项目: alojzije/GA_NN
def main():
    parser = argparse.ArgumentParser(description='Tweak GA parameters')
    parser.add_argument('-size','--populationSize', type=int, required=False, default=100,
                        help = 'Desired population size (int)')
    parser.add_argument('-iter','--maxIter',        type=int, required=False, default=100,
                        help = "Max number of iterations allowed (int)")
    parser.add_argument('-n','--n',                 type=int, required=False, default=10,
                        help = 'Desired number of neural_networks in the hidden layer')
    parser.add_argument('-k','--K',                 type=float, required=False, default=1.1,
                        help = "Chromosome is mutated by adding a number from the normal_distibution(0,K) to it's weights value")
    parser.add_argument('-err','--errThreshold',    type=float, required=False, default=0.1,
                        help = "Algorithm stops search if it has found a chromosome with error less than errThreshold")
    parser.add_argument('-train','--trainSet',      type=str, required=False, default="learningSet/train-set.txt",
                        help = "Path to training_set")
    #parser.add_argument('-test','--testSet',        type=str, required=False, default="learningSet/test-set.txt",
    #                    help = "Path to test_set")

    args = parser.parse_args()
    ERR_THRESHOLD = args.errThreshold
    VEL_POP  = args.populationSize
    MAX_ITER = args.maxIter
    N = args.n
    K = args.K

    train_set = parseLearningSet(args.trainSet)

    ## initialize needed operators
    fitnessOp  = Fitness(train_set)
    mutationOp = Mutation(K, N, VEL_POP)

    ##initialize population
    P = Population(N, VEL_POP)

    ##returns best neural_network (individual)
    best_nn = run_GA(P, fitnessOp, mutationOp, VEL_POP, MAX_ITER, ERR_THRESHOLD)
    test_set  = [] # parseLearningSet(args.testSet)
    test_dict = {} #parseLearningDict(args.testSet)

    writeOut(best_nn, test_set, test_dict)
示例#36
0
 def __results__(self):
     fitness = dict(
         map(lambda x: (x, Fitness(self.population[x])), self.population))
     fitness_global = dict(
         map(
             lambda x: (x, {
                 "makespan_glob": [
                     round(max(fitness[x].makespan), 2),
                     round(min(fitness[x].makespan), 2)
                 ],
                 "energyCons_glob": [
                     round(max(fitness[x].energyCons), 2),
                     round(min(fitness[x].energyCons), 2)
                 ],
                 "bt_makespan_energyCons": [
                     round(
                         fitness[x].makespan[np.argmin(fitness[
                             x].makespan + fitness[x].makespan)], 2),
                     round(
                         fitness[x].energyCons[np.argmin(fitness[
                             x].makespan + fitness[x].energyCons)], 2)
                 ]
             }), fitness))
     pprint(fitness_global)
示例#37
0
    def geraCruzamento(self, Frase):  # Método para gera os filhos
        x1 = 4  # Ponto de corte 1
        x2 = 9  # Ponto de corte 2
        x3 = 14  # Ponto de corte 3
        cnt = 0
        listTmp = []
        while (
                len(listTmp) < self.Tamanho_Populacao
        ):  # lopp. Enquanto o tamanho da lista filhos for menor que tamanho da população
            ind = self.populacao[
                cnt]  # Variável 'ind' recebe o primeiro indivíduo
            p1 = ind[:x1]  # corta o indivíduo em 3 pontos
            p2 = ind[x1:x2]
            p3 = ind[x2:x3]  #

            cnt += 1
            ind = self.populacao[
                cnt]  # Variável 'ind' recebe o segundo indivíduo
            p4 = ind[0:x1]  # corta o indivíduo em 3 pontos
            p5 = ind[x1:x2]
            p6 = ind[x2:x3]  #

            t1 = p1 + p5 + p3  # Produz um novo indivíduo(filho) com as partes cortadas
            t2 = p4 + p2 + p6  # Produz um novo indivíduo(filho) com as partes cortadas
            t1.append(0)  # Adiciona o valor 0 do fitness ao individuo 1
            t2.append(0)  # Adiciona o valor 0 do fitness ao individuo 2

            F = Fitness(Frase,
                        self.numCrom)  # Calcula o fitness dos indivíduos
            listTmp.append(
                F.Calc_Fitness(t1))  # Adiciona o indivíduo na lista de filhos
            F = Fitness(Frase,
                        self.numCrom)  # Calcula o fitness dos indivíduos
            listTmp.append(
                F.Calc_Fitness(t2))  # Adiciona o indivíduo na lista de filhos
            # repete o procedimento com mais dois individuos
        print("filhos")  # imprimi a lista de filhos
        for i in listTmp:
            print(i)
        return listTmp
示例#38
0
 def testTimeDiffNeg(self):
     fit = Fitness()
     self.assertEqual(fit.timeDiff('08:00', '08:01'), timedelta(minutes=-1))
示例#39
0
 def testTimeDiffEq(self):
     fit = Fitness()
     self.assertEqual(fit.timeDiff('00:00', '00:00'), timedelta(hours=0, minutes=0))
示例#40
0
 def testTimeDiffPos(self):
     fit = Fitness()
     self.assertEqual(fit.timeDiff('23:59', '00:00'), timedelta(hours=23, minutes=59))
                    type=float,
                    help='Final temperature')
    ap.add_argument('-a', '--alpha', type=float, default=0.90, help='alpha')
    ap.add_argument('-b', '--beta', type=str, default=0.2, help='beta')
    ap.add_argument('--datfile',
                    dest='datfile',
                    type=str,
                    help='File where it will be save the score (result)')

    args = ap.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    logging.debug(args)

    student_results_before = sum([
        Fitness.get_fitnessConcepts(student_id, concept_coverage.T)
        for student_id in range(num_students)
    ]) / num_students

    simulatedAnnealing = SimulatedAnnealing(args.max_iterations, args.cycle,
                                            args.initial_temperature,
                                            args.final_temperature, args.alpha,
                                            args.beta, 0.0356, 0.1667,
                                            98092891)

    simulatedAnnealing.run(concept_coverage, student_results_before,
                           args.datfile)
    # annealing_concept_coverage, student_results_annealing = simulatedAnnealing.run(concept_coverage, student_results_before)
    # print(f'student_results_annealing: {student_results_annealing}')