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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165 | class CNSGAGenerator(Generator):
name = "cnsga"
supports_multi_objective: bool = True
population_size: int = Field(64, description="Population size")
crossover_probability: confloat(ge=0, le=1) = Field(
0.9, description="Crossover probability"
)
mutation_probability: confloat(ge=0, le=1) = Field(
1.0, description="Mutation probability"
)
population_file: Optional[str] = Field(
None, description="Population file to load (CSV format)"
)
output_path: Optional[str] = Field(
None, description="Output path for population " "files"
)
_children: List[Dict] = PrivateAttr([])
_offspring: Optional[pd.DataFrame] = PrivateAttr(None)
population: Optional[pd.DataFrame] = Field(None)
model_config = ConfigDict(extra="allow")
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._loaded_population = (
None # use these to generate children until the first pop is made
)
# DEAP toolbox (internal)
self._toolbox = cnsga_toolbox(self.vocs, selection="auto")
if self.population_file is not None:
self.load_population_csv(self.population_file)
if self.output_path is not None:
assert os.path.isdir(self.output_path), "Output directory does not exist"
# if data is not None:
# self.population = cnsga_select(data, n_pop, vocs, self.toolbox)
def create_children(self) -> List[Dict]:
# No population, so create random children
if self.population is None:
# Special case when pop is loaded from file
if self._loaded_population is None:
return self.vocs.random_inputs(self.n_pop, include_constants=False)
else:
pop = self._loaded_population
else:
pop = self.population
# Use population to create children
inputs = cnsga_variation(
pop,
self.vocs,
self._toolbox,
crossover_probability=self.crossover_probability,
mutation_probability=self.mutation_probability,
)
return inputs.to_dict(orient="records")
def add_data(self, new_data: pd.DataFrame):
if new_data is not None:
self._offspring = pd.concat([self._offspring, new_data])
# Next generation
if len(self._offspring) >= self.n_pop:
candidates = pd.concat([self.population, self._offspring])
self.population = cnsga_select(
candidates, self.n_pop, self.vocs, self._toolbox
)
if self.output_path is not None:
self.write_offspring()
self.write_population()
self._children = [] # reset children
self._offspring = None # reset offspring
def generate(self, n_candidates) -> list[dict]:
"""
generate `n_candidates` candidates
"""
# Make sure we have enough children to fulfill the request
while len(self._children) < n_candidates:
self._children.extend(self.create_children())
return [self._children.pop() for _ in range(n_candidates)]
def write_offspring(self, filename=None):
"""
Write the current offspring to a CSV file.
Similar to write_population
"""
if self._offspring is None:
logger.warning("No offspring to write")
return
if filename is None:
filename = f"{self.name}_offspring_{xopt.utils.isotime(include_microseconds=True)}.csv"
filename = os.path.join(self.output_path, filename)
self._offspring.to_csv(filename, index_label="xopt_index")
def write_population(self, filename=None):
"""
Write the current population to a CSV file.
Similar to write_offspring
"""
if self.population is None:
logger.warning("No population to write")
return
if filename is None:
filename = f"{self.name}_population_{xopt.utils.isotime(include_microseconds=True)}.csv"
filename = os.path.join(self.output_path, filename)
self.population.to_csv(filename, index_label="xopt_index")
def load_population_csv(self, filename):
"""
Read a population from a CSV file.
These will be reverted back to children for re-evaluation.
"""
pop = pd.read_csv(filename, index_col="xopt_index")
self._loaded_population = pop
# This is a list of dicts
self._children = self.vocs.convert_dataframe_to_inputs(
pop[self.vocs.variable_names], include_constants=False
).to_dict(orient="records")
logger.info(f"Loaded population of len {len(pop)} from file: {filename}")
@property
def n_pop(self):
"""
Convenience name for `options.population_size`
"""
return self.population_size
|