Beispiel #1
0
    def mutate_gene(self, genome, p_add, p_delete):
        """
        Mutate only a single gene.
        """

        if p_add < 0 or p_delete < 0:
            raise Exception("Mutation parameters must not be negative.")

        if p_add + p_delete > 1:
            raise Exception("Sum of the mutation probabilities must be less than 1.")

        mutated_individual = BehaviorTreeStringRepresentation([])
        max_attempts = 100
        attempts = 0
        while (not mutated_individual.is_valid() or mutated_individual.bt == genome) and attempts < max_attempts:
            mutated_individual.set(genome)
            index = random.randint(0, len(genome) - 1)
            mutation = random.random()

            if mutation < p_delete:
                mutated_individual.delete_node(index)
            elif mutation < p_delete + p_add:
                mutated_individual.add_node(index)
            else:
                mutated_individual.change_node(index)

            mutated_individual.close()
            mutated_individual.trim()
            attempts += 1

        if attempts >= max_attempts and (not mutated_individual.is_valid() or mutated_individual.bt == genome):
            mutated_individual = BehaviorTreeStringRepresentation([])

        return mutated_individual.bt
    def test_trim(self):
        """ Tests trim function """

        btsr = BehaviorTreeStringRepresentation([])

        btsr.set(
            ['s(', 'a0', 'f(', 'a0', 'a0', ')', 'a0', 's(', 'a0', ')', ')'])
        btsr.trim()
        self.assertEqual(btsr.bt,
                         ['s(', 'a0', 'f(', 'a0', 'a0', ')', 'a0', 'a0', ')'])

        btsr.set(['s(', 'a0', 'f(', ')', 'a0', 's(', 'a0', ')', ')'])
        btsr.trim()
        self.assertEqual(btsr.bt, ['s(', 'a0', 'a0', 'a0', ')'])

        btsr.set(
            ['s(', 'a0', 'f(', 'a1', 's(', 'a2', ')', 'a3', ')', 'a4', ')'])
        btsr.trim()
        self.assertEqual(btsr.bt,
                         ['s(', 'a0', 'f(', 'a1', 'a2', 'a3', ')', 'a4', ')'])

        btsr.set(['s(', 'a0', 'f(', 's(', 'a2', 'a3', ')', ')', 'a4', ')'])
        btsr.trim()
        self.assertEqual(btsr.bt, ['s(', 'a0', 'a2', 'a3', 'a4', ')'])

        btsr.set(['s(', 'a0', ')'])
        btsr.trim()
        self.assertEqual(btsr.bt, ['s(', 'a0', ')'])