-
Notifications
You must be signed in to change notification settings - Fork 12
/
Problem.py
1789 lines (1466 loc) · 65.6 KB
/
Problem.py
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
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Desdeo-problem related definitions.
This file has following classes:
ProblemError
EvaluationResults
ProblemBase
ScalarMOProblem -- to be deprecated
ScalarDataProblem -- to be deprecated
MOProblem
DataProblem
ExperimentalProblem
classificationPISProblem
DiscreteDataProblem
"""
from abc import ABC, abstractmethod
# , TypedDict coming in py3.8
from functools import reduce
from operator import iadd
from os import path
from typing import Callable, Dict, List, NamedTuple, Optional, Tuple, Union
import numpy as np
import pandas as pd
from desdeo_problem.problem.Constraint import ScalarConstraint
from desdeo_problem.problem.Objective import (
VectorDataObjective,
VectorObjective,
_ScalarDataObjective,
_ScalarObjective,
ScalarObjective,
ScalarDataObjective,
)
from desdeo_problem.surrogatemodels.SurrogateModels import BaseRegressor
from desdeo_problem.problem.Variable import Variable
class ProblemError(Exception):
"""Raised when an error related to the Problem class is encountered.
"""
# TODO consider replacing namedtuple with attr.s for validation purposes.
class EvaluationResults(NamedTuple):
"""The return object of <problem>.evaluate methods.
Attributes:
objectives (np.ndarray): The objective function values for each input
vector.
fitness (np.ndarray): Equal to objective values if objective is to be
minimized. Multiplied by (-1) if objective to be maximized.
constraints (Union[None, np.ndarray]): The constraint values of the
problem corresponding each input vector.
uncertainity (Union[None, np.ndarray]): The uncertainity in the
objective values.
"""
objectives: np.ndarray
fitness: np.ndarray
constraints: Union[None, np.ndarray] = None
uncertainity: Union[None, np.ndarray] = None
def __str__(self):
"""Textual output of attributes.
Returns:
str: The textual output of attributes
"""
prnt_msg = (
"Evaluation Results Object \n"
f"Objective values are: \n{self.objectives}\n"
f"Constraint violation values are: \n{self.constraints}\n"
f"Fitness values are: \n{self.fitness}\n"
f"Uncertainity values are: \n{self.uncertainity}\n"
)
return prnt_msg
class ProblemBase(ABC):
"""The base class for the problems.
All other problem classes should be derived from this.
Attributes:
nadir (np.ndarray): Nadir values for the problem, initiated = None
ideal (np.ndarray): Ideal values for the problem, initiated = None
nadir_fitness (np.ndarray): Fitness values for nadir, initiated = None
ideal_fitness (np.ndarray): Fitness values for ideal, initiated = None
__n_of_objectives (int): Number of objectives, initiated = 0
__n_of_variables (int): Number of variables, initiated = 0
__decision_vectors (np.ndarray): Array of decision variable vectors,
initiated = None
__objective_vectors (np.ndarray): Array of objective variable vectors,
initiated = None
"""
def __init__(self):
self.nadir: np.ndarray = None
self.ideal: np.ndarray = None
self.nadir_fitness: np.ndarray = None
self.ideal_fitness: np.ndarray = None
self.__n_of_objectives: int = 0
self.__n_of_variables: int = 0
self.__decision_vectors: np.ndarray = None
self.__objective_vectors: np.ndarray = None
@property
def n_of_objectives(self) -> int:
"""Property, returns the number of objectives.
Returns:
int: The number of objectives
"""
return self.__n_of_objectives
@n_of_objectives.setter
def n_of_objectives(self, val: int):
"""Setter, the number of objectives.
Arguments:
val (int): the number of objectives
"""
self.__n_of_objectives = val
@property
def n_of_variables(self) -> int:
"""Property, returns the number of variables.
Returns:
int: The number of variables
"""
return self.__n_of_variables
@n_of_variables.setter
def n_of_variables(self, val: int):
"""Setter, the number of variables.
Arguments:
val (int): the number of variables
"""
self.__n_of_variables = val
@property
def decision_vectors(self) -> np.ndarray:
"""Property, returns the decision variable vectors array.
Returns:
np.ndarray: decision vector array
"""
return self.__decision_vectors
@decision_vectors.setter
def decision_vectors(self, val: np.ndarray):
"""Setter, the decision variable vector array.
Arguments:
val (np.ndarray): the decision vector array
"""
self.__decision_vectors = val
@abstractmethod
def get_variable_bounds(self) -> Union[None, np.ndarray]:
"""Abstract method to get variable bounds"""
pass
@abstractmethod
def evaluate(
self, decision_vectors: np.ndarray, use_surrogate: bool = False
) -> EvaluationResults:
"""Abstract method to evaluate problem.
Evaluates the problem using an ensemble of input vectors. Uses
surrogate models if available. Otherwise, it uses the true evaluator.
Arguments:
decision_vectors (np.ndarray): An array of decision variable
input vectors.
use_surrogate (bool): A bool to control whether to use the true, potentially
expensive function or a surrogate model to evaluate the objectives.
Returns:
(Dict): Dict with the following keys:
'objectives' (np.ndarray): The objective function values for each input
vector.
'constraints' (Union[np.ndarray, None]): The constraint values of the
problem corresponding each input vector.
'fitness' (np.ndarray): Equal to objective values if objective is to be
minimized. Multiplied by (-1) if objective to be maximized.
'uncertainity' (Union[np.ndarray, None]): The uncertainity in the
objective values.
"""
@abstractmethod
def evaluate_constraint_values(self) -> Optional[np.ndarray]:
"""Abstract method to evaluate constraint values.
Evaluate just the constraint function values using the attributes
decision_vectors and objective_vectors
Note:
Currently not supported by ScalarMOProblem
"""
# TODO: Depreciate. Use MO problem in the future
class ScalarMOProblem(ProblemBase):
"""A multiobjective optimization problem.
To be depreciated.
A multiobjective optimization problem with user defined objective
functions, constraints and variables.
The objectives each return a single scalar.
Arguments:
objectives (List[ScalarObjective]): A list containing the objectives of
the problem.
variables (List[Variable]): A list containing the variables of the
problem.
constraints (List[ScalarConstraint]): A list containing the
constraints of the problem. If no constraints exist, None may
be supllied as the value.
nadir (Optional[np.ndarray]): The nadir point of the problem.
ideal (Optional[np.ndarray]): The ideal point of the problem.
Attributes:
__n_of_objectives (int): The number of objectives in the problem.
__n_of_variables (int): The number of variables in the problem.
__n_of_constraints (int): The number of constraints in the problem.
__nadir (np.ndarray): The nadir point of the problem.
__ideal (np.ndarray): The ideal point of the problem.
__objectives (List[ScalarObjective]): A list containing the objectives of
the problem.
__constraints (List[ScalarConstraint]): A list conatining the constraints
of the problem.
Raises:
ProblemError: Ill formed nadir and/or ideal vectors are supplied.
"""
def __init__(
self,
objectives: List[ScalarObjective],
variables: List[Variable],
constraints: List[ScalarConstraint],
nadir: Optional[np.ndarray] = None,
ideal: Optional[np.ndarray] = None,
) -> None:
super().__init__()
self.__objectives: List[ScalarObjective] = objectives
self.__variables: List[Variable] = variables
self.__constraints: List[ScalarConstraint] = constraints
self.__n_of_objectives: int = len(self.objectives)
self.__n_of_variables: int = len(self.variables)
if self.constraints is not None:
self.__n_of_constraints: int = len(self.constraints)
else:
self.__n_of_constraints = 0
# Nadir vector must be the same size as the number of objectives
if nadir is not None:
if len(nadir) != self.n_of_objectives:
msg = (
"The length of the nadir vector does not match the"
"number of objectives: Length nadir {}, number of "
"objectives {}."
).format(len(nadir), self.n_of_objectives)
raise ProblemError(msg)
# Ideal vector must be the same size as the number of objectives
if ideal is not None:
if len(ideal) != self.n_of_objectives:
msg = (
"The length of the ideal vector does not match the"
"number of objectives: Length ideal {}, number of "
"objectives {}."
).format(len(ideal), self.n_of_objectives)
raise ProblemError(msg)
# Nadir and ideal vectors must match in size
if nadir is not None and ideal is not None:
if len(nadir) != len(ideal):
msg = (
"The length of the nadir and ideal point don't match:"
" length of nadir {}, length of ideal {}."
).format(len(nadir), len(ideal))
raise ProblemError(msg)
self.__nadir = nadir
self.__ideal = ideal
# Multiplier to convert maximization to minimization
max_multiplier = np.asarray([1, -1])
to_maximize = [objective.maximize for objective in objectives]
to_maximize = sum(to_maximize, []) # To flatten the list
to_maximize = np.asarray(to_maximize) * 1 # Convert to zeros and ones
self._max_multiplier = max_multiplier[to_maximize]
@property
def n_of_constraints(self) -> int:
"""Property: the number of constraints.
Returns:
int: the number of constraints.
"""
return self.__n_of_constraints
@n_of_constraints.setter
def n_of_constraints(self, val: int):
"""Setter: the number of constraints.
Arguments:
int: the number of constraints.
"""
self.__n_of_constraints = val
@property
def objectives(self) -> List[ScalarObjective]:
"""Property: the list of objectives.
Returns:
List[ScalarObjective]: the list of objectives
"""
return self.__objectives
@objectives.setter
def objectives(self, val: List[ScalarObjective]):
"""Setter: the list of objectives.
Arguments:
val (List[ScalarObjective]): the list of objectives.
"""
self.__objectives = val
@property
def variables(self) -> List[Variable]:
"""Property: the list of problem variables.
Returns:
List[_ScalarObjective]: the list of problem variables
"""
return self.__variables
@variables.setter
def variables(self, val: List[Variable]):
"""Setter: the list of variables.
Arguments:
val (List[_ScalarObjective]): the list of variables.
"""
self.__variables = val
@property
def constraints(self) -> List[ScalarConstraint]:
"""Property: the list of constraints.
Returns:
List[_ScalarObjective]: the list of constraints
"""
return self.__constraints
@constraints.setter
def constraints(self, val: List[ScalarConstraint]):
"""Setter: the list of constraints.
Arguments:
val (List[_ScalarObjective]): the list of constraints.
"""
self.__constraints = val
@property
def n_of_objectives(self) -> int:
"""Property: the number of objectives.
Returns:
int: the number of objectives.
"""
return self.__n_of_objectives
@n_of_objectives.setter
def n_of_objectives(self, val: int):
"""Setter: the number of objectives.
Arguments:
int: the number of objectives.
"""
self.__n_of_objectives = val
@property
def n_of_variables(self) -> int:
"""Property: the number of variables.
Returns:
int: the number of variables.
"""
return self.__n_of_variables
@n_of_variables.setter
def n_of_variables(self, val: int):
"""Setter: the number of variables.
Arguments:
int: the number of variables.
"""
self.__n_of_variables = val
@property
def nadir(self) -> np.ndarray:
"""Property: the nadir point of the problem.
Returns:
np.ndarray: the nadir point of the problem.
"""
return self.__nadir
@nadir.setter
def nadir(self, val: np.ndarray):
"""Setter: the nadir point of the problem.
Arguments:
val (np.ndarray): The nadir point of the problem.
"""
self.__nadir = val
@property
def ideal(self) -> np.ndarray:
"""Property: the ideal point of the problem.
Returns:
np.ndarray: the ideal point of the problem.
"""
return self.__ideal
@ideal.setter
def ideal(self, val: np.ndarray):
"""Setter: the ideal point of the problem.
Arguments:
val (np.ndarray): The ideal point of the problem.
"""
self.__ideal = val
def get_variable_bounds(self) -> Union[np.ndarray, None]:
"""Get the variable bounds.
Return the upper and lower bounds of each decision variable present
in the problem as a 2D numpy array. The first column corresponds to the
lower bounds of each variable, and the second column to the upper
bound.
Returns:
np.ndarray: Lower and upper bounds of each variable
as a 2D numpy array. If undefined variables, return None instead.
"""
if self.variables is not None:
bounds = np.ndarray((self.n_of_variables, 2))
for ind, var in enumerate(self.variables):
bounds[ind] = np.array(var.get_bounds())
return bounds
else:
return None
def get_variable_names(self) -> List[str]:
"""Get variable names.
Return the variable names of the variables present in the problem in
the order they were added.
Returns:
List[str]: Names of the variables in the order they were added.
"""
return [var.name for var in self.variables]
def get_objective_names(self) -> List[str]:
"""Get objective names.
Return the names of the objectives present in the problem in the
order they were added.
Returns:
List[str]: Names of the objectives in the order they were added.
"""
return [obj.name for obj in self.objectives]
def get_uncertainty_names(self) -> List[str]:
"""Return the names of the objectives present in the problem in the
order they were added.
Returns:
List[str]: Names of the objectives in the order they were added.
"""
return [unc.name for unc in self.uncertainty]
def get_variable_lower_bounds(self) -> np.ndarray:
"""Get variable lower bounds.
Return the lower bounds of each variable as a list. The order of the bounds
follows the order the variables were added to the problem.
Returns:
np.ndarray: An array with the lower bounds of the variables.
"""
return np.array([var.get_bounds()[0] for var in self.variables])
def get_variable_upper_bounds(self) -> np.ndarray:
"""Get variable upper bounds.
Return the upper bounds of each variable as a list. The order of the
bounds follows the order the variables were added to the problem.
Returns:
np.ndarray: An array with the upper bounds of the variables.
"""
return np.array([var.get_bounds()[1] for var in self.variables])
def evaluate(
self, decision_vectors: np.ndarray, use_surrogate: bool = False
) -> EvaluationResults:
"""Evaluates the problem using an ensemble of input vectors.
Arguments:
decision_vectors (np.ndarray): An 2D array of decision variable
input vectors. Each column represent the values of each decision
variable.
Returns:
Tuple[np.ndarray, Union[None, np.ndarray]]: If constraint are
defined, returns the objective vector values and corresponding
constraint values. Or, if no constraints are defined, returns just
the objective vector values with None as the constraint values.
Raises:
ProblemError: The decision_vectors have wrong dimensions.
"""
# Reshape decision_vectors with single row to work with the code
if use_surrogate is True:
raise NotImplementedError(
"Surrogates not yet supported in this class. "
"Use the '''DataProblem''' class instead."
)
shape = np.shape(decision_vectors)
if len(shape) == 1:
decision_vectors = np.reshape(decision_vectors, (1, shape[0]))
(n_rows, n_cols) = np.shape(decision_vectors)
if n_cols != self.n_of_variables:
msg = (
"The length of the input vectors does not match the number "
"of variables in the problem: Input vector length {}, "
"number of variables {}."
).format(n_cols, self.n_of_variables)
raise ProblemError(msg)
objective_vectors: np.ndarray = np.ndarray(
(n_rows, self.n_of_objectives), dtype=float
) # ??? Use np.zeros instead of this?
uncertainity: np.ndarray = np.ndarray(
(n_rows, self.n_of_objectives), dtype=float
) # ??? Use np.zeros instead of this?
if self.n_of_constraints > 0:
constraint_values: np.ndarray = np.ndarray(
(n_rows, self.n_of_constraints), dtype=float
)
else:
constraint_values = None
# Calculate the objective values
for (col_i, objective) in enumerate(self.objectives):
results = objective.evaluate(decision_vectors)
objective_vectors[:, col_i] = results.objectives
uncertainity[:, col_i] = results.uncertainity
# Calculate fitness, which is always to be minimized
fitness = objective_vectors * self._max_multiplier
# Calculate the constraint values
if constraint_values is not None:
for (col_i, constraint) in enumerate(self.constraints):
constraint_values[:, col_i] = np.array(
constraint.evaluate(decision_vectors, objective_vectors)
)
return EvaluationResults(
objective_vectors, fitness, constraint_values, uncertainity
)
def evaluate_constraint_values(self) -> Optional[np.ndarray]:
"""Evaluate constraint values.
Evaluate just the constraint function values using the attributes
decision_vectors and objective_vectors
Raises:
NotImplementedError
Note:
Currently not supported by ScalarMOProblem
"""
raise NotImplementedError("Not implemented for ScalarMOProblem")
# TODO: Depreciate. Use data problem in the future
class ScalarDataProblem(ProblemBase):
"""A problem class for case where the data is pre-computed.
To be depreciated
Defines a problem with pre-computed data representing a multiobjective
optimization problem with scalar valued objective functions.
Arguments:
decision_vectors (np.ndarray): A 2D vector of decision_vectors. Each
row represents a solution with the value for each decision_vectors
defined on the columns.
objective_vectors (np.ndarray): A 2D vector of
objective function values. Each row represents one objective vector
with the values for the invidual objective functions defined on the
columns.
Attributes:
decision_vectors (np.ndarray): See args
objective_vectors (np.ndarray): See args
__epsilon (float): A small floating point number to shift the bounds of
the variables. See, get_variable_bounds, default value 1e-6
__constraints (List[ScalarConstraint]): A list of defined constraints.
nadir (np.ndarray): The nadir point of the problem.
ideal (np.ndarray): The ideal point of the problem.
__model_exists (bool): is there a model for this problem
Note:
It is assumed that the decision_vectors and objectives follow a direct
one-to-one mapping, i.e., the objective values on the ith row in
'objectives' should represent the solution of the multiobjective
problem when evaluated with the decision_vectors on the ith row in
'decision_vectors'.
"""
def __init__(self, decision_vectors: np.ndarray, objective_vectors: np.ndarray):
super().__init__()
self.decision_vectors: np.ndarray = decision_vectors
self.objective_vectors: np.ndarray = objective_vectors
# epsilon is used when computing the bounds. We don't want to exclude
# any of the solutions that contain border values.
# See get_variable_bounds
self.__epsilon: float = 1e-6
# Used to indicate if a model has been built to represent the model.
# Used in the evaluation.
self.__model_exists: bool = False
self.__constraints: List[ScalarConstraint] = []
try:
self.n_of_variables = self.decision_vectors.shape[1]
except IndexError as e:
msg = (
"Check the variable dimensions. Is it a 2D array? "
"Encountered '{}'".format(str(e))
)
raise ProblemError(msg)
try:
self.n_of_objectives = self.objective_vectors.shape[1]
except IndexError as e:
msg = (
"Check the objective dimensions. Is it a 2D array? "
"Encountered '{}'".format(str(e))
)
raise ProblemError(msg)
self.nadir = np.max(self.objective_vectors, axis=0)
self.ideal = np.min(self.objective_vectors, axis=0)
@property
def epsilon(self) -> float:
"""Property: epsilon.
Return:
float: epsilon value (for shifting the bounds of variables)
"""
return self.__epsilon
@epsilon.setter
def epsilon(self, val: float):
"""Setter: epsilon.
Argument:
val (float): epsilon value (for shifting the bounds of variables.)
"""
self.__epsilon = val
@property
def constraints(self) -> List[ScalarConstraint]:
"""Property: Constraints.
Return:
List[ScalarConstraint]: list of the defined constraints
"""
return self.__constraints
@constraints.setter
def constraints(self, val: List[ScalarConstraint]):
"""Setter: Constraints.
Argument:
val (List[ScalarConstraint]): list of the constraints.
"""
self.__constraints = val
def get_variable_bounds(self):
"""Get the variable bounds.
Returns:
np.array[float]: The variable bounds in a stack. The epsilon value
will be added to the upper bounds and substracted from the
lower bounds to return closed bounds.
Note:
If self.epsilon is zero, the bounds will represent an open range.
"""
return np.stack(
(
np.min(self.decision_vectors, axis=0) - self.epsilon,
np.max(self.decision_vectors, axis=0) + self.epsilon,
),
axis=1,
)
def evaluate_constraint_values(self) -> Optional[np.ndarray]:
"""Evaluate the constraint values.
Evaluate the constraint values for each defined constraint. A positive value indicates that a constraint is adhered to, a negative
value indicates a violated constraint.
Returns:
Optional[np.ndarray]: A 2D array with each row representing the
constraint values for different objective vectors. One column for
each constraint. If no constraint function are defined, returns
None.
"""
if len(self.constraints) == 0:
return None
constraint_values = np.zeros(
(len(self.objective_vectors), len(self.constraints))
)
for ind, con in enumerate(self.constraints):
constraint_values[:, ind] = con.evaluate(
self.decision_vectors, self.objective_vectors
)
return constraint_values
def evaluate(self, decision_vectors: np.ndarray) -> np.ndarray:
"""Evaluate the values of the objectives at the given decision.
Evaluate the values of the objectives corresponding to the decision
decision_vectors.
Args:
decision_vectors (np.ndarray): A 2D array with the decision
decision_vectors to be evaluated on each row.
Returns:
nd.ndarray: A 2D array with the objective values corresponding to
each decision vectors on the rows.
Note:
At the moment, this function just maps the given decision
decision_vectors to the closest decision variable present (using an
L2 distance) in the problem and returns the corresponsing objective
vector.
"""
if not self.__model_exists:
idx = np.unravel_index(
np.linalg.norm(
self.decision_vectors - decision_vectors, axis=1
).argmin(),
self.objective_vectors.shape,
order="F",
)[0]
else:
msg = "Models not implemented yet for data based problems."
raise NotImplementedError(msg)
return (self.objective_vectors[idx],)
class MOProblem(ProblemBase):
"""An user defined multiobjective optimization problem.
A multiobjective optimization problem with user defined objective
functions, constraints, and variables.
Arguments:
objectives (List[Union[ScalarObjective, VectorObjective]]): A list
containing the objectives of the problem.
variables (List[Variable]): A list containing the variables of
the problem.
constraints (List[ScalarConstraint]): A list of the constraints
of the problem.
nadir (Optional[np.ndarray], optional): Nadir point of the problem.
Defaults to None.
ideal (Optional[np.ndarray], optional): Ideal point of the problem.
Defaults to None.
Attributes:
__objectives (List[Union[ScalarObjective, VectorObjective]]): A list
containing the objectives of the problem.
__variables (List[Variable]): A list containing the variables of
the problem.
__constraints (List[ScalarConstraint]): A list of the constraints
of the problem.
__nadir (Optional[np.ndarray], optional): Nadir point of the problem.
Defaults to None.
__ideal (Optional[np.ndarray], optional): Ideal point of the problem.
Defaults to None.
__n_of_variables (int): The number of variables
__n_of_objectives (int): The number of objectives
Raises:
ProblemError: If ideal or nadir vectors are not the same size as
number of objectives.
"""
#TODO: use_surrogate : Union[bool, List[bool]]
def __init__(
self,
objectives: List[Union[ScalarObjective, VectorObjective]],
variables: List[Variable],
constraints: List[ScalarConstraint] = None,
nadir: Optional[np.ndarray] = None,
ideal: Optional[np.ndarray] = None,
):
super().__init__()
self.__objectives: List[Union[ScalarObjective, VectorObjective]] = objectives
self.__variables: List[Variable] = variables
self.__constraints: List[ScalarConstraint] = constraints
self.__n_of_variables: int = len(self.variables)
self.__n_of_objectives: int = sum(
map(self.number_of_objectives, self.__objectives)
)
if self.constraints is not None:
self.__n_of_constraints: int = len(self.constraints)
else:
self.__n_of_constraints = 0
# Multiplier to convert maximization to minimization
max_multiplier = np.asarray([1, -1])
to_maximize = [objective.maximize for objective in objectives]
# Does not work
# to_maximize = sum(to_maximize, []) # To flatten the list
to_maximize = (
np.hstack(to_maximize) * 1
) # To flatten list and convert to zeros and ones
# to_maximize = np.asarray(to_maximize) * 1 # Convert to zeros and ones
self._max_multiplier = max_multiplier[to_maximize]
self.nadir_fitness = np.full(self.__n_of_objectives, np.inf, dtype=float)
self.nadir = self.nadir_fitness * self._max_multiplier
self.ideal_fitness = np.full(self.__n_of_objectives, np.inf, dtype=float)
self.ideal = self.ideal_fitness * self._max_multiplier
# Nadir vector must be the same size as the number of objectives
if nadir is not None:
if len(nadir) != self.n_of_objectives:
msg = (
"The length of the nadir vector does not match the"
"number of objectives: Length nadir {}, number of "
"objectives {}."
).format(len(nadir), self.n_of_objectives)
raise ProblemError(msg)
self.nadir = nadir
# Ideal vector must be the same size as the number of objectives
if ideal is not None:
if len(ideal) != self.n_of_objectives:
msg = (
"The length of the ideal vector does not match the"
"number of objectives: Length ideal {}, number of "
"objectives {}."
).format(len(ideal), self.n_of_objectives)
raise ProblemError(msg)
self.ideal = ideal
self.nadir_fitness = self.nadir * self._max_multiplier
self.ideal_fitness = self.ideal * self._max_multiplier
# Objective and variable names
self.objective_names = self.get_objective_names()
self.variable_names = self.get_variable_names()
@property
def n_of_constraints(self) -> int:
"""Property: number of constraints.
Returns:
int: Number of constraints
"""
return self.__n_of_constraints
@n_of_constraints.setter
def n_of_constraints(self, val: int):
"""Setter: number of constraints.
Arguments:
val (int): number of constraints
"""
self.__n_of_constraints = val
@property
def objectives(self) -> List[ScalarObjective]:
"""Property: list of objectives.
Returns:
List[ScalarObjective]: list of objectives
"""
return self.__objectives
@objectives.setter
def objectives(self, val: List[ScalarObjective]):
"""Setter: set list of objectives.
Arguments:
val (List[ScalarObjective]): List of objectives
"""
self.__objectives = val
@property
def variables(self) -> List[Variable]:
"""Property: List of variables
Returns:
List[Variable]: list of variables
"""
return self.__variables
@variables.setter
def variables(self, val: List[Variable]):
"""Setter: set list of variables.
Arguments:
val (List[Variable]): list of variables
"""
self.__variables = val
@property
def constraints(self) -> List[ScalarConstraint]:
"""Property: list of constraints.
Returns:
List[ScalarConstraint]: list of constraints
"""
return self.__constraints
@constraints.setter
def constraints(self, val: List[ScalarConstraint]):
"""Setter: list of constraints.
Arguments:
val (List[ScalarConstraint]): list of constraints
"""
self.__constraints = val
@property
def n_of_objectives(self) -> int:
"""Property: number of objectives.
Returns:
int: number of objectives
"""
return self.__n_of_objectives
@n_of_objectives.setter
def n_of_objectives(self, val: int):
"""Setter: number of objectives.
Arguments:
val (int): number of objectives