예제 #1
0
    def setUp(self):
        self.sut = None
        self.randomizer = Randomizer(Random())
        self.cyk_configuration = CykConfiguration.create(
            should_correct_grammar=False,
            terminal_chance=0,
            universal_chance=0,
            aggressive_chance=0,
            starting_chance=0,
            full_chance=0
        )

        self.rule_adding = AddingRuleSupervisor.default(self.randomizer)

        self.grammar_sentence = self.create_sentence(
            Symbol('she'),
            Symbol('eats'),
            Symbol('a'),
            Symbol('fish'),
            Symbol('with'),
            Symbol('a'),
            Symbol('fork'))

        self.service_creator = None
        self.statistics = None
예제 #2
0
 def __init__(self, randomizer, run_no, cyk_service_variant=None):
     self.cyk_service_variant = cyk_service_variant if cyk_service_variant is not None \
         else CykServiceVariationManager(False)
     self.randomizer = randomizer
     self.configuration = None
     self.rule_adding = AddingRuleSupervisor.default(randomizer)
     self.grammar_estimator = None
     self.induction = self.cyk_service_variant.create_cyk_service(randomizer, self.rule_adding)
     self.evolution = EvolutionService(randomizer)
     self.stop_criteria = [NoStopCriteriaSpecified()]
     self.run_no = run_no
예제 #3
0
    def create_rule_adding(self):
        configuration = AddingRulesConfiguration.create(
            crowding_factor=2,
            crowding_size=3,
            elitism_size=2,
            max_non_terminal_rules=19
        )

        adding_strategies = [SimpleAddingRuleStrategy(),
                             AddingRuleWithCrowdingStrategy(),
                             AddingRuleWithElitismStrategy()]

        self.rule_adding = AddingRuleSupervisor(self.randomizer, configuration, adding_strategies)
예제 #4
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.expanding_strategy_mock = create_autospec(AddingRuleStrategy)
        self.expanding_strategy_mock.is_applicable.side_effect = \
            lambda x: x == AddingRuleStrategyHint.expand_population

        self.controlling_strategy_mock = create_autospec(AddingRuleStrategy)
        self.controlling_strategy_mock.is_applicable.side_effect = \
            lambda x: x == AddingRuleStrategyHint.control_population_size

        self.sut = AddingRuleSupervisor(
            self.randomizer_mock, self.configuration_mock, [self.expanding_strategy_mock,
                                                            self.controlling_strategy_mock])
        self.sut.strategies = [self.expanding_strategy_mock, self.controlling_strategy_mock]

        self.max_symbols = 24
        self.rule_population_mock.configure_mock(max_non_terminal_rules=self.max_symbols)
        self.rule_population_mock.get_all_non_terminal_rules.return_value = range(5)
예제 #5
0
class TestAddingRuleSupervisor(TestAddingRuleStrategyCommon):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.expanding_strategy_mock = create_autospec(AddingRuleStrategy)
        self.expanding_strategy_mock.is_applicable.side_effect = \
            lambda x: x == AddingRuleStrategyHint.expand_population

        self.controlling_strategy_mock = create_autospec(AddingRuleStrategy)
        self.controlling_strategy_mock.is_applicable.side_effect = \
            lambda x: x == AddingRuleStrategyHint.control_population_size

        self.sut = AddingRuleSupervisor(
            self.randomizer_mock, self.configuration_mock, [self.expanding_strategy_mock,
                                                            self.controlling_strategy_mock])
        self.sut.strategies = [self.expanding_strategy_mock, self.controlling_strategy_mock]

        self.max_symbols = 24
        self.rule_population_mock.configure_mock(max_non_terminal_rules=self.max_symbols)
        self.rule_population_mock.get_all_non_terminal_rules.return_value = range(5)

    def test_valid_rule_strategies_should_be_used(self):
        # Given:
        self.sut.add_rule(self.rule, self.rule_population_mock, self.statistics_mock)
        self.expanding_strategy_mock.apply.assert_called_once_with(
            self.sut, self.statistics_mock, self.rule, self.rule_population_mock)

        # When:
        self.sut.add_rule(self.rule, self.rule_population_mock, self.statistics_mock,
                          AddingRuleStrategyHint.control_population_size)

        # Then:
        self.controlling_strategy_mock.apply.assert_called_once_with(
            self.sut, self.statistics_mock, self.rule, self.rule_population_mock)

    def test_given_population_size_exceeded_crowding_should_be_used(self):
        # Given:
        self.rule_population_mock.get_all_non_terminal_rules.return_value = range(self.max_symbols)

        # When:
        self.sut.add_rule(self.rule, self.rule_population_mock, self.statistics_mock,
                          AddingRuleStrategyHint.expand_population)

        # Then:
        assert_that(not self.expanding_strategy_mock.apply.called)
        self.controlling_strategy_mock.apply.assert_called_once_with(
            self.sut, self.statistics_mock, self.rule, self.rule_population_mock)
예제 #6
0
class TestEvolution(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.randomizer = Randomizer(Random())

        selector_configuration = [
            EvolutionRandomSelectorConfiguration.create(),
            EvolutionRouletteSelectorConfiguration.create()
        ]
        self.configuration = EvolutionConfiguration.create(
            selector_configuration, inversion_chance=0, mutation_chance=0, crossover_chance=0)
        self.create_rule_population()
        self.create_grammar_statistics()
        self.create_rule_adding()

        self.sut = EvolutionService(self.randomizer)

        self.rules = [
            Rule(Symbol('S'), Symbol('NP'), Symbol('VP')),
            Rule(Symbol('VP'), Symbol('VP'), Symbol('PP')),
            Rule(Symbol('VP'), Symbol('V'), Symbol('NP')),
            TerminalRule(Symbol('VP'), Symbol('eats')),
            Rule(Symbol('PP'), Symbol('P'), Symbol('NP')),
            Rule(Symbol('NP'), Symbol('Det'), Symbol('N')),
            TerminalRule(Symbol('NP'), Symbol('she')), TerminalRule(Symbol('V'), Symbol('eats')),
            TerminalRule(Symbol('P'), Symbol('with')), TerminalRule(Symbol('N'), Symbol('fish')),
            TerminalRule(Symbol('N'), Symbol('fork')), TerminalRule(Symbol('Det'), Symbol('a'))
        ]

    def create_rule_population(self):
        self.starting_symbol = Symbol('S')
        self.rule_population = RulePopulation(self.starting_symbol)

    def create_grammar_statistics(self):
        configuration = ClassicalStatisticsConfiguration.default()
        configuration.base_fitness = 5
        configuration.classical_fitness_weight = 1
        configuration.fertility_weight = 1
        configuration.positive_weight = 1
        configuration.negative_weight = 1

        self.grammar_statistics = GrammarStatistics(
            configuration, self.randomizer, ClassicRuleStatistics(),
            ClassicFitness())

    def create_rule_adding(self):
        configuration = AddingRulesConfiguration.create(
            crowding_factor=2,
            crowding_size=3,
            elitism_size=2,
            max_non_terminal_rules=19
        )

        adding_strategies = [SimpleAddingRuleStrategy(),
                             AddingRuleWithCrowdingStrategy(),
                             AddingRuleWithElitismStrategy()]

        self.rule_adding = AddingRuleSupervisor(self.randomizer, configuration, adding_strategies)

    def simulate_induction_part_work(self, rules):
        for rule in rules:
            self.rule_adding.add_rule(rule, self.rule_population, self.grammar_statistics)

        for rule in rules:
            rule_usage_info = ClassicRuleUsageInfo(True, 1)
            positive_usages = self.randomizer.randint(1, 4)
            for _ in range(positive_usages):
                self.grammar_statistics.on_rule_usage(rule, rule_usage_info)

            rule_usage_info.positive_sentence = False
            self.grammar_statistics.on_rule_usage(rule, rule_usage_info)

            self.grammar_statistics.fitness.get(self.grammar_statistics, rule)

    def get_symbols_from_rules(self, rules):
        return {y for y in chain.from_iterable(
            (x.parent, x.left_child, x.right_child) for x in rules)}

    def assert_contains_rules(self, rules, rules_pool):
        for rule in rules:
            assert_that(rules_pool, has_item(rule))

    def count_rules_that_has_changed(self, old):
        changed_rules = 0
        for rule in self.rule_population.get_all_non_terminal_rules():
            changed_rules += 1 if rule not in old else 0
        return changed_rules

    def test_given_no_operator_used_rule_population_should_remain_unchanged(self):
        # Given:
        self.simulate_induction_part_work(self.rules)

        old_population = copy.deepcopy(self.rule_population)

        # When:
        self.sut.run_genetic_algorithm(self.grammar_statistics, self.rule_population,
                                       self.rule_adding, self.configuration)

        # Then:
        self.assert_contains_rules(self.rule_population.get_all_non_terminal_rules(),
                                   list(old_population.get_all_non_terminal_rules()))

        old_symbols = self.get_symbols_from_rules(old_population.get_all_non_terminal_rules())
        new_symbols = self.get_symbols_from_rules(self.rule_population.get_all_non_terminal_rules())
        assert_that(old_symbols, has_items(*new_symbols))

    def promote_those_rules_to_elite(self, rules):
        for rule in rules:
            rule_usage_info = ClassicRuleUsageInfo(True, 1)
            positive_usages = 5
            for _ in range(positive_usages):
                self.grammar_statistics.on_rule_usage(rule, rule_usage_info)

    def test_given_high_operator_usage_rule_population_should_expect_some_major_change(self):
        # Given:
        self.configuration.operators.inversion.chance = 1
        self.configuration.operators.mutation.chance = 1
        self.configuration.operators.crossover.chance = 1

        self.simulate_induction_part_work(self.rules)
        self.promote_those_rules_to_elite(self.rules[0:2])

        elite = list(self.rules[0:2])

        old_population = copy.deepcopy(self.rule_population)

        # When:
        self.sut.run_genetic_algorithm(self.grammar_statistics, self.rule_population,
                                       self.rule_adding, self.configuration)

        # Then:
        self.assert_contains_rules(elite, list(old_population.get_all_non_terminal_rules()))

        assert_that(self.count_rules_that_has_changed(old_population.get_all_non_terminal_rules()),
                    is_(greater_than_or_equal_to(2)))

        old_symbols = self.get_symbols_from_rules(old_population.get_all_non_terminal_rules())
        new_symbols = self.get_symbols_from_rules(self.rule_population.get_all_non_terminal_rules())
        assert_that(old_symbols, not_(has_items(*new_symbols)))