def __mutateAddNode(self): # Loop through connections connection_gene = choice(self.connection_genes.values()) into = self.node_genes[connection_gene.into] out = self.node_genes[connection_gene.out] # If difference in node levels is greater than 1, add node with chance in random level between diff = into.level - out.level if diff > 1: #print "New node between %s and %s" % (connection_gene.out, connection_gene.into) # Disable connection gene connection_gene.disabled = True # Create new node in random level between new_node = NodeGene() new_node.level = randint(out.level+1, into.level-1) self.addNode(new_node) # Create two new connection genes connecting new node new_conn1 = ConnectionGene() new_conn1.into = into.innovation new_conn1.out = new_node.innovation new_conn1.weight = 1.0 new_conn2 = ConnectionGene() new_conn2.into = new_node.innovation new_conn2.out = out.innovation new_conn2.weight = connection_gene.weight self.addConnection(new_conn1) self.addConnection(new_conn2) else: self.__mutateAddNode()
def init(self, n_inputs, n_outputs): Organism.n_threshold = (n_inputs+1)*n_outputs + n_inputs + n_outputs + 1 + 4 print "n_threshold: %s" % Organism.n_threshold # Create initial population base = Organism(self.options['levels']) # Create input NodeGenes for i in range(0, n_inputs): node = NodeGene() node.level = 1 base.addNode(node) # Create bias node node = NodeGene() node.level = 1 node.value = 2.0 base.addNode(node) # Create output NodeGenes for i in range(0, n_outputs): node = NodeGene() node.level = self.options['levels'] base.addNode(node) # Create connections between all inputs and outputs for j in range(0, n_inputs+1): connection_gene = ConnectionGene() connection_gene.out = j + 1 connection_gene.into = node.innovation connection_gene.weight = 0.0 base.addConnection(connection_gene) # Mutate base to create population for i in range(0, self.options['pop_size']): new_organism = deepcopy(base) new_organism.mutate() new_organism.id = Organism.organism_id Organism.organism_id += 1 #base = new_organism self.addOrganism(new_organism)