def test_connection_json(self): """Test whether a connection can be saved to and loaded from JSON.""" c = Connection(1, 0) out_file = json.dumps(c.to_json()) c_load = Connection.from_json(json.loads(out_file)) self.assertEqual(c, c_load) self.assertEqual(c.id, c_load.id) self.assertEqual(c.weight, c_load.weight)
class ConnectionGene(Gene): """Represents a connection gene.""" pool = {} def __init__(self, target_id=None, input_id=None): """Create a connection gene. Creates a empty connection gene if either target_id or input_id are set to None. Arguments: target_id: the id of the node that receives the input. input_id: the id of the node that provides the input. """ self.is_enabled = True if target_id is None or input_id is None: self.connection = None self.innovation_number = None return self.connection = Connection(target_id, input_id) try: self.innovation_number = ConnectionGene.pool[self.connection] except KeyError: self.innovation_number = len(ConnectionGene.pool) + 1 ConnectionGene.pool[self.connection] = self.innovation_number def copy(self): """Make a copy of this gene. Returns: the copy of this gene. """ copy = ConnectionGene() copy.connection = self.connection.copy() copy.is_enabled = self.is_enabled copy.innovation_number = self.innovation_number return copy @property def alignment_key(self): return self.innovation_number @property def weight(self): return self.connection.weight @weight.setter def weight(self, value): self.connection.weight = value def combine_by_average(self, other): new_gene = self.copy() new_gene.weight = 0.5 * (self.weight + other.weight) return new_gene def to_json(self): return dict(connection=self.connection.to_json(), innovation_number=self.innovation_number, is_enabled=self.is_enabled) @staticmethod def from_json(config): gene = ConnectionGene() gene.connection = Connection.from_json(config['connection']) gene.innovation_number = config['innovation_number'] gene.is_enabled = config['is_enabled'] return gene def __str__(self): return 'Connection_Gene_%d(%s)' % (self.innovation_number, self.connection) + \ ' (disabled)' if not self.is_enabled else '' def __eq__(self, other): return self.connection == other.connection and \ self.innovation_number == other.innovation_number def __hash__(self): return self.innovation_number def __lt__(self, other): return self.innovation_number < other.innovation_number