feat(ga): tournament selection + elitism

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-09 20:12:51 +02:00
parent 71cfcf786f
commit 3f36ad65dd
2 changed files with 72 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
from __future__ import annotations
import random
from ..genome.hypothesis import HypothesisAgentGenome
def tournament_select(
population: list[HypothesisAgentGenome],
fitnesses: dict[str, float],
k: int,
rng: random.Random,
) -> HypothesisAgentGenome:
"""Estrae k individui random e restituisce il migliore."""
if k < 1:
raise ValueError("k must be >= 1")
if not population:
raise ValueError("empty population")
candidates = rng.sample(population, k=min(k, len(population)))
return max(candidates, key=lambda g: fitnesses.get(g.id, 0.0))
def elite_select(
population: list[HypothesisAgentGenome],
fitnesses: dict[str, float],
k: int,
) -> list[HypothesisAgentGenome]:
"""Restituisce i k genomi con fitness più alta."""
sorted_pop = sorted(population, key=lambda g: fitnesses.get(g.id, 0.0), reverse=True)
return sorted_pop[:k]