-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindividual.py
More file actions
84 lines (65 loc) · 3.03 KB
/
Copy pathindividual.py
File metadata and controls
84 lines (65 loc) · 3.03 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import numpy as np
import random
from typing import List
import config
from shape import Shape, create_shape
class Individual:
def __init__(self, num_shapes: int = 0, image_size: tuple[int, int] = (256, 256)):
self.dna: List[Shape] = []
self.fitness = 0.0
self.image_size = image_size
# Inicializa com formas aleatorias se num_shapes for fornecido
if num_shapes > 0:
self._initialize_random_dna(num_shapes)
def _initialize_random_dna(self, num_shapes: int):
"""Inicializa DNA com formas aleatorias."""
self.dna = [
create_shape(random.choice(config.SHAPE_TYPES), self.image_size)
for _ in range(num_shapes)
]
def render(self, image_size: tuple[int, int] | None = None) -> np.ndarray:
"""Renderiza o individuo desenhando todas as formas em seu DNA e retorna numpy array (BGR)."""
if image_size is None:
image_size = self.image_size
# Cria uma nova imagem numpy com fundo predominante (BGR format para cv2)
height, width = image_size[1], image_size[0]
color = config.PALLETE[0] if config.PALLETE is not None else (255, 255, 255)
image = np.full((height, width, 3), color, dtype=np.uint8)
# Desenha todas as formas do DNA
for shape in self.dna:
shape.draw(image)
return image
def mutate(self, mutation_rate: float):
"""Muta o individuo mutando cada forma em seu DNA."""
for shape in self.dna:
shape.mutate(mutation_rate)
def crossover(self, other: "Individual") -> "Individual":
"""Executa crossover entre este individuo e outro, retornando um novo individuo."""
# Cria um novo individuo
child = Individual(image_size=self.image_size)
# Crossover simples: pega metade do DNA de cada pai
if len(self.dna) > 0 and len(other.dna) > 0:
# Encontra o comprimento minimo para evitar erros de indice
min_length = min(len(self.dna), len(other.dna))
mid_point = min_length // 2
# Pega formas de ambos os pais, copiando para evitar problemas de referencia
child.dna = [shape.copy() for shape in self.dna[:mid_point]] + [
shape.copy() for shape in other.dna[mid_point:]
]
return child
def copy(self) -> "Individual":
"""Cria uma copia profunda deste individuo."""
new_individual = Individual()
new_individual.image_size = self.image_size
new_individual.dna = [shape.copy() for shape in self.dna]
new_individual.fitness = self.fitness
return new_individual
def get_num_shapes(self) -> int:
"""Obtem o numero de formas no DNA do individuo."""
return len(self.dna)
def __str__(self) -> str:
"""Representacao string do individuo."""
return f"Individual(shapes={len(self.dna)}, fitness={self.fitness:.4f})"
def __repr__(self) -> str:
"""Representacao string detalhada do individuo."""
return self.__str__()