OpenCog Framework  Branch: master, revision 6f0b7fc776b08468cf1b74aa9db028f387b4f0c0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
genetic_algorithm.py
Go to the documentation of this file.
1 __author__ = 'keyvan'
2 
3 from utility.evolutionary import *
4 
5 BIT_STRING_LENGTH = 32
6 ALL_BITS_ONE = 2**BIT_STRING_LENGTH - 1
7 
8 class BitStringIndividualBase(IndividualBase):
9 
10  def __init__(self, _binary_chromosome=0):
11  self.chromosome = _binary_chromosome
12 
13  @staticmethod
15  instance = BitStringIndividualBase()
16  instance.chromosome = randrange(0,ALL_BITS_ONE)
17  return instance
18 
19  loci = range(BIT_STRING_LENGTH)
20 
21  def __fitness__(self):
22  result = 0
23  for i in range(BIT_STRING_LENGTH):
24  if self[i] == 1:
25  result += 1
26  return result
27 
28  def __getitem__(self, index):
29  if self.chromosome & 2**index == 0:
30  return 0
31  return 1
32 
33  def __setitem__(self, index, value):
34  if value == 1:
35  self.chromosome |= 2**index
36  else:
37  self.chromosome &= ALL_BITS_ONE ^ 2**index
38 
39  def __mutate__(self):
40  mask = 2**randrange(0, BIT_STRING_LENGTH)
41  return BitStringIndividualBase(self.chromosome ^ mask)
42 
43  def __repr__(self):
44  result = ''
45  for i in range(BIT_STRING_LENGTH):
46  result = str(self[i]) + result
47  return result
48 
49 if __name__ == '__main__':
50  population = []
51  for i in range(32):
52  population.append(BitStringIndividualBase.randomly_initialised())
53  ga = GeneticAlgorithm(population)
54  for i in range(10):
55  fittest = ga.step(0, 1)
56  print fittest, fittest.fitness
57  print 'Solution found:'
58  print ga.fittest_individual_found, ga.highest_fitness_found