def test_adjust_to_interval(var, expected): ga = RealGA(fitness_test_sin_func) ga.interval = (-3, 5) try: assert ga._adjust_to_interval(var) == expected except ValueError: result_arr = ga._adjust_to_interval(var) == expected assert result_arr.all()
def test_generate_random_population(size, dim, interval): ga = RealGA(fitness_test_linear_func) population = ga._generate_random_population(size, dim, interval) res_arr0 = population >= interval[0] res_arr1 = population < interval[1] assert len(population) == size assert len(population[0]) == dim assert res_arr0.all() assert res_arr1.all()
def test_invert_bit(num, bit_num): ga = RealGA(fitness_test_sin_func, mut_prob=1) ga.interval = (num - 1, num + 32) original_bstr = BitArray(floatbe=num, length=ga._bin_length).bin mutant = ga._invert_bit(num, bit_num) result_bstr = BitArray(floatbe=mutant, length=ga._bin_length).bin diff = sum(1 for i in range(ga._bin_length) if result_bstr[i] != original_bstr[i] and i in bit_num) assert diff == len(bit_num)
def test_valid_replace_bits(num, start, stop, bit_idx, count): ga = RealGA(fitness_test_sin_func, cross_prob=1) ga.interval = (-numpy.inf, numpy.inf) source_bstr = BitArray(floatbe=num, length=ga._bin_length).bin new_chromosome = ga._replace_bits(num, 0, start, stop) actual_bstr = BitArray(floatbe=new_chromosome, length=ga._bin_length).bin for i in bit_idx: assert actual_bstr[i] == source_bstr[i] assert actual_bstr.count('1') == count
def test_valid_init_populations(optim): mga = MigrationGA(type='real') rga1 = RealGA(fitness_test_sin_func, optim=optim) rga2 = RealGA(fitness_test_sin_func, optim=optim) size1, size2, dim, interval = 10, 5, 1, (-5, 5) rga1.init_random_population(size1, dim, interval) rga2.init_random_population(size2, dim, interval) mga.init_populations([rga1, rga2]) assert mga._ga_list_size == 2 assert len(mga._ga_list) == 2 assert mga._optim == optim assert mga._min_elements == size2 assert len(mga._ga_list[0].population) == size1 assert len(mga._ga_list[1].population) == size2 for rind1, rind2, mind1, mind2 in \ zip(rga1.population, rga2.population, mga._ga_list[0].population, mga._ga_list[1].population): assert rind1.chromosome == mind1.chromosome assert rind2.chromosome == mind2.chromosome assert rind1.fitness_val == mind1.fitness_val assert rind2.fitness_val == mind2.fitness_val
def test_valid_run(optim): mga = MigrationGA(type='real') rga1 = RealGA(fitness_test_linear_func, optim=optim) rga2 = RealGA(fitness_test_linear_func, optim=optim) rga1.init_population(test_chrom_part1, (0, 100)) rga2.init_population(test_chrom_part2, (0, 100)) old_best1 = rga1.best_solution old_best2 = rga2.best_solution mga.init_populations([rga1, rga2]) fitness_progress, best_solution = mga.run(10, 5, 1, True) assert len(fitness_progress) == 2 assert len(fitness_progress[0]) == 11 assert len(fitness_progress[1]) == 11 if optim == 'min': assert best_solution[1] <= old_best1[1] assert best_solution[1] <= old_best2[1] else: assert best_solution[1] >= old_best1[1] assert best_solution[1] >= old_best2[1]
def test_invalid_init_population(): optim = 'min' chromosomes = list(test_real_chromosomes) expected_population = [] for chromosome in chromosomes: expected_population.append(IndividualGA(chromosome, fitness_test_sin_func(chromosome))) expected_population = sort_population(optim, expected_population) ga = RealGA(fitness_test_sin_func, optim=optim) interval = (10, 4) with pytest.raises(ValueError): ga.init_population(test_real_chromosomes, interval)
def test_init_random_population_real(optim, type): size, dim, interval = 9, 1, (-5, 5) if type == 'real': ga = RealGA(fitness_test_linear_func, optim=optim) dga = DiffusionGA(ga) dga.init_random_population(size, dim, interval) else: ga = BinaryGA(test_bin_data, fitness_test_func, optim=optim) dga = DiffusionGA(ga) dga.init_random_population(size) assert dga.population[0].size == size assert dga.population[1].size == size shape = dga.population[0].shape if optim == 'max': for row in range(shape[0]): for column in range(shape[1]): assert dga.population[1][row][column] <= dga.best_solution[1] else: for row in range(shape[0]): for column in range(shape[1]): assert dga.population[1][row][column] >= dga.best_solution[1]
def test_invalid_init_population(): optim = 'min' chromosomes = list(test_real_chromosomes) expected_population = [] for chromosome in chromosomes: expected_population.append( IndividualGA(chromosome, fitness_test_sin_func(chromosome))) expected_population = sort_population(optim, expected_population) ga = RealGA(fitness_test_sin_func, optim=optim) interval = (10, 4) with pytest.raises(ValueError): ga.init_population(test_real_chromosomes, interval)
def test_init_random_population(optim): ga = RealGA(fitness_test_linear_func, optim=optim) size, dim, interval = 3, 1, (-5, 5) ga.init_random_population(size, dim, interval) assert len(ga.population) == size assert ga.population[size - 1].fitness_val == ga.best_solution[1] assert ga.population[size - 1].chromosome == ga.best_solution[0] if optim == 'max': for i in range(size - 1): assert ga.population[i].fitness_val <= ga.best_solution[1] assert ga.population[0].fitness_val <= ga.population[i].fitness_val else: for i in range(size - 1): assert ga.population[i].fitness_val >= ga.best_solution[1] assert ga.population[0].fitness_val >= ga.population[i].fitness_val
def test_valid_run(optim): """ "Run" function is the same for both types of GA: RealGA and Binary GA and thus, it is not necessary to test it twice. """ ga = RealGA(fitness_test_sin_func, optim=optim) ga.init_random_population(15, 1, (-5, 5)) init_best = ga.best_solution generations = 10 fitness_progress = ga.run(generations) assert len(fitness_progress) == generations + 1 if optim == 'min': assert init_best[1] >= ga.best_solution[1] else: assert init_best[1] <= ga.best_solution[1]
def test_invalid_run(max_generation, period, migrant_num, cloning, migrate): mga = MigrationGA(type='real') rga1 = RealGA(fitness_test_linear_func) rga2 = RealGA(fitness_test_linear_func) size1, size2, dim, interval = 10, 5, 1, (-5, 5) rga1.init_random_population(size1, dim, interval) rga2.init_random_population(size2, dim, interval) mga.init_populations([rga1, rga2]) with pytest.raises(ValueError): mga.run(max_generation, period, migrant_num, cloning, migrate)
def test_valid_init_population(optim): chromosomes = list(test_real_chromosomes) expected_population = [] for chromosome in chromosomes: expected_population.append(IndividualGA(chromosome, fitness_test_sin_func(chromosome))) expected_population = sort_population(optim, expected_population) ga = RealGA(fitness_test_sin_func, optim=optim) interval = (-10, 10) ga.init_population(test_real_chromosomes, interval) assert ga.interval == interval best_solution = ga.best_solution if optim == 'min': assert test_real_best_min_ind[0] == best_solution[0] else: assert test_real_best_max_ind[0] == best_solution[0] for actual, expected in zip(ga.population, expected_population): assert actual.chromosome == expected.chromosome
def test_valid_find_critical_values(optim, arr, rmin, rmax): ga = RealGA(fitness_test_sin_func, optim=optim) dga = DiffusionGA(ga) arr = numpy.array(arr) coords_best, coords_worst = dga._find_critical_values(arr) if optim == 'min': assert arr[coords_best] == rmin assert arr[coords_worst] == rmax else: assert arr[coords_best] == rmax assert arr[coords_worst] == rmin
def test_valid_init_population(optim): chromosomes = list(test_real_chromosomes) expected_population = [] for chromosome in chromosomes: expected_population.append( IndividualGA(chromosome, fitness_test_sin_func(chromosome))) expected_population = sort_population(optim, expected_population) ga = RealGA(fitness_test_sin_func, optim=optim) interval = (-10, 10) ga.init_population(test_real_chromosomes, interval) assert ga.interval == interval best_solution = ga.best_solution if optim == 'min': assert test_real_best_min_ind[0] == best_solution[0] else: assert test_real_best_max_ind[0] == best_solution[0] for actual, expected in zip(ga.population, expected_population): assert actual.chromosome == expected.chromosome
def test_compare_solutions(optim): mga = MigrationGA(type='real') rga1 = RealGA(fitness_test_linear_func, optim=optim) rga2 = RealGA(fitness_test_linear_func, optim=optim) rga1.init_population(test_chrom_part1, (1, 2)) rga2.init_population(test_chrom_part2, (1, 2)) mga.init_populations([rga1, rga2]) best_solution = mga._compare_solutions() if optim == 'min': best_chrom = min(test_chromosomes) else: best_chrom = max(test_chromosomes) assert best_solution[0] == best_chrom assert best_solution[1] == fitness_test_linear_func(best_chrom)
def test_get_neighbour(fit_list, row, column): ga = RealGA(fitness_test_sin_func) dga = DiffusionGA(ga) dga._chrom_arr = numpy.array(list(range(9))).reshape((3, 3)) dga._fitness_arr = numpy.array(fit_list).reshape(3, 3) shape = dga._chrom_arr.shape selected_chromosome = dga._get_neighbour(row, column) indices = numpy.where(dga._chrom_arr == selected_chromosome) coords = (indices[0][0], indices[1][0]) valid_indices = [((row - 1) % shape[0], column), ((row + 1) % shape[0], column), (row, (column - 1) % shape[1]), (row, (column + 1) % shape[1])] assert coords in valid_indices
def test_valid_run(optim): """ "Run" function is the same for both types of diffusion GA: RealGA and Binary GA and thus, it is not necessary to test it twice. """ ga = RealGA(fitness_test_sin_func, optim=optim) dga = DiffusionGA(ga) dga.init_random_population(11, 1, (-5, 5)) # size is 11 but actually wil be 9 (truncated square root from 11) init_best = dga.best_solution generations = 10 fitness_progress = dga.run(generations) assert len(fitness_progress) == generations + 1 if optim == 'min': assert init_best[1] >= dga.best_solution[1] else: assert init_best[1] <= dga.best_solution[1]
def test_valid_init_population(optim): """ This test includes testing of the following parts: *init_population()*, *_init_diffusion_model()*, *_construct_diffusion_model()* and *best_solution*. """ ga = RealGA(fitness_test_linear_func, optim=optim) dga = DiffusionGA(ga) array_side = 3 population = list(range(array_side * array_side)) fitness = [fitness_test_linear_func(chrom) for chrom in population] dga.init_population(population) for elem, fit in zip(population, fitness): assert elem in dga._chrom_arr assert fit in dga._fitness_arr if optim == 'min': assert dga.best_solution[0] == min(population) assert dga.best_solution[1] == fitness_test_linear_func(min(population)) else: assert dga.best_solution[0] == max(population) assert dga.best_solution[1] == fitness_test_linear_func(max(population))
def test_valid_get_chromosome_return_value(chromosome, expected): ga = RealGA(fitness_test_sin_func) assert expected == ga._get_chromosome_return_value(chromosome)
def test_invalid_get_chromosome_return_value(chromosome): ga = RealGA(fitness_test_sin_func) with pytest.raises(ValueError): ga._get_chromosome_return_value(chromosome)
def test_invalid_replace_bits(start, stop): ga = RealGA(fitness_test_sin_func) with pytest.raises(ValueError): ga._replace_bits(1, 0, start, stop)
dga.init_population(population) for elem, fit in zip(population, fitness): assert elem in dga._chrom_arr assert fit in dga._fitness_arr if optim == 'min': assert dga.best_solution[0] == min(population) assert dga.best_solution[1] == fitness_test_linear_func(min(population)) else: assert dga.best_solution[0] == max(population) assert dga.best_solution[1] == fitness_test_linear_func(max(population)) @pytest.mark.parametrize(['size', 'dim', 'interval', 'ga_inst'], [(10, None, None, RealGA(fitness_test_linear_func)), (None, None, None, RealGA(fitness_test_linear_func)), (10, 3, None, RealGA(fitness_test_linear_func)), (None, None, None, BinaryGA([1,2,3,4], fitness_test_linear_func)) ]) def test_invalid_init_random_population(size, dim, interval, ga_inst): with pytest.raises(ValueError): DiffusionGA(ga_inst).init_random_population(size, dim, interval) @pytest.mark.parametrize('optim', ('min', 'max')) @pytest.mark.parametrize('type', ('real', 'binary')) def test_init_random_population_real(optim, type): size, dim, interval = 9, 1, (-5, 5) if type == 'real':
def test_compute_fitness(chromosome): ga = RealGA(fitness_test_linear_func) assert ga._compute_fitness(chromosome) == 2 * chromosome # 2*x is linear test function
def test_is_chromosome_list(): ga = RealGA(fitness_test_sin_func) assert not ga._is_chromosome_list(5) assert ga._is_chromosome_list([5]) assert ga._is_chromosome_list([1,2,3,4])
def test_valid_check_init_random_population(): size, dim, interval = 2, 3, (-5, 5) ga = RealGA(fitness_test_linear_func) ga._check_init_random_population(size, dim, interval)
def test_invalid_check_init_random_population(size, dim, interval): ga = RealGA(fitness_test_linear_func) with pytest.raises(ValueError): ga._check_init_random_population(size, dim, interval)
def test_compute_fitness(chromosome): ga = RealGA(fitness_test_linear_func) assert ga._compute_fitness( chromosome) == 2 * chromosome # 2*x is linear test function
def test_valid_get_mut_bit_offset(bin_length, result): ga = RealGA(fitness_test_sin_func) ga._bin_length = bin_length assert ga._get_mut_bit_offset() == result
def test_invalid_cross_type(): with pytest.raises(ValueError): RealGA(fitness_test_sin_func, cross_type=1000)
def test_invalid_bin_length(): ga = RealGA(fitness_test_sin_func) ga._bin_length = 128 with pytest.raises(ValueError): ga._check_parameters()
def test_invalid_get_mut_bit_offset(): ga = RealGA(fitness_test_sin_func) ga._bin_length = 128 with pytest.raises(ValueError): ga._get_mut_bit_offset()
elitism = True selection = "rank" tournament_size = None # in case of tournament selection mut_type = 1 mut_prob = 0.05 cross_type = 1 cross_prob = 0.95 optim = "min" # we need to minimize error interval = (-1, 1) len_vector_x = total_param #run GA sga = RealGA(func, optim=optim, elitism=elitism, selection=selection, mut_type=mut_type, mut_prob=mut_prob, cross_type=cross_type, cross_prob=cross_prob) sga.init_random_population(population_size, len_vector_x, interval) t2 = time.time() fitness_progress = sga.run(generation_num) t3 = time.time() print("Genetic Algorithms") print("Time taken to train the model: ", t3 - t2, "secs.") print("Error:", sga.best_solution[1]) print() print("***************************")
def test_is_chromosome_list(): ga = RealGA(fitness_test_sin_func) assert not ga._is_chromosome_list(5) assert ga._is_chromosome_list([5]) assert ga._is_chromosome_list([1, 2, 3, 4])
def test_invalid_run(generations): ga = RealGA(fitness_test_sin_func) with pytest.raises(ValueError): ga.run(generations)