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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495 | class Instance:
__slots__ = (
"_variables",
"_fitness",
"_performance_bias",
"_novelty",
"_descriptor",
"_portfolio_scores",
"_descriptor_dim",
"_portfolio_dim",
"_dtype",
)
def __init__(
self,
variables: Sequence | np.ndarray,
fitness: float | np.float64 = np.float64(0.0),
performance_bias: float | np.float64 = np.float64(0.0),
novelty: float | np.float64 = np.float64(0.0),
descriptor: Optional[Sequence[float | np.float64]] = None,
portfolio_scores: Optional[Sequence[float | np.float64]] = None,
dtype=np.uint32,
):
"""Creates an instance of a Instance for QD algorithms.
This class is used to represent a solution in a QD algorithm. It contains the
variables, fitness, performance bias, novelty, descriptor and portfolio scores
of the instance.
The variables, descriptor and portfolio scores are stored as a numpy array.
The fitness, performance and novelty are stored as np.float64.
Args:
variables (Sequence): Variables or genome of the instance.
fitness (float, optional): Fitness of the instance. Defaults to 0.0.
performance_bias (float, optional): Performance score. Defaults to 0.0.
novelty (float, optional): Novelty score. Defaults to 0.0.
descriptor (Optional[Sequence[float | np.float64], optional): Tuple with the descriptor information of the instance. Defaults to None.
portfolio_scores (Optional[Sequence[float | np.float64], optional): Scores of the solvers in the portfolio. Defaults to None.
Raises:
ValueError: If fitness, performance_bias or novelty are not convertible to float.
"""
self._dtype = dtype
try:
self._fitness = float(fitness)
self._performance_bias = float(performance_bias)
self._novelty = float(novelty)
except (TypeError, ValueError) as exception:
exception.add_note(f"fitness: {fitness}")
exception.add_note(f"performance_bias: {performance_bias}")
exception.add_note(f"novelty: {novelty}")
raise TypeError("Wrong parameters for Instance.") from exception
# Todo: Consider fix the dimensions of the descriptor and portfolio
# if type(descriptor_dim) is not int or descriptor_dim <= 0:
# raise ValueError(
# f"descriptor_dim must be a positive integer. Got {descriptor_dim}."
# )
# else:
# self._descriptor_dim = int(descriptor_dim)
# if type(portfolio_dim) is not int or portfolio_dim <= 0:
# raise ValueError(
# f"portfolio_dim must be a positive integer. Got {portfolio_dim}."
# )
# else:
# self._portfolio_dim = int(portfolio_dim)
if variables is None or len(variables) == 0:
raise ValueError(f"variables has to be a valid sequence. Got: {variables}")
else:
self._variables = np.asarray(variables, dtype=self._dtype, copy=True)
if descriptor is not None and len(descriptor) == 0:
raise ValueError(
f"descriptors must be either None or a sequence with at least one value. Got: {descriptor}"
)
else:
if descriptor is None:
self._descriptor = np.empty(0, dtype=np.float64)
else:
self._descriptor = np.asarray(descriptor, dtype=np.float64, copy=True)
if portfolio_scores is not None and len(portfolio_scores) == 0:
raise ValueError(
f"portfolio_scores must be either None or a sequence with at least one value. Got: {portfolio_scores}"
)
else:
if portfolio_scores is None:
self._portfolio_scores = np.empty((0), dtype=np.float64)
else:
self._portfolio_scores = np.asarray(portfolio_scores, dtype=np.float64)
@property
def dtype(self):
return self._dtype
def clone(self) -> Self:
"""Create a clone of the current instance.
This avoids Python-level list/tuple conversions by copying the underlying
NumPy arrays directly.
Returns:
Self: Instance object
"""
new_instance = object.__new__(type(self))
new_instance._dtype = self._dtype
new_instance._fitness = self._fitness
new_instance._performance_bias = self._performance_bias
new_instance._novelty = self._novelty
new_instance._variables = self._variables.copy()
new_instance._descriptor = self._descriptor.copy()
new_instance._portfolio_scores = self._portfolio_scores.copy()
return new_instance
def clone_with(self, **overrides):
"""Clones an Instance with overriden attributes
Returns:
Instance
"""
new_object = self.clone()
for key, value in overrides.items():
setattr(new_object, key, value)
return new_object
@property
def variables(self):
return self._variables
@variables.setter
def variables(self, new_variables: np.ndarray):
if new_variables is None or len(new_variables) == 0:
raise ValueError(
f"new_variables cannot be None nor be empty. Got: {new_variables}."
)
elif len(new_variables) != len(self._variables):
raise ValueError(
"Updating the variables of an Instance object with a different number of values. "
f"Instance have {len(self._variables)} variables "
f"and the new_variables sequence have {len(new_variables)}"
)
else:
self._variables = np.asarray(new_variables)
@property
def performance_bias(self) -> float | np.float64:
return self._performance_bias
@performance_bias.setter
def performance_bias(self, performance: float | np.float64):
try:
self._performance_bias = float(performance)
except (TypeError, ValueError) as exc:
raise ValueError(
f"performance_bias value is not a float. Got: {performance}."
) from exc
@property
def novelty(self) -> float | np.float64:
return self._novelty
@novelty.setter
def novelty(self, nov_score: float | np.float64):
try:
self._novelty = float(nov_score)
except (TypeError, ValueError) as exc:
raise ValueError(
f"nov_score value is not a float. Got: {nov_score}."
) from exc
@property
def fitness(self) -> float | np.float64:
return self._fitness
@fitness.setter
def fitness(self, new_fitness: float | np.float64):
try:
self._fitness = float(new_fitness)
except (TypeError, ValueError) as exc:
raise ValueError(
f"new_fitness value is not a float. Got: {new_fitness}."
) from exc
@property
def descriptor(self) -> np.ndarray:
return self._descriptor
@descriptor.setter
def descriptor(self, descriptor: Sequence[float | np.float64] | np.ndarray):
self._descriptor = np.asarray(descriptor)
@property
def portfolio_scores(self):
return self._portfolio_scores
@portfolio_scores.setter
def portfolio_scores(self, scores: Sequence[float | np.float64] | np.ndarray):
self._portfolio_scores = np.asarray(scores)
def __repr__(self):
return self.__str__()
def __str__(self):
import reprlib
descriptor = reprlib.repr(self.descriptor)
performance = reprlib.repr(self.portfolio_scores)
performance = performance[performance.find("(") : performance.rfind(")") + 1]
return (
f"Instance:\n"
f" - fitness = {self.fitness}\n"
f" - performance_bias = {self.performance_bias}\n"
f" - novelty = {self.novelty}\n"
f" - descriptor = {descriptor}\n"
f" - portfolio scores = {performance}\n"
)
def __iter__(self):
return iter(self._variables)
def __len__(self):
return len(self._variables)
def __getitem__(self, key: int | slice) -> Sequence | np.ndarray:
"""Accessor to variables of the Instance
Args:
key (index | slice): index or slice to access a subset of variables
Returns:
Sequence or np.ndarray: If accessed with a slice the subset of variables
are returned. Otherwise, it returns a single scalar at variables[key].
"""
if not isinstance(key, (int, slice)):
raise TypeError(
f"Instance cannot be indexed with type: {type(key)}. Use slice or int."
)
if isinstance(key, slice):
return self._variables[key]
else:
index = operator.index(key)
return self.variables[index]
def __setitem__(self, key: int | slice, value):
"""Setter to variables of the Instance
Args:
key (int | slice): index or slice to access a subset of variables
value: Value to set in the variables
"""
if not isinstance(key, (int, np.integer, np.unsignedinteger, slice)):
raise TypeError(
f"Instance cannot be update via __setitem__ with type: {type(key)}. Use slice or int."
)
if isinstance(key, slice):
# Compute how many positions this slice actually targets
start, stop, step = key.indices(len(self.variables))
target_count = len(range(start, stop, step))
# Accept any sequence; reject bare scalars for slice assignment
try:
expected_len = len(value)
except TypeError:
raise TypeError(
f"[Instance] slice assignment requires a sequence, got scalar {value!r}. "
f"Expected {target_count} value(s)."
)
if expected_len != target_count:
raise ValueError(
f"[Instance] slice targets {target_count} element(s) but value has "
f"{expected_len} element(s)."
)
else:
index = operator.index(key)
try:
if len(value) != 1:
raise ValueError(
f"[Instance] index {index!r} targets 1 element but value has "
f"{len(value)} element(s). Use a slice to assign multiple values."
)
except TypeError:
pass # len() failed which means that we have a scalar value
self._variables[key] = value
def __eq__(self, other: Self) -> bool:
"""Compares two Instances based on their variables.
Args:
other (Self): Another instance to compare.
Returns:
bool: Returns True if the two instances have the same number of variables,
and all of them are equal. Returns False otherwise.
"""
if not isinstance(other, Instance):
raise TypeError(
f"Other of type {other.__class__.__name__} can not be compared with an Instance."
)
else:
try:
return all(a == b for a, b in zip(self, other, strict=True))
except ValueError:
return False
def __gt__(self, other: Self) -> bool | np.bool:
"""Compares two Instances based on their fitness.
Args:
other (Self): Another instance to compare.
Returns:
bool: Returns True if the self has a greater fitness
than the other. Returns False otherwise.
"""
if not isinstance(other, Instance):
raise TypeError(
f"Other of type {other.__class__.__name__} can not be compared with an Instance."
)
else:
return self.fitness > other.fitness
def __ge__(self, other: Self) -> bool | np.bool:
"""Compares two Instances based on their fitness.
Args:
other (Self): Another instance to compare.
Returns:
bool: Returns True if the self has a greater or equal fitness
than the other. Returns False otherwise.
"""
if not isinstance(other, Instance):
raise TypeError(
f"Other of type {other.__class__.__name__} can not be compared with an Instance."
)
else:
return self.fitness >= other.fitness
def to_dict(
self,
variables_names: Optional[Sequence[str]] = None,
descriptor_names: Optional[Sequence[str]] = None,
portfolio_names: Optional[Sequence[str]] = None,
) -> dict:
"""Convert the instance to a dictionary.
The keys are the names of the attributes and the values are the values of the attributes.
Args:
variables_names (Optional[Sequence[str]], optional): Names of the variables in the dictionary, otherwise v_i. Defaults to None.
descriptor_names: (Optional[Sequence[str]], optional): Names of the components of the descriptor, otherwisde di. Default to None.
portfolio_names (Optional[Sequence[str]], optional): Name of the solvers, otherwise solver_i. Defaults to None.
Returns:
dict: Dictionary with the attributes of the instance as keys and the values of the attributes as values.
"""
_instance_data = {}
descriptor_names = _validate_column_names(
"descriptor", descriptor_names, len(self._descriptor), fallback_keyword="d"
)
_instance_data = {
**{key: value for key, value in zip(descriptor_names, self._descriptor)}
}
variables_names = _validate_column_names(
"variables_names", variables_names, len(self), fallback_keyword="v"
)
_instance_data["variables"] = {
key: value for key, value in zip(variables_names, self._variables)
}
portfolio_names = _validate_column_names(
"portfolio_names",
portfolio_names,
len(self.portfolio_scores),
fallback_keyword="alg",
)
_instance_data["portfolio_scores"] = {
key: value for key, value in zip(portfolio_names, self._portfolio_scores)
}
_instance_data = {
"target": portfolio_names[0],
"fitness": self._fitness,
"novelty": self._novelty,
"performance_bias": self._performance_bias,
**_instance_data,
}
return _instance_data
def to_json(self) -> str:
"""Convert the instance to a JSON string.
The keys are the names of the attributes and the values are the values of the attributes.
Returns:
str: JSON string with the attributes of the instance as keys and the values of the attributes as values.
"""
import json
# Todo: Need to change dtypes because np is not JSON serializable
return json.dumps(self.to_dict(), sort_keys=False, indent=2)
def to_df(
self,
variables_names: Optional[Sequence[str]] = None,
descriptor_names: Optional[Sequence[str]] = None,
portfolio_names: Optional[Sequence[str]] = None,
) -> pl.DataFrame:
"""Creates a Polars DataFrame from the instance.
Args:
variables_names (Optional[Sequence[str]], optional): Names of the variables in the dictionary, otherwise v_i. Defaults to None.
descriptor_names: (Optional[Sequence[str]], optional): Names of the components of the descriptor, otherwisde di. Default to None.
portfolio_names (Optional[Sequence[str]], optional): Name of the solvers, otherwise solver_i. Defaults to None.
Returns:
DataFrame: Polars DataFrame with the attributes of the instance as keys and the values of the attributes as values.
"""
_flatten_data = {}
for key, value in self.to_dict(
variables_names=variables_names,
descriptor_names=descriptor_names,
portfolio_names=portfolio_names,
).items():
if isinstance(value, dict): # Flatten nested dicts
for sub_key, sub_value in value.items():
_flatten_data[sub_key] = sub_value
else:
_flatten_data[key] = value
return pl.DataFrame(_flatten_data)
|