Вынес методы инициализации из хромосомы

This commit is contained in:
2025-10-21 18:14:20 +03:00
parent afd7a700ca
commit 83be98e923
3 changed files with 84 additions and 73 deletions

View File

@@ -1,7 +1,7 @@
import random
from typing import Callable
from .chromosome import Chromosome, InitMethod
from .chromosome import Chromosome, InitFunc, init_full, init_grow
type Population = list[Chromosome]
@@ -9,7 +9,7 @@ type Population = list[Chromosome]
def ramped_initialization(
population_size: int,
depths: list[int],
make_chromosome: Callable[[int, InitMethod], Chromosome], # (max_depth, method)
make_chromosome: Callable[[InitFunc], Chromosome],
) -> Population:
"""Комбинация методов grow и full инициализации хромосом для инициализации начальной
популяции.
@@ -25,14 +25,18 @@ def ramped_initialization(
n_full = int(per_depth / 2)
n_grow = int(per_depth / 2)
population.extend(make_chromosome(depth, "full") for _ in range(n_full))
population.extend(make_chromosome(depth, "grow") for _ in range(n_grow))
population.extend(
make_chromosome(lambda c: init_full(c, depth)) for _ in range(n_full)
)
population.extend(
make_chromosome(lambda c: init_grow(c, depth)) for _ in range(n_grow)
)
# Из-за округления хромосом может оказаться меньше заданного количества,
# поэтому дозаполняем остаток популяции случайными хромосомами
while len(population) < population_size:
depth = random.choice(depths)
method = "full" if random.random() < 0.5 else "grow"
population.append(make_chromosome(depth, method))
init_func = init_full if random.random() < 0.5 else init_grow
population.append(make_chromosome(lambda c: init_func(c, depth)))
return population