def crossover_genome(self, genome1, genome2, replace): """ Do crossover between genomes at random points """ bt1 = BehaviorTreeStringRepresentation(genome1) bt2 = BehaviorTreeStringRepresentation(genome2) offspring1 = BehaviorTreeStringRepresentation([]) offspring2 = BehaviorTreeStringRepresentation([]) if bt1.is_valid() and bt2.is_valid(): max_attempts = 100 attempts = 0 found = False while not found and attempts < max_attempts: offspring1.set(bt1.bt) offspring2.set(bt2.bt) cop1 = -1 cop2 = -1 if len(genome1) == 1: cop1 = 0 # Change whole tree else: while not offspring1.is_subtree(cop1): cop1 = random.randint(1, len(genome1) - 1) if len(genome2) == 1: cop2 = 0 # Change whole tree else: while not offspring2.is_subtree(cop2): cop2 = random.randint(1, len(genome2) - 1) if replace: offspring1.swap_subtrees(offspring2, cop1, cop2) else: subtree1 = offspring1.get_subtree(cop1) subtree2 = offspring2.get_subtree(cop2) if len(genome1) == 1: index1 = random.randint(0, 1) else: index1 = random.randint(1, len(genome1) - 1) if len(genome2) == 1: index2 = random.randint(0, 1) else: index2 = random.randint(1, len(genome2) - 1) offspring1.insert_subtree(subtree2, index1) offspring2.insert_subtree(subtree1, index2) attempts += 1 if offspring1.is_valid() and offspring2.is_valid(): found = True if not found: offspring1.set([]) offspring2.set([]) return offspring1.bt, offspring2.bt
def test_get_subtree(self): """ Tests get_subtree function """ btsr = BehaviorTreeStringRepresentation( ['s(', 'a0', 'f(', 'a0', 'a0', ')', 'a0', ')']) subtree = btsr.get_subtree(1) self.assertEqual(subtree, ['a0']) btsr.set( ['s(', 'a0', 'f(', 'a0', 'a0', ')', 's(', 'a0', 'a0', ')', ')']) subtree = btsr.get_subtree(6) self.assertEqual(subtree, ['s(', 'a0', 'a0', ')']) btsr.set(['s(', 'a0', 'f(', 'a0', 'a0', ')', ')']) subtree = btsr.get_subtree(2) self.assertEqual(subtree, ['f(', 'a0', 'a0', ')']) subtree = btsr.get_subtree(5) self.assertEqual(subtree, [])