Beispiel #1
0
    def test_mutate_population(self):

        continuous_solver = ContinuousGenAlgSolver(
            fitness_function=lambda x: x.sum(),
            n_genes=4,
            pop_size=5,
            random_state=42)

        population = continuous_solver.initialize_population()

        expected_mutated_population = np.array([
            [-2.50919762, -6.88010959, -9.58831011, -6.3319098],
            [9.01428613, -8.83832776, 9.39819704, -3.91515514],
            [4.63987884, 7.32352292, -8.04655772, 0.49512863],
            [1.97316968, 2.02230023, -5.75321779, 8.18640804],
            [-6.87962719, 9.31264066, -6.36350066, -4.1754172],
        ])

        mutated_population = continuous_solver.mutate_population(population, 5)

        print(mutated_population)

        assert np.allclose(mutated_population,
                           expected_mutated_population,
                           rtol=1e-5)
Beispiel #2
0
    def test_solve(
        self,
        mocker,
        mock_matplotlib,
        mock_logging,
        fitness_function,
        n_genes,
        expected_best_fitness,
        expected_best_individual,
    ):

        solver = ContinuousGenAlgSolver(
            n_genes,
            fitness_functions_continuous(fitness_function),
            pop_size=10,
            max_gen=2,
            mutation_rate=0.05,
            selection_rate=0.5,
            random_state=42,
        )

        solver.solve()

        assert np.allclose(solver.best_fitness_, expected_best_fitness, rtol=1)
        assert np.allclose(solver.best_individual_,
                           expected_best_individual,
                           rtol=1)
    def __init__(
        self,
        graph,
        mutation_strategy: str = "2-opt",
        n_searches: int = 1,
        numba_speedup: bool = False,
        *args,
        **kwargs,
    ):

        self.check_input(kwargs, graph)

        MutationStrategies.__init__(self, n_searches=n_searches)
        ContinuousGenAlgSolver.__init__(self,
                                        n_crossover_points=2,
                                        *args,
                                        **kwargs)

        if mutation_strategy not in allowed_mutations:
            raise (InvalidInput(
                f"{mutation_strategy} is an invalid mutation strategy"))

        if numba_speedup:

            edges_dict = convert_to_typed_dict(graph)

            self.fitness_function = lambda individual: fitness_function(
                individual, edges_dict)

        self.G = graph
        self.mutation_strategy = mutation_strategy
        self.fitness_time = 0
        self.chromosomes = defaultdict(int)
Beispiel #4
0
 def __init__(self, *args, **kwargs):
     self.demands = kwargs.pop('demands')
     self.supplies = kwargs.pop('supplies')
     self.inversion_mutation_rate = kwargs.pop('inversion_mutation_rate')
     self.displacement_mutation_rate = kwargs.pop('displacement_mutation_rate')
     self.cost = kwargs.pop('cost')
     BinaryGenAlgSolver.__init__(self, *args, **kwargs)
     ContinuousGenAlgSolver.__init__(self, *args, **kwargs)
Beispiel #5
0
    def test_initialize_population(self, problem_type, expected_result):

        continuous_solver = ContinuousGenAlgSolver(
            fitness_function=lambda x: x.sum(),
            n_genes=4,
            pop_size=5,
            problem_type=problem_type,
            random_state=42,
        )

        population = continuous_solver.initialize_population()

        assert np.allclose(population, expected_result, rtol=1e-05)
Beispiel #6
0
    def test_initialize_population_variable_limits(self, variables_limits,
                                                   problem_type):

        continuous_solver = ContinuousGenAlgSolver(
            fitness_function=lambda x: x.sum(),
            n_genes=4,
            pop_size=5,
            problem_type=problem_type,
            variables_limits=variables_limits,
            random_state=42,
        )

        population = continuous_solver.initialize_population()

        for i in range(population.shape[1]):
            assert population[:, i].min(
            ) > continuous_solver.variables_limits[i][0]
            assert population[:, i].max(
            ) < continuous_solver.variables_limits[i][1]
def genal_optim(p):
    global logger

    logger.optim_alg = 'gen'
    logger.run = str(int(logger.run) + 1)

    logger.pso_steps = ""
    logger.pso_n_particles = ""
    logger.pso_iters = ""

    logger.gen_pop_size = "25"
    logger.gen_mutation_rate = "0.1"
    logger.gen_selection_rate = "0.6"
    logger.gen_selection_strategy = "roulette_wheel"

    logger.field_x = "100"
    logger.field_y = "100"
    logger.n_bots = "10"
    logger.trail_decay = "100"

    logger.p_resource = str(p)
    logger.resource_dist_mean = "1"
    logger.resource_dist_std = "0"

    # for patching
    logger.is_selected = ''

    solver = ContinuousGenAlgSolver(n_genes=2,
                                    fitness_function=genal_fitness(p),
                                    pop_size=25,
                                    mutation_rate=0.1,
                                    selection_rate=0.6,
                                    selection_strategy="roulette_wheel",
                                    problem_type=float,
                                    variables_limits=(0, 1),
                                    verbose=True,
                                    show_stats=True,
                                    plot_results=True)
    solver.solve()
Beispiel #8
0
    def test_create_offspring(self, crossover_pt, expected_first_offspring,
                              expected_second_offspring):

        continuous_solver = ContinuousGenAlgSolver(
            fitness_function=lambda x: x.sum(),
            n_genes=4,
            pop_size=5,
            random_state=42)

        first_parent = np.array([1, -3, 5, 0])
        sec_parent = np.array([2, 2, -4, 0])

        first_offspring = continuous_solver.create_offspring(
            first_parent, sec_parent, crossover_pt, "first")

        second_offspring = continuous_solver.create_offspring(
            sec_parent, first_parent, crossover_pt, "second")

        assert np.allclose(first_offspring,
                           expected_first_offspring,
                           rtol=1e-5)
        assert np.allclose(second_offspring,
                           expected_second_offspring,
                           rtol=1e-5)
Beispiel #9
0
 def __init__(self, *args, **kwargs):
     BinaryGenAlgSolver.__init__(self, *args, **kwargs)
     ContinuousGenAlgSolver.__init__(self, *args, **kwargs)