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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383 | class EAGenerator(Generator, RNG):
"""Object to generate instances based on a Evolutionary Algorithn with set of diverse solutions"""
def __init__(
self,
domain: Domain,
portfolio: Iterable[SupportsSolve[P]],
novelty_approach: NS,
pop_size: int = 100,
generations: int = 1000,
solution_set: Optional[Archive] = None,
descriptor_strategy: str = "features",
transformer: Optional[SupportsTransform] = None,
repetitions: int = 1,
cxrate: float = 0.5,
mutrate: float = 0.8,
crossover: Crossover = uniform_crossover,
mutation: Mutation = uniform_one_mutation,
selection: Selection = binary_tournament_selection,
replacement: Replacement = generational_replacement,
performance_function: PerformanceFn = max_gap_target,
phi: float = 0.85,
seed: int = 42,
):
"""Creates a Evolutionary Instance Generator based on Novelty Search
The generator uses a set of solvers to evaluate the instances and
a novelty search algorithm to guide the evolution of the instances.
Args:
domain (Domain): Domain for which the instances are generated for.
portfolio (Iterable[SupportSolve]): Iterable item of callable objects that can evaluate a instance.
pop_size (int, optional): Number of instances in the population to evolve. Defaults to 100.
generations (int, optional): Number of generations to perform. Defaults to 1000.
solution_set (Optional[Archive], optional): Solution set to store the instances. Defaults to None.
descriptor_strategy (str, optional): Descriptor used to calculate the diversity. The options available are defined in the dictionary digneapy.qd.descriptor_strategies. Defaults to "features".
transformer (callable, optional): Define a strategy to transform the high-dimensional descriptors to low-dimensional.Defaults to None.
repetitions (int, optional): Number times a solver in the portfolio must be run over the same instance. Defaults to 1.
cxrate (float, optional): Crossover rate. Defaults to 0.5.
mutrate (float, optional): Mutation rate. Defaults to 0.8.
crossover (Crossover, optional): Crossover operator. Defaults to uniform_crossover.
mutation (Mutation, optional): Mutation operator. Defaults to uniform_one_mutation.
selection (Selection, optional): Selection operator. Defaults to binary_tournament_selection.
replacement (Replacement, optional): Replacement operator. Defaults to generational_replacement.
performance_function (PerformanceFn, optional): Performance function to calculate the performance score. Defaults to max_gap_target.
phi (float, optional): Phi balance value for the weighted fitness function. Defaults to 0.85.
seed (int, optional): Seed for the RNG protocol. Defaults to 42.
Raises:
ValueError: Raises error if phi is not a floating point value or it is not in the range [0.0-1.0]
KeyError: Raises error if the descriptor strategy is not available in the DESCRIPTORS dictionary
"""
try:
self._desc_key = descriptor_strategy
self._descriptor_strategy = DESCRIPTORS[self._desc_key]
except KeyError:
self._desc_key = "instance"
self._descriptor_strategy = DESCRIPTORS[self._desc_key]
print(
f"Descriptor: {descriptor_strategy} not available. Using the full instance as default descriptor"
)
try:
phi = float(phi)
except ValueError:
raise ValueError("Phi must be a float number in the range [0.0-1.0].")
if phi < 0.0 or phi > 1.0:
msg = f"Phi must be a float number in the range [0.0-1.0]. Got: {phi}."
raise ValueError(msg)
self.phi = phi
self._novelty_search = novelty_approach
self._solution_set = None # By default there's not solution set
if solution_set is not None:
self._ns_solution_set = NS(archive=solution_set, k=1)
self._transformer = transformer
self.pop_size = pop_size
self.offspring_size = pop_size
self.generations = generations
self.domain = domain
self.portfolio = tuple(portfolio) if portfolio else ()
self.population = []
self.repetitions = repetitions
self.cxrate = cxrate
self.mutrate = mutrate
self.crossover = crossover
self.mutation = mutation
self.selection = selection
self.replacement = replacement
self.performance_function = performance_function
self._logbook = Logbook()
self.initialize_rng(seed=seed)
@property
def log(self) -> Logbook:
return self._logbook
def __str__(self):
port_names = [s.__name__ for s in self.portfolio]
domain_name = self.domain.name if self.domain is not None else "None"
return f"EAGenerator(pop_size={self.pop_size},gen={self.generations},domain={domain_name},portfolio={port_names!r},{self._novelty_search.__str__()})"
def __repr__(self) -> str:
port_names = [s.__name__ for s in self.portfolio]
domain_name = self.domain.name if self.domain is not None else "None"
return f"EAGenerator<pop_size={self.pop_size},gen={self.generations},domain={domain_name},portfolio={port_names!r},{self._novelty_search.__repr__()}>"
def __call__(self, verbose: bool = False) -> GenResult:
if self.domain is None:
raise ValueError("You must specify a domain to run the generator.")
if len(self.portfolio) == 0:
raise ValueError(
"The portfolio is empty. To run the generator you must provide a valid portfolio of solvers"
)
self.population = self.domain.generate_instances(n=self.pop_size)
perf_biases, portfolio_scores = self._evaluate_population(self.population)
descriptors, features = self._update_descriptors(
self.population, portfolio_scores=portfolio_scores
)
for pgen in range(self.generations):
offspring = self._generate_offspring(self.pop_size)
perf_biases, portfolio_scores = self._evaluate_population(offspring)
descriptors, features = self._update_descriptors(
offspring, portfolio_scores=portfolio_scores
)
novelty_scores = self._novelty_search(instances_descriptors=descriptors)
offspring_fitness = self.__compute_fitness(perf_biases, novelty_scores)
# Update to include this
# 1. Novelty Scores --> novelty_scores
# 2. Performance bias --> perf_biases
# 3. Fitness --> oiffspring_fitness
# 4. Descriptor --> descriptors
offspring = [
Instance(
variables=offspring[i],
fitness=offspring_fitness[i],
descriptor=descriptors[i],
portfolio_scores=portfolio_scores[i],
p=perf_biases[i],
s=novelty_scores[i],
features=features[i] if features is not None else None,
)
for i in range(len(offspring))
]
# Only the feasible instances are considered to be included
# in the archive and the solution set.
feasible_indeces = np.where(perf_biases > 0)[0]
self._novelty_search.archive.extend(
instances=[offspring[i] for i in feasible_indeces],
descriptors=descriptors[feasible_indeces],
novelty_scores=novelty_scores[feasible_indeces],
)
if self._ns_solution_set:
# TODO: Here I should only compute the feasible individuals
novelty_solution_set = self._ns_solution_set(
instances_descriptors=descriptors
)
self._ns_solution_set.archive.extend(
instances=[offspring[i] for i in feasible_indeces],
descriptors=descriptors[feasible_indeces],
novelty_scores=novelty_solution_set[feasible_indeces],
)
# However the whole offspring population is used in the replacement operator
self.population = self.replacement(self.population, offspring)
# Record the stats and update the performed gens
self._logbook.update(
generation=pgen, population=self.population, feedback=verbose
)
if verbose:
# Clear the terminal
blank = " " * 80
print(f"\r{blank}\r", end="")
_instances = (
self._ns_solution_set.archive
if self._ns_solution_set is not None
else self._novelty_search.archive
)
return GenResult(
target=self.portfolio[0].__name__,
instances=_instances,
history=self._logbook,
)
def _generate_offspring(self, offspring_size: int) -> np.ndarray:
"""Generates a offspring population of size |offspring_size| from the current population
Args:
offspring_size (int): offspring size. Defaults to pop_size.
Returns:
Sequence[Instance] Returns a sequence with the instances definitions, the offspring population.
"""
offspring = [None] * offspring_size # np.empty(offspring_size, dtype=Instance)
for i in range(offspring_size):
p_1 = self.selection(self.population)
p_2 = self.selection(self.population)
child = self.__reproduce(p_1, p_2)
offspring[i] = child
return np.array(offspring)
def _update_descriptors(
self,
population: np.ndarray,
portfolio_scores: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, Optional[np.ndarray]]:
"""Updates the descriptors of the population of instances
Args:
population (Sequence[Instance]): Population of instances to update the descriptors.
"""
descriptors = np.empty(len(population))
features = None
if self._desc_key == "features":
descriptors = self.domain.extract_features(population)
features = descriptors.copy()
elif self._desc_key == "performance":
descriptors = np.mean(portfolio_scores, axis=2)
else:
descriptors = self._descriptor_strategy(population)
if self._transformer is not None:
# Transform the descriptors if necessary
descriptors = self._transformer(descriptors)
return (descriptors, features)
def _evaluate_population(
self, population: Sequence[Instance]
) -> Tuple[np.ndarray, np.ndarray]:
"""Evaluates the population of instances using the portfolio of solvers.
Args:
population (Sequence[Instance]): Sequence of instances to evaluate
"""
solvers_scores = np.zeros(
shape=(len(population), len(self.portfolio), self.repetitions)
)
problems_to_solve = self.domain.generate_problems_from_instances(population)
for j, problem in enumerate(problems_to_solve):
for i, solver in enumerate(self.portfolio):
# There is no need to change anything in the evaluation code when using Pisinger solvers
# because the algs. only return one solution per run (len(solutions) == 1)
# The same happens with the simple KP heuristics. However, when using Pisinger solvers
# the lower the running time the better they're considered to work an instance
scores = np.zeros(self.repetitions)
for rep in range(self.repetitions):
scores[rep] = max(
solver(problem), key=attrgetter("fitness")
).fitness
solvers_scores[j, i, :] = scores
mean_solvers_scores = np.mean(solvers_scores, axis=2)
performance_biases = self.performance_function(mean_solvers_scores)
return performance_biases, solvers_scores
def __compute_fitness(
self, performance_biases: np.ndarray, novelty_scores: np.ndarray
) -> np.ndarray:
"""Calculates the fitness of each instance in the population
Args:
performance_biases (np.ndarray): Performance biases or scores of each instance
novelty_scores (np.ndarray): Novelty scores of each instance
Returns:
fitness of each instance (np.ndarray)
"""
phi_r = 1.0 - self.phi
fitness = np.zeros(len(performance_biases))
fitness = (fitness * self.phi) + (novelty_scores * phi_r)
return fitness
def __reproduce(self, parent_1: Instance, parent_2: Instance) -> Instance:
"""Generates a new offspring instance from two parent instances
Args:
parent_1 (Instance): First Parent
parent_1 (Instance): Second Parent
Returns:
Instance: New offspring
"""
offspring = parent_1.clone()
if self._rng.random() < self.cxrate:
offspring = self.crossover(offspring, parent_2)
return self.mutation(offspring, self.domain.bounds)
else:
return self.mutation(offspring, self.domain.bounds)
|