-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopulation_manager.py
More file actions
71 lines (55 loc) · 2.15 KB
/
population_manager.py
File metadata and controls
71 lines (55 loc) · 2.15 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
"""Population persistence and selection for the grounded evolution loop.
Manages a JSON-based population of prompts with their scores and
generation metadata. Supports elitist selection and tournament
selection strategies.
"""
import json
import random
from pathlib import Path
POP_FILE: str = "population/population.json"
MAX_POPULATION: int = 50
PopulationEntry = dict[str, str | float | int]
Population = list[PopulationEntry]
def load_population() -> Population:
"""Load population from JSON file, seeding if empty."""
path = Path(POP_FILE)
if not path.exists():
seed: Population = [
{
"prompt": "Generate clean production-grade Python software with modular structure, type hints, and comprehensive tests",
"score": 0,
"generation": 0,
}
]
path.parent.mkdir(exist_ok=True)
with open(path, "w") as f:
json.dump(seed, f, indent=2)
return seed
with open(path) as f:
return json.load(f)
def save_population(pop: Population) -> None:
"""Persist population to JSON file."""
with open(POP_FILE, "w") as f:
json.dump(pop, f, indent=2)
def select_best(pop: Population, k: int = 3) -> Population:
"""Return the top-k individuals by score (elitist selection)."""
return sorted(pop, key=lambda x: float(x.get("score", 0)), reverse=True)[:k]
def select_tournament(pop: Population, tournament_size: int = 3) -> PopulationEntry | None:
"""Select via tournament: pick best from random subset.
Returns None if the population is empty.
"""
if not pop:
return None
competitors: Population = random.sample(pop, min(tournament_size, len(pop)))
return max(competitors, key=lambda x: float(x.get("score", 0)))
def add_individual(pop: Population, prompt: str, score: float, generation: int) -> Population:
"""Add a new individual and cull to MAX_POPULATION."""
pop.append(
{
"prompt": prompt,
"score": score,
"generation": generation,
}
)
pop.sort(key=lambda x: float(x.get("score", 0)), reverse=True)
return pop[:MAX_POPULATION]