def setUp(self):
        """Test Problem: Assume you can only carry 3 items to sell in your bag.
        Pick a combination of items that maximises your profit. The profit for
        each item is listed.
        """
        self.seed_data = [('apple', 15), ('banana', 10), ('carrot', 12),
                          ('pear', 5), ('mango', 8)]

        member_1 = pyeasyga.Chromosome([0, 1, 0, 1, 1])
        member_2 = pyeasyga.Chromosome([1, 1, 0, 0, 1])
        member_3 = pyeasyga.Chromosome([1, 1, 1, 1, 0])
        member_4 = pyeasyga.Chromosome([0, 1, 1, 1, 1])

        self.population = []
        self.population.append(member_1)
        self.population.append(member_2)
        self.population.append(member_3)
        self.population.append(member_4)

        self.ga = pyeasyga.GeneticAlgorithm(self.seed_data)
        self.ga.population_size = 10
        self.ga.generations = 10

        self.ga.fitness_function = lambda member, data: sum([
            profit for (selected, (fruit, profit)) in zip(member, data)
            if selected and member.count(1) == 3
        ])

        self.ga.selection_function = self.ga.tournament_selection
Exemple #2
0
def task1(data):

    ga = pyeasyga.GeneticAlgorithm(data)
    ga.population_size = POPULATION_SIZE

    def fitness(individual, data):
        weight, volume, price = 0, 0, 0
        for (selected, item) in zip(individual, data):
            if selected:
                weight += item[0]
                volume += item[1]
                price += item[2]
        if weight > max_weight or volume > max_volume:
            price = 0
        return price

    ga.fitness_function = fitness
    ga.run()
    result = ga.best_individual()
    items = []
    for i in range(0, len(result[1])):
        if result[1][i] == 1:
            items.append(i + 1)
    real_volume = 0
    real_weight = 0
    for i in range(0, len(items)):
        real_volume += data[items[i] - 1][1]
        real_weight += data[items[i] - 1][0]
    j = dict(value=result[0],
             weight=real_weight,
             volume=real_volume,
             items=items)
    return j
Exemple #3
0
def runGen():
    data=readInput.things
    ga = pyeasyga.GeneticAlgorithm(data)        # initialise the GA with data
    ga.population_size = 200                    # increase population size to 200 (default value is 50)
    ga.fitness_function = fitness  # set the GA's fitness function
    ga.run()  # run the GA
    return ga.best_individual()  # print the GA's best solution
Exemple #4
0
def main():
    # maze: 0 - sciana, 1 - wolna sciezka.
    maze = [(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
            (0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0),
            (0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0),
            (0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0),
            (0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0),
            (0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0),
            (0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0),
            (0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0),
            (0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0),
            (0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0),
            (0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0),
            (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)]
    ga = pyeasyga.GeneticAlgorithm(maze,
                                   population_size=300,
                                   generations=200,
                                   crossover_probability=0.8,
                                   mutation_probability=0.1,
                                   elitism=True,
                                   maximise_fitness=False)
    ga.create_individual = generate_chrom
    ga.fitness_function = fitness_type_1
    ga.mutate_function = mutate
    ga.run()
    best_1 = ga.best_individual()

    ga.fitness_function = fitness_type_2
    ga.run()
    best_2 = ga.best_individual()

    print("Najlepszy wynik dla funkcji fitness 1:")
    print(best_1)
    print("Najlepszy wynik dla funkcji fitness 2:")
    print(best_2)
Exemple #5
0
def run_single_experiment(graph_manager, beta, generations, population_size, mutation_rate=1, crossover_rate=0.8,
                          verbose=False):
    """Run a single experiment with the provided parameters. Returns whether or not optimality was reached"""
    global evaluations
    evaluations = 0
    global fast_mutation_operator
    global mask

    data = [graph_manager]
    parameter_count = data[0].n

    fast_mutation_operator = FastMutationOperator(parameter_count, beta=beta)
    mask_percent = get_mask_percent(get_relative_neighbours(graph_manager.n, graph_manager.raw_edges))
    mask = get_mask(mask_percent)
    ga = pyeasyga.GeneticAlgorithm(data,
                                   population_size=population_size,
                                   generations=generations,
                                   crossover_probability=crossover_rate,
                                   mutation_probability=mutation_rate,
                                   elitism=True,
                                   maximise_fitness=True)
    ga.fitness_function = fitness
    ga.create_individual = create_individual
    ga.mutate_function = mutate_individual
    ga.run(graph_manager.bkv)

    best_fitness, best_individual = ga.best_individual()

    if verbose:
        print("(", best_fitness, "/", graph_manager.bkv, ")", "eval", evaluations, end=' ')
    return best_fitness == graph_manager.bkv
Exemple #6
0
    def geneticFit(self, pretrained = False):
        data = self.training_set

        ga = pyeasyga.GeneticAlgorithm(data,
                               population_size=self.pop_size,
                               generations=self.num_generations,
                               crossover_probability=0.0,
                               mutation_probability=0.5,
                               elitism=False,
                               maximise_fitness=True)

        ga.create_individual = self.create_individual
        ga.fitness_function = self.fitness
        ga.mutate_function = self.mutate
        ga.crossover_function = self.crossover

        ga.run()

        print("Best individual is: ")
        print(ga.best_individual()[1].layer_dimensions)
        print("With performance: ", ga.best_individual()[1].evaluate(self.validation_set[0], self.validation_set[1]))
        print("Saving model...")

        BEST_PATH = './best_model.pth'
        torch.save(ga.best_individual()[1].state_dict(), BEST_PATH)

        return ga.best_individual()
Exemple #7
0
 def __init__(self,data,W,V):
     # инициализируем алгоритм данными
     self.ga=pyeasyga.GeneticAlgorithm(data)
     # устанавливаем популяцию равной 200
     self.ga.population_size = 200
     self.ga.fitness_function = self.fitness  # установка фитнес-функции
     self.MaxWeight=W
     self.MaxVolume=V
    def test_genetic_algorithm_initialisation_1(self):
        ''' Test default initialisation '''
        ga_1 = pyeasyga.GeneticAlgorithm(self.seed_data)

        assert ga_1.population_size == 50
        assert ga_1.generations == 100
        assert ga_1.elitism is True
        assert ga_1.crossover_probability == 0.8
        assert ga_1.mutation_probability == 0.2
 def genetic_algorithm(self, population, generation, crossover, mutation):
     self.initial_data = self.initialize_population()
     ga = pyeasyga.GeneticAlgorithm(seed_data=self.initial_data,
                                    population_size=population,
                                    generations=generation,
                                    crossover_probability=crossover,
                                    mutation_probability=mutation,
                                    elitism=True,
                                    maximise_fitness=True)
     ga.create_individual = self.create_individual
     ga.fitness_function = self.fitness_function
     return ga
Exemple #10
0
def start_lib_ga():
    def get_data(path: str = 'data.txt'):
        """Чтение из файла и построчная запись в lines"""
        f = open(path)
        lines = [line.strip() for line in f]
        f.close()
        """Создание пустого словаря и переменной-итератора"""
        resultTotal = {}
        result = []
        first = True
        """Запись в словарь всех данных"""
        for i in lines:
            item = i.split(' ', -1)
            if (first):
                resultTotal['maxWeight'] = int(item[0])
                resultTotal['maxVolume'] = float(item[1])
                first = False
                continue

            elem = (int(item[0]), float(item[1]), int(item[2]))
            result.extend([elem])

        resultTotal['items'] = result
        return resultTotal

    """Получение и приведение данных к стандартизиированному в бибилиотеке виду"""
    data = get_data()
    bag = {'weight': data['maxWeight'], 'volume': data['maxVolume']}
    items = data['items']
    """Начальные условия"""
    ga = pyeasyga.GeneticAlgorithm(items)
    ga.population_size = 200
    """ Фитнес-фукнция определяет насколько жизнеспособна и эволюционно перспективна особь
        определяется прямой суммой стоимостей входящих в рюкзак вещей"""

    def fitness(individual, data):
        weight, volume, price = 0, 0, 0
        for (selected, item) in zip(individual, data):
            if selected:
                weight += item[0]
                volume += item[1]
                price += item[2]
        if weight > bag['weight'] or volume > bag['volume']:
            price = 0

        #print("W: " + str(weight) + "; V: " + str(volume) + "; P: " + str(price))
        return price

    """Запуск генетического алгоритма"""
    ga.fitness_function = fitness
    ga.run()

    return ga.best_individual()
def run_gen(option, pop_size=50, gens=1000):
    genetic_alg = ps.GeneticAlgorithm(
        option,
        population_size=pop_size,
        generations=gens,
        mutation_probability=0.7,
        elitism=True,
        maximise_fitness=OPTIONS[option[0]].MAXIMIZE_FITNESS)
    genetic_alg.create_individual = create_individual
    genetic_alg.fitness_function = fitness
    genetic_alg.mutate_function = mutate
    genetic_alg.crossover_function = crossover
    return genetic_alg
Exemple #12
0
def initialize_ga(graph, generations):
    ga = pyga.GeneticAlgorithm(graph,
                               generations=generations,
                               population_size=800,
                               crossover_probability=0.8,
                               mutation_probability=0.40,
                               elitism=True,
                               maximise_fitness=False)
    ga.create_individual = create_individual
    ga.fitness_function = fitness_function
    ga.crossover_function = crossover_function
    ga.mutate_function = mutate_function
    ga.selection_function = selection_function
    return ga
Exemple #13
0
 def solve(self, items: Sequence) -> Sequence[bool]:
     from pyeasyga import pyeasyga
     if len(items) <= 0:
         return []
     elif len(items) == 1:
         return [self.score(items) > 0]
     # TODO sometimes this leads to error
     ga = pyeasyga.GeneticAlgorithm(list(items))
     ga.fitness_function = self.fitness
     ga.run()
     max_score, selected = ga.best_individual()
     flowsaber.context.logger.debug(
         f"score: {max_score} selected: {selected}")
     return selected
Exemple #14
0
 def solve(self,
           generations=_GENERATIONS,
           population_size=_POPULATION_SIZE):
     """
     Solve backpack problem with pyeasyga genetic library
     https://github.com/remiomosowon/pyeasyga
     """
     ga = pyeasyga.GeneticAlgorithm(self.data,
                                    population_size=population_size,
                                    generations=generations,
                                    maximise_fitness=True)
     ga.fitness_function = self.fitness
     ga.run()
     return ga.best_individual()[1]
Exemple #15
0
def giveBestFitnessValue(maze, strt, end, l, type):
    global start, finish, length
    if type not in range(1, 4):
        return [0, 0]
    start = strt[:]
    finish = end[:]
    length = l
    if type == 1:
        ga = pyeasyga.GeneticAlgorithm(maze,
                                       population_size=300,
                                       generations=200,
                                       crossover_probability=0.8,
                                       mutation_probability=0.2,
                                       elitism=True,
                                       maximise_fitness=False)
        ga.create_individual = generate_chrom
        ga.fitness_function = fitness_type_1
        ga.mutate_function = mutate
        ga.run()
        best = ga.best_individual()
        return best
    elif type == 2:
        ga = pyeasyga.GeneticAlgorithm(maze,
                                       population_size=300,
                                       generations=200,
                                       crossover_probability=0.8,
                                       mutation_probability=0.1,
                                       elitism=True,
                                       maximise_fitness=False)
        ga.create_individual = generate_chrom
        ga.fitness_function = fitness_type_2
        ga.mutate_function = mutate
        ga.run()
        best = ga.best_individual()
        return best
    elif type == 3:
        return [1, 1]
Exemple #16
0
def run_ga(data: [str], population_size: int, generations: int,
           crossover_proba: float, mutation_proba: float,
           elitism: bool) -> [str]:
    ga = pyeasyga.GeneticAlgorithm(data, population_size, generations,
                                   crossover_proba, mutation_proba, elitism)

    ga.create_individual = create_individual
    ga.crossover_function = one_point_crossover
    ga.mutate_function = simple_mutation
    ga.selection_function = roulette_wheel_selector
    ga.fitness_function = fitness

    random.seed()
    ga.run()
    return ga.best_individual()
Exemple #17
0
def main():
    if TEST == 1:
        tmmf_params_df, tmmf_range_params_df = init_tmmf_dfs()
        arbi = arbitrator.arbitrator(tmmf_params_df, tmmf_range_params_df)
        trade_final_result_df = pd.DataFrame(columns=(
            'week_num', 'is_trade', 'a_start', 'a_end', 'profit', 'hold_profit', 'trade_profit', 'as_start', 'as_end',
            'ad_start', 'ad_end', 'ap_start',
            'ap_end', 'trade_s_d', 'trade_s_p', 'trade_d_s', 'trade_d_p', 'trade_p_s', 'trade_p_d'))
        for t, _ in zip(range(len(delta_test_df)), delta_test_df.iterrows()):
            if t < len(delta_test_df) - 1:
                trade_final_result_df.loc[t] = arbi.arbitrate(delta_test_df, forecast_test_df, t,
                                                              trade_final_result_df.iloc[t - 1] if t > 0 else None,
                                                              ALL_HOLD)

        trade_final_result_df.to_csv("trade_final_result.csv", index=False, sep=',')
    else:
        tmmf_params_df, tmmf_range_params_df = init_tmmf_dfs()
        data = np.append(tmmf_params_df.T.values.flatten(), tmmf_range_params_df.T.values.flatten()).tolist()
        ga = pyeasyga.GeneticAlgorithm(data,
                                       population_size=50,
                                       generations=50,
                                       crossover_probability=0.1,
                                       mutation_probability=0.9,
                                       elitism=True,
                                       maximise_fitness=True)
        ga.fitness_function = fitness
        ga.create_individual = create_individual
        ga.run()
        print(ga.best_individual())

        # ===get the best individual and fit in test
        individual_chrom = ga.best_individual()
        idmf_params_df, idmf_range_df = get_mfdf_from_data(individual_chrom[1])

        arbi = arbitrator.arbitrator(conv_paramdf_key(idmf_params_df), conv_rangedf_key(idmf_range_df))
        trade_final_result_df = pd.DataFrame(columns=(
            'week_num', 'is_trade', 'a_start', 'a_end', 'profit', 'hold_profit', 'trade_profit', 'as_start', 'as_end',
            'ad_start', 'ad_end', 'ap_start',
            'ap_end', 'trade_s_d', 'trade_s_p', 'trade_d_s', 'trade_d_p', 'trade_p_s', 'trade_p_d'))
        for t, _ in tqdm(zip(range(len(delta_test_df)), delta_test_df.iterrows())):
            if t < len(delta_test_df) - 1:
                trade_final_result_df.loc[t] = arbi.arbitrate(delta_test_df, forecast_test_df, t,
                                                              trade_final_result_df.iloc[t - 1] if t > 0 else None,
                                                              ALL_HOLD)

        trade_final_result_df.to_csv("trade_ga_result.csv", index=False, sep=',')

    return
def start_training(end_callback):
    global user_ratings, create_individual, crossover, mutate, fitness, max_generations, ga, c
    ga = pyeasyga.GeneticAlgorithm(user_ratings,
                                   population_size=c[0],
                                   generations=max_generations,
                                   crossover_probability=c[1],
                                   mutation_probability=1.0,
                                   elitism=False,
                                   maximise_fitness=True)
    ga.create_individual = create_individual
    ga.crossover_function = crossover
    ga.mutate_function = mutate
    ga.fitness_function = fitness
    # we could also define a custom selection function

    ga.run()
    end_callback()
Exemple #19
0
    def geneticFit(self, pretrained=False):
        data = self.trainloader

        print("Training default network")

        PATH = './cifar_net.pth'
        net = DefaultNet()

        # ifnotdef, train model, else use pretrained model
        if (not pretrained or (not os.path.isfile(PATH))):
            train(net, self.trainloader, num_epochs=10, verbose=True)
            torch.save(net.state_dict(), PATH)
        else:  #load model back in
            net.load_state_dict(torch.load(PATH))

        computePerformance(net, self.validationloader)
        print("Base training complete")
        data = [net]

        ga = pyeasyga.GeneticAlgorithm(data,
                                       population_size=self.pop_size,
                                       generations=self.num_generations,
                                       crossover_probability=0.8,
                                       mutation_probability=0.05,
                                       elitism=True,
                                       maximise_fitness=True)

        ga.create_individual = self.create_individual
        ga.fitness_function = self.fitness
        ga.mutate_function = self.mutate
        ga.crossover_function = self.crossover

        ga.run()

        print("Best individual is: ")
        print(ga.best_individual()[1].layers)
        print(
            "With performance: ",
            computePerformance(ga.best_individual()[1], self.validationloader))
        print("Saving model...")

        BEST_PATH = './best_model.pth'
        torch.save(ga.best_individual()[1].state_dict(), BEST_PATH)

        return ga.best_individual()
Exemple #20
0
    def run_ga(self):

        seed_data = [0.00, 0.00, 0.00]
        ga = pyeasyga.GeneticAlgorithm(
            seed_data,
            population_size=1000,
            generations=5,
            crossover_probability=0.8,
            mutation_probability=0.05,
            elitism=True,
            maximise_fitness=False)  # initialise the GA with data

        ga.create_individual = self.create_individual
        ga.fitness_function = self.fitness  # set the GA's fitness function
        ga.run()  # run the GA

        #print(ga.best_individual())  # print the GA's best solution
        return (ga.best_individual())
    def test_genetic_algorithm_initialisation_2(self):
        ''' Test initialisation with specific values '''
        ga_2 = pyeasyga.GeneticAlgorithm(self.seed_data,
                                         population_size=235,
                                         generations=57,
                                         crossover_probability=0.9,
                                         mutation_probability=0.05)
        ga_2.elitism = False
        ga_2.maximise_fitness = False
        fruit, profit = ga_2.seed_data[1]

        assert len(ga_2.seed_data) == 5
        assert (fruit, profit) == ('banana', 10)
        assert ga_2.population_size == 235
        assert ga_2.generations == 57
        assert ga_2.elitism is False
        assert ga_2.maximise_fitness is False
        assert ga_2.crossover_probability == 0.9
        assert ga_2.mutation_probability == 0.05
Exemple #22
0
def SAD():
    if tailleMatriceColis < 5:

        solution_sac = SadExact()
        print "exacte : ", solution_sac

    else:
        for i in range(1, tailleMatriceColis + 1):
            indice = i
            tempon = {'value': donneejson["colis" + str(indice)][0], 'volume': donneejson["colis" + str(indice)][1]}
            data_genetique_sac.append(tempon)
        #print data_genetique_sac

        ga = pyeasyga.GeneticAlgorithm(data_genetique_sac)  # initialise the GA with data
        ga.fitness_function = SadHeuristique  # set the GA's fitness function
        ga.run()  # run the GA
        solution_sac = ga.best_individual()[1]

        print "genetique : ", solution_sac

    return solution_sac
Exemple #23
0
def AGFunction(data,mw,mv):
    MAX_WEIGHT = mw
    MAX_VOLUME = mv
    ga = pyeasyga.GeneticAlgorithm(data)  # intitialiser l'AG avec les données
    ga.population_size = 200  # Taille de la population a 200 chromosomes
    print("wei")
    print(MAX_WEIGHT)
    def fitness(individual, data):
        weight, volume, priority = 0, 0, 0
        for (selected, item) in zip(individual, data):
            if selected:
                weight += item[0]
                volume += item[1]
                priority += item[2]
        if weight > MAX_WEIGHT or volume > MAX_VOLUME:
            priority = 0
        return priority

    ga.fitness_function = fitness  # set the GA's fitness function
    ga.run()  # run the GA
    return ga.best_individual()
Exemple #24
0
def calculate(usb_size, memes):
    """

    :param usb_size: int - capacity of usb stick in GiB
    :param memes: List[Tuple[str, int, int]] - list of 3-element tuples, each with the name, size in MiB , and price
    :return: - Tuple[int, set] a tuple with the first element being the value of the most expensive set of memes
    and the second being the set of names of the memes that should be copied
    onto the USB stick to maximize its value.
    """
    usb_size *= 1024
    memes = list(set(memes))

    def fitness(individual, data):
        """

        :param individual: list - a candidate solution
        :param data: dict of 3-element dict, each with the name, size in MiB, and price
        :return: tuple - first element being int value of the most expensive set of memes and
        the second being the list with used element
        """
        values, weights = 0, 0
        for selected, box in zip(individual, data):
            if selected:
                values += box.get('price')
                weights += box.get('size')
        if weights > usb_size:
            values = 0
        return values

    x = [{
        'name': memes[i][0],
        'price': memes[i][2],
        'size': memes[i][1]
    } for i in range(len(memes))]
    ga = pyeasyga.GeneticAlgorithm(x)
    ga.fitness_function = fitness
    ga.run()
    return ga.best_individual()[0], set(
        [memes[x][0] for x, v in enumerate(ga.best_individual()[1]) if v == 1])
Exemple #25
0
def genetic_algorithm_scheduling(data,
                                 counter,
                                 pop_size=100,
                                 num_generations=500):
    start_time = time()
    ga = pyeasyga.GeneticAlgorithm(
        data,
        maximise_fitness=False,
        population_size=pop_size,
        generations=num_generations,
        mutation_probability=0.3)  # initialization of the algorithm
    ga.create_individual = create_individual
    ga.mutate_function = mutate
    ga.fitness_function = fitness
    ga.run()
    best_individual = ga.best_individual()
    steps.append(best_individual)
    best_fitness = best_individual[0]
    if best_fitness > 1000 and counter < 10:
        counter += 1
        new_generations = num_generations + 100
        print("Incrementing generations to ", new_generations, "......")
        genetic_algorithm_scheduling(data, counter, pop_size, new_generations)
    elif best_fitness > 1000 and counter == 10:
        print("Feasible individual wasn't found!")
        print("Best infeasible individual: ", ga.best_individual())
        end_time = time()
        print("The execution time was: ", (end_time - start_time), " seconds")
    elif best_fitness < 1000:
        end_time = time()
        print("Best feasible individual found! ", ga.best_individual())
        print("The execution time was: ", (end_time - start_time), " seconds")
        print("These were the different best individuals:")
        for i in range(0, len(steps)):
            print(steps[i])
        return steps
def run_ga(data):
    """Run the genetic algorithm generation and search process and returns the final solution of timings
    """
    ga = pyeasyga.GeneticAlgorithm(data,
                                   population_size=100,
                                   generations=200,
                                   crossover_probability=0.8,
                                   mutation_probability=0.05,
                                   elitism=True,
                                   maximise_fitness=False)

    ga.create_individual = create_individual

    ga.fitness_function = fitness
    ga.run()
    result = ga.best_individual()

    t1 = result[1][0]
    t2 = result[1][1]
    t3 = result[1][2]
    t4 = result[1][3]

    print(result)
    return (t1, t2, t3, t4)
    def __init__(self, data, droneSpeed, windSpeed, windDir, populationsize,
                 generations):

        self.ga = pyeasyga.GeneticAlgorithm(data,
                                            population_size=populationsize,
                                            generations=generations,
                                            crossover_probability=0.9,
                                            mutation_probability=0.05,
                                            elitism=True,
                                            maximise_fitness=False)

        self.data = data

        self.bearingFinder = bearing.BearingFinder()
        self.e6b = E6B.E6B()

        #Get wind data
        self.windDir = windDir
        self.windSpeed = windSpeed
        #Get drone speed
        self.droneSpeed = droneSpeed

        self.maximise_fitness = False
        self.tournament_size = populationsize // 10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug  8 10:04:46 2018

@author: prasad
"""

from pyeasyga import pyeasyga

data = [('pear', 50), ('apple', 35), ('banana', 40)]
ga = pyeasyga.GeneticAlgorithm(data)


def fitness(individual, data):
    fitness = 0
    if individual.count(1) == 2:
        for (selected, (fruit, profit)) in zip(individual, data):
            if selected:
                fitness += profit
    return fitness


ga.fitness_function = fitness
ga.run()
print(ga.best_individual())
    'weight': 1
}, {
    'name': 'box3',
    'value': 10,
    'weight': 4
}, {
    'name': 'box4',
    'value': 1,
    'weight': 1
}, {
    'name': 'box5',
    'value': 2,
    'weight': 2
}]

ga = pyeasyga.GeneticAlgorithm(data)  # initialise the GA with data


# define a fitness function
def fitness(individual, data):
    values, weights = 0, 0
    for selected, box in zip(individual, data):
        if selected:
            values += box.get('value')
            weights += box.get('weight')
    if weights > 15:
        values = 0
    return values


ga.fitness_function = fitness  # set the GA's fitness function
Exemple #30
0
from pyeasyga import pyeasyga
import random

data = [("A", 20), ("B", 50), ("C", 75), ("D", 25), ("E", 25), ("F", 78)]

ga = pyeasyga.GeneticAlgorithm(data, 8, 100, 0.9, 0.8, True, True)


def create_individual(data):
    return [random.randint(-1, 1) for _ in range(len(data))]


ga.create_individual = create_individual


def fitness(individual, data):
    fn = 0
    auxCounter = 0
    goal = 125
    sm = 0

    for (selected, (_, profit)) in zip(individual, data):
        if selected == 1:
            sm += profit
        elif selected == -1:
            sm -= profit
            #auxCounter +=1
    fn = 1 / (abs(goal - sm) + 0.01)
    #fn -= auxCounter*2
    return fn