def test_parse_bnf_string(self, bnf_string): hypothesis.assume(bnf_string != "") _bnf_string = bnf_string["bnf_string"] terminals = bnf_string["terminals"] terminals = [_.strip() for _ in terminals] non_terminals = bnf_string["non_terminals"] rules = bnf_string["rules"] gramm = grammar.Grammar("") gramm.parse_bnf_string(_bnf_string) self.assertEqual(gramm.start_rule[0], non_terminals[0]) self.assertEqual( len(gramm.non_terminals), len(non_terminals), "%s != %s" % (gramm.non_terminals, non_terminals), ) # TODO generate terminals so all generated terminals are # present in bnf_string for terminal in gramm.terminals: try: self.assertIn(terminal, terminals, "%s not in %s" % (terminal, terminals)) except AssertionError: # When parsing terminals two or more subsequent # terminals can be parsed as one. Therefore we need to # check if the terminals exist in this terminal # TODO generate better terminals... matches = [_ for _ in terminals if _ in terminal] self.assertGreaterEqual(len(matches), 1) self.assertEqual(len(gramm.rules), len(rules))
def test_read_bnf_file(self): """Non hypothesis test, since we want to check known files... TODO write """ _dir = "tests/grammars/" files = os.listdir(_dir) for _file in files: if _file.endswith(".bnf"): path = os.path.join(_dir, _file) gramm = grammar.Grammar(path) gramm.read_bnf_file(gramm.file_name)
def test_search_loop(self, param): hypothesis.assume(param["tournament_size"] <= param["population_size"]) hypothesis.assume(param["elite_size"] < param["population_size"]) # TODO too much setup, can it be refactored... fitness_function = ge_run.get_fitness_function( param["fitness_function"]) gramm = grammar.Grammar(param["bnf_grammar"]) gramm.read_bnf_file(gramm.file_name) population.Individual.codon_size = param["codon_size"] population.Individual.max_length = param["max_length"] individuals = ge_helpers.initialise_population( param["population_size"]) pop = population.Population(fitness_function, gramm, individuals) try: _individual = ge_helpers.search_loop(pop, param) self.assertIsNotNone(_individual.phenotype) except ValueError as e: self.assertEqual("Phenotype is None", str(e))
def _get_grammar(n_non_terminals, n_terminals): gramm = grammar.Grammar("") bnf_string = write_rule_str(n_non_terminals, n_terminals) gramm.parse_bnf_string(bnf_string["bnf_string"]) return gramm
def run(param: Dict[str, Any]) -> Dict[str, hpop.Individual]: """ Return the best solution. Create an initial population. Perform an evolutionary search. :param param: parameters for pony gp :type param: dict :returns: Best solution """ start_time = time.time() coev = param["coev"] spatial = param["spatial"] # Set random seed if not 0 is passed in as the seed if "seed" not in param.keys(): param["seed"] = int(time.time()) random.seed(param["seed"]) print("Setting random seed: {} {:.5f}".format(param["seed"], random.random())) # convert elite proportion to elite number if "elite_prop" in [*param]: param["elite_size"] = math.floor(param["population_size"] * param["elite_prop"]) # Print settings print("ge_run settings:", param) assert param["population_size"] > 1 assert param["generations"] > 0 assert param["max_length"] > 0 assert param["integer_input_element_max"] > 0 assert param["seed"] > -1 assert param["tournament_size"] <= param["population_size"] assert param["elite_size"] < param["population_size"] assert 0.0 <= param["crossover_probability"] <= 1.0 assert 0.0 <= param["mutation_probability"] <= 1.0 ########################### # Create Population + Evolutionary search ########################### if coev: populations: OrderedDict[str, Any] = OrderedDict() # pylint: disable=unsubscriptable-object for key in param["populations"].keys(): p_dict = param["populations"][key] grammar = hgrammar.Grammar(p_dict["bnf_grammar"]) grammar.read_bnf_file(grammar.file_name) fitness_function = get_fitness_function(p_dict["fitness_function"]) adversary = p_dict["adversary"] hpop.Individual.max_length = param["max_length"] hpop.Individual.codon_size = param["integer_input_element_max"] individuals = hhelp.initialise_population(param["population_size"]) population_coev = hpop.CoevPopulation(fitness_function, grammar, adversary, key, individuals) populations[key] = population_coev best_overall_solution_coev = hhelp.search_loop_coevolution( populations, param) # Display results print("Time: {:.3f} Best solution:{}".format( time.time() - start_time, best_overall_solution_coev)) return best_overall_solution_coev grammar = hgrammar.Grammar(param["bnf_grammar"]) grammar.read_bnf_file(grammar.file_name) fitness_function = get_fitness_function(param["fitness_function"]) hpop.Individual.max_length = param["max_length"] hpop.Individual.codon_size = param["integer_input_element_max"] if spatial: graph = hhelp.build_graph_from_file(param["graph_file"]) individuals = hhelp.initialise_population(len(graph)) populated_graph = hpop.PopulatedGraph( graph, None, fitness_function, grammar, individuals, ) best_overall_solution = hhelp.search_loop_spatial( populated_graph, param) else: individuals = hhelp.initialise_population(param["population_size"]) population = hpop.Population(fitness_function, grammar, individuals) best_overall_solution = hhelp.search_loop(population, param) # Display results print("Time: {:.3f} Best solution:{}".format(time.time() - start_time, best_overall_solution)) return {"best": best_overall_solution}