-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindividual.py
More file actions
48 lines (38 loc) · 1.74 KB
/
individual.py
File metadata and controls
48 lines (38 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import numpy as np
from .problem import KnapsackProblem
class Individual:
def __init__(self, chromosome_length: int) -> None:
if chromosome_length <= 0:
raise ValueError("chromosome_length must be > 0")
self.genes: np.ndarray = np.zeros(chromosome_length, dtype=bool)
self.fitness: int = 0
self.total_value: int = 0
self.total_weight: int = 0
@classmethod
def random(cls, chromosome_length: int, rng: np.random.Generator) -> "Individual":
instance = cls(chromosome_length)
instance.genes = rng.integers(0, 2, size=chromosome_length, dtype=bool)
return instance
@classmethod
def copy_of(cls, other: "Individual") -> "Individual":
instance = cls(other.chromosome_length())
instance.genes = other.genes.copy()
instance.fitness = other.fitness
instance.total_value = other.total_value
instance.total_weight = other.total_weight
return instance
def chromosome_length(self) -> int:
return int(self.genes.size)
def gene(self, index: int) -> bool:
return bool(self.genes[index])
def set_gene(self, index: int, value: bool) -> None:
self.genes[index] = value
def flip_gene(self, index: int) -> None:
self.genes[index] = not self.genes[index]
def evaluate(self, problem: KnapsackProblem) -> None:
values = problem._values_array
weights = problem._weights_array
self.total_value = int((self.genes * values).sum())
self.total_weight = int((self.genes * weights).sum())
# kara za nadwagę: osobnik niedopuszczalny dostaje fitness 0 i przegrywa każdy turniej
self.fitness = self.total_value if self.total_weight <= problem.capacity else 0