Source code for Individual.BitstreamIndividual
1"""Individual representation for evolutionary bitstream experiments.
2
3Each individual wraps a boolean bitstream that maps to an FPGA circuit
4configuration. Provides mutation, crossover, and randomization operators
5used by the population initialization and reproduction strategies.
6"""
7
8from random import Random
9
10
[docs]
11class BitstreamIndividual:
12 """A genetic individual whose genome is a list of boolean bits.
13
14 Used by :class:`~Population.PopulationInitialization.GenerateBitstreamPopulation`
15 to create populations, and by reproducers to generate offspring.
16 """
[docs]
17 def __init__(self, bitstream_sz: int, rand: Random, mutation_probability: float):
18 """Create an individual with a zeroed bitstream of the given size."""
19 self.__bitstream: list[bool] = [False] * bitstream_sz
20 self.__rand = rand
21 self.__mutation_probability = mutation_probability
22
[docs]
23 def set_bitstream(self, bitstream: list[bool]):
24 """Replace the entire bitstream with the provided list."""
25 self.__bitstream = bitstream
26
[docs]
27 def get_bitstream(self) -> list[bool]:
28 """Return the current bitstream."""
29 return self.__bitstream
30
[docs]
31 def mutate(self):
32 """Flip each bit independently with the configured mutation probability."""
33 for i in range(len(self.__bitstream)):
34 if self.__mutation_probability >= self.__rand.uniform(0,1):
35 self.__bitstream[i] = not self.__bitstream[i]
36
[docs]
37 def crossover(self, parent: 'BitstreamIndividual', crossover_point: int):
38 """Single-point crossover: take bits before *crossover_point* from self and the rest from *parent*."""
39 first = self.__bitstream[0:crossover_point]
40 second = parent.__bitstream[crossover_point:]
41 new_bitstream = first + second
42 self.set_bitstream(new_bitstream)
43
[docs]
44 def randomize(self):
45 """Set every bit to a uniformly random value."""
46 for i in range(len(self.__bitstream)):
47 if self.__rand.randint(0, 1) == 0:
48 self.__bitstream[i] = False
49 else:
50 self.__bitstream[i] = True
51
[docs]
52 def copy_from(self, other: 'BitstreamIndividual'):
53 """Deep-copy the bitstream from *other* into this individual."""
54 self.__bitstream = other.__bitstream.copy()
55