engibench 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- engibench/__init__.py +7 -0
- engibench/constraint.py +280 -0
- engibench/core.py +208 -0
- engibench/problems/__init__.py +1 -0
- engibench/problems/airfoil/__init__.py +5 -0
- engibench/problems/airfoil/pyopt_history.py +740 -0
- engibench/problems/airfoil/templates/airfoil_analysis.py +212 -0
- engibench/problems/airfoil/templates/airfoil_opt.py +330 -0
- engibench/problems/airfoil/templates/pre_process.py +86 -0
- engibench/problems/airfoil/utils.py +428 -0
- engibench/problems/airfoil/v0.py +620 -0
- engibench/problems/beams2d/__init__.py +5 -0
- engibench/problems/beams2d/backend.py +418 -0
- engibench/problems/beams2d/v0.py +368 -0
- engibench/problems/heatconduction2d/__init__.py +5 -0
- engibench/problems/heatconduction2d/templates/initialize_design_2d.py +62 -0
- engibench/problems/heatconduction2d/templates/optimize_heat_conduction_2d.py +233 -0
- engibench/problems/heatconduction2d/templates/simulate_heat_conduction_2d.py +232 -0
- engibench/problems/heatconduction2d/v0.py +295 -0
- engibench/problems/heatconduction3d/__init__.py +5 -0
- engibench/problems/heatconduction3d/templates/initialize_design_3d.py +64 -0
- engibench/problems/heatconduction3d/templates/optimize_heat_conduction_3d.py +259 -0
- engibench/problems/heatconduction3d/templates/simulate_heat_conduction_3d.py +237 -0
- engibench/problems/heatconduction3d/v0.py +320 -0
- engibench/problems/photonics2d/__init__.py +5 -0
- engibench/problems/photonics2d/backend.py +360 -0
- engibench/problems/photonics2d/dataset_slurm_test.py +257 -0
- engibench/problems/photonics2d/v0.py +746 -0
- engibench/problems/power_electronics/__init__.py +5 -0
- engibench/problems/power_electronics/data/5_4_3_6_10-dcdc_converter_1.net +49 -0
- engibench/problems/power_electronics/utils/__init__.py +0 -0
- engibench/problems/power_electronics/utils/config.py +122 -0
- engibench/problems/power_electronics/utils/constants.py +5 -0
- engibench/problems/power_electronics/utils/netlist_handler.py +154 -0
- engibench/problems/power_electronics/utils/ngspice.py +162 -0
- engibench/problems/power_electronics/utils/process_log_file.py +19 -0
- engibench/problems/power_electronics/utils/process_sweep_data.py +25 -0
- engibench/problems/power_electronics/v0.py +261 -0
- engibench/problems/thermoelastic2d/__init__.py +5 -0
- engibench/problems/thermoelastic2d/model/__init__.py +0 -0
- engibench/problems/thermoelastic2d/model/fea_model.py +375 -0
- engibench/problems/thermoelastic2d/model/fem_matrix_builder.py +65 -0
- engibench/problems/thermoelastic2d/model/fem_setup.py +245 -0
- engibench/problems/thermoelastic2d/model/mma_subroutine.py +133 -0
- engibench/problems/thermoelastic2d/utils.py +169 -0
- engibench/problems/thermoelastic2d/v0.py +250 -0
- engibench/utils/__init__.py +0 -0
- engibench/utils/all_problems.py +35 -0
- engibench/utils/container.py +280 -0
- engibench/utils/files.py +83 -0
- engibench/utils/slurm.py +311 -0
- engibench-0.0.1.dist-info/METADATA +164 -0
- engibench-0.0.1.dist-info/RECORD +56 -0
- engibench-0.0.1.dist-info/WHEEL +5 -0
- engibench-0.0.1.dist-info/licenses/LICENSE +674 -0
- engibench-0.0.1.dist-info/top_level.txt +1 -0
engibench/__init__.py
ADDED
engibench/constraint.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Constraints for parameters of Problem classes."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Iterable
|
|
4
|
+
import dataclasses
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from dataclasses import is_dataclass
|
|
7
|
+
from enum import auto
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from enum import Flag
|
|
10
|
+
import inspect
|
|
11
|
+
import typing
|
|
12
|
+
from typing import Any, ClassVar, overload, TypeVar
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
Check = Callable[..., None]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Category(Flag):
|
|
20
|
+
"""Category of a constraint."""
|
|
21
|
+
|
|
22
|
+
Theory = auto()
|
|
23
|
+
Implementation = auto()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
IMPL = Category.Implementation
|
|
27
|
+
THEORY = Category.Theory
|
|
28
|
+
UNCATEGORIZED = Category(0)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Criticality(Enum):
|
|
32
|
+
"""Criticality of a constraint violation."""
|
|
33
|
+
|
|
34
|
+
Error = auto()
|
|
35
|
+
Warning = auto()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Constraint:
|
|
40
|
+
"""Constraint for parameters passed to e.g. :method:`engibench.core.Problem.optimize()`."""
|
|
41
|
+
|
|
42
|
+
check: Check
|
|
43
|
+
"""Check callback raising an AssertError if the constraint is violated."""
|
|
44
|
+
categories: Category = UNCATEGORIZED
|
|
45
|
+
"""Categories of the constraint."""
|
|
46
|
+
criticality: Criticality = Criticality.Error
|
|
47
|
+
"""Criticality of a violation of the constraint."""
|
|
48
|
+
|
|
49
|
+
def category(self, category: Category) -> "Constraint":
|
|
50
|
+
"""Return a copy of the constraint which has the specified category added."""
|
|
51
|
+
return Constraint(check=self.check, criticality=self.criticality, categories=self.categories | category)
|
|
52
|
+
|
|
53
|
+
def warning(self) -> "Constraint":
|
|
54
|
+
"""Return a copy of the constraint with the criticality level set to "warning"."""
|
|
55
|
+
return Constraint(check=self.check, criticality=Criticality.Warning, categories=self.categories)
|
|
56
|
+
|
|
57
|
+
def check_dict(self, parameter_args: dict[str, Any]) -> "Violation | None":
|
|
58
|
+
"""Check for a violation of the given constraint for the given parameters."""
|
|
59
|
+
# We first inspect the arguments of check callback:
|
|
60
|
+
sig = inspect.signature(self.check)
|
|
61
|
+
required_args = {
|
|
62
|
+
p.name
|
|
63
|
+
for p in sig.parameters.values()
|
|
64
|
+
if p.default is p.empty and p.kind not in {p.VAR_KEYWORD, p.VAR_POSITIONAL}
|
|
65
|
+
}
|
|
66
|
+
missing_args = frozenset(required_args) - frozenset(parameter_args)
|
|
67
|
+
if missing_args:
|
|
68
|
+
msg = f"Missing argument(s) {', '.join(missing_args)} for constraint {self.check.__name__}"
|
|
69
|
+
raise TypeError(msg)
|
|
70
|
+
|
|
71
|
+
# If self.check() accepts `**kwargs`, we feed in **parameter_args:
|
|
72
|
+
if any(p.kind is p.VAR_KEYWORD for p in sig.parameters.values()):
|
|
73
|
+
constraint_args = parameter_args
|
|
74
|
+
# Otherwise, we only feed in parameters defined in the signature:
|
|
75
|
+
else:
|
|
76
|
+
constraint_args = {param: value for param, value in parameter_args.items() if param in sig.parameters}
|
|
77
|
+
try:
|
|
78
|
+
self.check(**constraint_args)
|
|
79
|
+
except AssertionError as e:
|
|
80
|
+
return Violation(self, str(e))
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
def check_value(self, value: Any) -> "Violation | None":
|
|
84
|
+
"""Check for a violation for the given single positional value."""
|
|
85
|
+
try:
|
|
86
|
+
self.check(value)
|
|
87
|
+
except AssertionError as e:
|
|
88
|
+
return Violation(self, str(e))
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@overload
|
|
93
|
+
def constraint(check: Check, /) -> Constraint: ...
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@overload
|
|
97
|
+
def constraint(
|
|
98
|
+
*, categories: Category = UNCATEGORIZED, criticality: Criticality = Criticality.Error
|
|
99
|
+
) -> Callable[[Check], Constraint]: ...
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def constraint(
|
|
103
|
+
check: Check | None = None,
|
|
104
|
+
/,
|
|
105
|
+
*,
|
|
106
|
+
categories: Category = UNCATEGORIZED,
|
|
107
|
+
criticality: Criticality = Criticality.Error,
|
|
108
|
+
) -> Callable[[Check], Constraint] | Constraint:
|
|
109
|
+
"""Decorator for check callbacks to convert the callback to a :class:`Constraint`."""
|
|
110
|
+
if check is not None:
|
|
111
|
+
return Constraint(check)
|
|
112
|
+
|
|
113
|
+
def decorator(check: Check) -> Constraint:
|
|
114
|
+
return Constraint(check, categories=categories, criticality=criticality)
|
|
115
|
+
|
|
116
|
+
return decorator
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Var:
|
|
120
|
+
"""Helper class to bind variable names to a constraint."""
|
|
121
|
+
|
|
122
|
+
def __init__(self, *names: str) -> None:
|
|
123
|
+
self.names = names
|
|
124
|
+
|
|
125
|
+
def check(self, constraint: Constraint) -> Constraint:
|
|
126
|
+
"""Bind the variable names to `constraint`."""
|
|
127
|
+
name = "_".join([*self.names, constraint.check.__name__])
|
|
128
|
+
|
|
129
|
+
def extracting_check(**kwargs) -> None:
|
|
130
|
+
try:
|
|
131
|
+
values = [kwargs[name] for name in self.names]
|
|
132
|
+
except KeyError as e:
|
|
133
|
+
msg = f"Missing argument {e} for constraint {name}"
|
|
134
|
+
raise AssertionError(msg) from None
|
|
135
|
+
constraint.check(*values)
|
|
136
|
+
|
|
137
|
+
extracting_check.__name__ = name
|
|
138
|
+
return dataclasses.replace(constraint, check=extracting_check)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass
|
|
142
|
+
class Violation:
|
|
143
|
+
"""Representation of a violation of a constraint."""
|
|
144
|
+
|
|
145
|
+
constraint: Constraint
|
|
146
|
+
cause: str
|
|
147
|
+
|
|
148
|
+
def __str__(self) -> str:
|
|
149
|
+
return f"{self.constraint.check.__name__}: {self.cause}"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class Violations:
|
|
153
|
+
"""Filterable collection of :class:`Violation` instances returned by :function:`check_constraints`."""
|
|
154
|
+
|
|
155
|
+
def __init__(self, violations: list[Violation], n_constraints: int) -> None:
|
|
156
|
+
self.violations = violations
|
|
157
|
+
self.n_constraints = n_constraints
|
|
158
|
+
|
|
159
|
+
def by_category(self, category: Category) -> "Violations":
|
|
160
|
+
"""Filter the violations by the category of the constraint causing the violation."""
|
|
161
|
+
return Violations(
|
|
162
|
+
[violation for violation in self.violations if category in violation.constraint.categories], self.n_constraints
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
def by_criticality(self, criticality: Criticality) -> "Violations":
|
|
166
|
+
"""Filter the violations by criticality."""
|
|
167
|
+
return Violations(
|
|
168
|
+
[violation for violation in self.violations if violation.constraint.criticality == criticality],
|
|
169
|
+
self.n_constraints,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def __bool__(self) -> bool:
|
|
173
|
+
return bool(self.violations)
|
|
174
|
+
|
|
175
|
+
def __len__(self) -> int:
|
|
176
|
+
return len(self.violations)
|
|
177
|
+
|
|
178
|
+
def __str__(self) -> str:
|
|
179
|
+
return "\n".join(str(v) for v in self.violations)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
T = TypeVar("T", int, float)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def bounded(*, lower: T | None = None, upper: T | None = None) -> Constraint:
|
|
186
|
+
"""Create a constraint which checks that the specified parameter is contained in an interval `[lower, upper]`."""
|
|
187
|
+
|
|
188
|
+
def check(value: T) -> None:
|
|
189
|
+
msg = f"{value} ∉ [{lower if lower is not None else '-∞'}, {upper if upper is not None else '∞'}]"
|
|
190
|
+
assert lower is None or np.all(lower <= value), msg
|
|
191
|
+
assert upper is None or np.all(value <= upper), msg
|
|
192
|
+
|
|
193
|
+
return Constraint(check)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def greater_than(lower: T, /) -> Constraint:
|
|
197
|
+
"""Create a constraint which checks that the specified parameter is greater than `lower`."""
|
|
198
|
+
|
|
199
|
+
def check(value: T) -> None:
|
|
200
|
+
assert np.all(value > lower), f"{value} ∉ ({lower}, ∞)"
|
|
201
|
+
|
|
202
|
+
return Constraint(check)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def less_than(upper: T, /) -> Constraint:
|
|
206
|
+
"""Create a constraint which checks that the specified parameter is less than `upper`."""
|
|
207
|
+
|
|
208
|
+
def check(value: T) -> None:
|
|
209
|
+
assert np.all(value < upper), f"{value} ∉ (-∞, {upper})"
|
|
210
|
+
|
|
211
|
+
return Constraint(check)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def check_optimize_constraints(
|
|
215
|
+
constraints: Iterable[Constraint],
|
|
216
|
+
design: Any,
|
|
217
|
+
config: dict[str, Any],
|
|
218
|
+
) -> Violations:
|
|
219
|
+
"""Specifically check the arguments of :method:`engibench.core.Problem.optimize()`."""
|
|
220
|
+
return check_constraints(constraints, {"design": design, **config})
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def check_constraints(
|
|
224
|
+
constraints: Iterable[Constraint],
|
|
225
|
+
parameter_args: dict[str, Any],
|
|
226
|
+
) -> Violations:
|
|
227
|
+
"""Check for violations of the given constraints for the given parameters."""
|
|
228
|
+
constraints = list(constraints)
|
|
229
|
+
violations = [
|
|
230
|
+
violation
|
|
231
|
+
for violation in (constraint.check_dict(parameter_args) for constraint in constraints)
|
|
232
|
+
if violation is not None
|
|
233
|
+
]
|
|
234
|
+
return Violations(violations, len(constraints))
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def check_field_constraints(
|
|
238
|
+
data: Any,
|
|
239
|
+
) -> Violations:
|
|
240
|
+
"""Check for violations of constraints for fields of a dataclass which declare constraints via :function:`field_constraints`."""
|
|
241
|
+
assert is_dataclass(data)
|
|
242
|
+
assert not isinstance(data, type)
|
|
243
|
+
violations = []
|
|
244
|
+
n_constraints = 0
|
|
245
|
+
for f_name, constraint in field_constraints(data):
|
|
246
|
+
n_constraints += 1
|
|
247
|
+
violation = (
|
|
248
|
+
constraint.check_value(getattr(data, f_name))
|
|
249
|
+
if f_name is not None
|
|
250
|
+
else constraint.check_dict(dataclasses.asdict(data))
|
|
251
|
+
)
|
|
252
|
+
if violation is not None:
|
|
253
|
+
if f_name is not None:
|
|
254
|
+
violation = Violation(violation.constraint, f"{type(data).__name__}.{f_name}: {violation.cause}")
|
|
255
|
+
violations.append(violation)
|
|
256
|
+
|
|
257
|
+
return Violations(violations, n_constraints)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def field_constraints(data: Any) -> Iterable[tuple[str | None, Constraint]]:
|
|
261
|
+
"""Iterate over all constraints declared on the dataclass instance `data`."""
|
|
262
|
+
assert is_dataclass(data)
|
|
263
|
+
# Check for annotated ClassVar:
|
|
264
|
+
for f_name, f in data.__annotations__.items():
|
|
265
|
+
if typing.get_origin(f) is not ClassVar:
|
|
266
|
+
continue
|
|
267
|
+
try:
|
|
268
|
+
(annotation,) = typing.get_args(f)
|
|
269
|
+
except TypeError:
|
|
270
|
+
continue
|
|
271
|
+
yield from ((f_name, c) for c in getattr(annotation, "__metadata__", ()) if isinstance(c, Constraint))
|
|
272
|
+
for f in dataclasses.fields(data):
|
|
273
|
+
# Check for typing.Annotated:
|
|
274
|
+
yield from ((f.name, c) for c in getattr(f.type, "__metadata__", ()) if isinstance(c, Constraint))
|
|
275
|
+
yield from ((None, c) for c in vars(type(data)).values() if isinstance(c, Constraint))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def count_field_constraints(data: Any) -> int:
|
|
279
|
+
"""Return the number of constraints declared on the dataclass `data`."""
|
|
280
|
+
return len(list(field_constraints(data)))
|
engibench/core.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Core API for Problem and other base classes."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
import dataclasses
|
|
5
|
+
from enum import auto
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any, Generic, TypeVar
|
|
8
|
+
|
|
9
|
+
from datasets import Dataset
|
|
10
|
+
from datasets import load_dataset
|
|
11
|
+
from gymnasium import spaces
|
|
12
|
+
import numpy as np
|
|
13
|
+
import numpy.typing as npt
|
|
14
|
+
|
|
15
|
+
from engibench import constraint
|
|
16
|
+
|
|
17
|
+
DesignType = TypeVar("DesignType")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclasses.dataclass
|
|
21
|
+
class OptiStep:
|
|
22
|
+
"""Optimization step."""
|
|
23
|
+
|
|
24
|
+
obj_values: npt.NDArray
|
|
25
|
+
step: int
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ObjectiveDirection(Enum):
|
|
29
|
+
"""Direction of the objective function."""
|
|
30
|
+
|
|
31
|
+
MINIMIZE = auto()
|
|
32
|
+
MAXIMIZE = auto()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Problem(Generic[DesignType]):
|
|
36
|
+
r"""Main class for defining an engineering design problem.
|
|
37
|
+
|
|
38
|
+
This class assumes there is:
|
|
39
|
+
|
|
40
|
+
- an underlying simulator that is called to evaluate the performance of a design (see `simulate` method);
|
|
41
|
+
- a dataset containing representations of designs and their performances (see `design_space`, `dataset_id` attributes);
|
|
42
|
+
|
|
43
|
+
The main API methods that users should use are:
|
|
44
|
+
|
|
45
|
+
- :meth:`check_constraints` - to check if a design and conditions violate any constraints.
|
|
46
|
+
- :meth:`simulate` - to simulate a design and return the performance given some conditions.
|
|
47
|
+
- :meth:`optimize` - to optimize a design starting from a given point, e.g., using adjoint solver included inside the simulator.
|
|
48
|
+
- :meth:`reset` - to reset the simulator and numpy random to a given seed.
|
|
49
|
+
- :meth:`render` - to render a design in a human-readable format.
|
|
50
|
+
- :meth:`random_design` - to generate a valid random design.
|
|
51
|
+
|
|
52
|
+
There are some attributes that help understanding the problem:
|
|
53
|
+
|
|
54
|
+
- :attr:`objectives` - a dictionary with the names of the objectives and their types (minimize or maximize).
|
|
55
|
+
- :attr:`conditions` - the conditions for the design problem.
|
|
56
|
+
- :attr:`design_space` - the space of designs (outputs of algorithms).
|
|
57
|
+
- :attr:`dataset_id` - a string identifier for the problem -- useful to pull datasets.
|
|
58
|
+
- :attr:`dataset` - the dataset with designs and performances.
|
|
59
|
+
- :attr:`container_id` - a string identifier for the singularity container.
|
|
60
|
+
|
|
61
|
+
Having all these defined in the code allows to easily extract the columns we want from the dataset to train ML models.
|
|
62
|
+
|
|
63
|
+
Note:
|
|
64
|
+
This class is generic and should be subclassed to define the specific problem.
|
|
65
|
+
|
|
66
|
+
Note:
|
|
67
|
+
This class is parameterized with `DesignType` is the type of the design that is optimized (e.g. a Numpy array representing the design).
|
|
68
|
+
|
|
69
|
+
Note:
|
|
70
|
+
Some simulators also ask for simulator related configurations. These configurations are generally defined in the
|
|
71
|
+
problem implementation, do not appear in the `problem.conditions`, but sometimes appear in the dataset (for
|
|
72
|
+
advanced usage). You can override them by using the `config` argument in the `simulate` or `optimize` method.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
# Must be defined in subclasses
|
|
76
|
+
version: int
|
|
77
|
+
"""Version of the problem"""
|
|
78
|
+
objectives: tuple[tuple[str, ObjectiveDirection], ...]
|
|
79
|
+
"""Objective names and types (minimize or maximize)"""
|
|
80
|
+
conditions: tuple[tuple[str, Any], ...]
|
|
81
|
+
"""Conditions for the design problem"""
|
|
82
|
+
design_space: spaces.Space[DesignType]
|
|
83
|
+
"""Design space (algorithm output)"""
|
|
84
|
+
dataset_id: str
|
|
85
|
+
"""String identifier for the problem (useful to pull datasets)"""
|
|
86
|
+
design_constraints: tuple[constraint.Constraint, ...] = ()
|
|
87
|
+
"""Additional constraints for designs"""
|
|
88
|
+
_dataset: Dataset | None = None
|
|
89
|
+
"""Dataset with designs and performances"""
|
|
90
|
+
container_id: str | None
|
|
91
|
+
"""String identifier for the singularity container"""
|
|
92
|
+
Config: type | None = None
|
|
93
|
+
"""Dataclass declaring types, defaults (optional) and constraints"""
|
|
94
|
+
|
|
95
|
+
# This handles the RNG properly
|
|
96
|
+
np_random: np.random.Generator
|
|
97
|
+
|
|
98
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
99
|
+
"""Initialize the problem.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
**kwargs: Keyword arguments.
|
|
103
|
+
"""
|
|
104
|
+
self.reset(**kwargs)
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def dataset(self) -> Dataset:
|
|
108
|
+
"""Pulls the dataset if it is not already loaded."""
|
|
109
|
+
if self._dataset is None:
|
|
110
|
+
self._dataset = load_dataset(self.dataset_id)
|
|
111
|
+
return self._dataset
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def conditions_dict(self) -> dict[str, Any]:
|
|
115
|
+
"""Returns the conditions as a dictionary."""
|
|
116
|
+
return dict(self.conditions)
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def conditions_keys(self) -> list[str]:
|
|
120
|
+
"""Returns the condition names as a list."""
|
|
121
|
+
return [name for name, _ in self.conditions]
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def objectives_keys(self) -> list[str]:
|
|
125
|
+
"""Returns the objective names as a list."""
|
|
126
|
+
return [name for name, _ in self.objectives]
|
|
127
|
+
|
|
128
|
+
def simulate(self, design: DesignType, config: dict[str, Any] | None = None) -> npt.NDArray:
|
|
129
|
+
r"""Launch a simulation on the given design and return the performance.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
design (DesignType): The design to simulate.
|
|
133
|
+
config (dict): A dictionary with configuration (e.g., boundary conditions, filenames) for the optimization.
|
|
134
|
+
**kwargs: Additional keyword arguments.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
np.array: The performance of the design -- each entry corresponds to an objective value.
|
|
138
|
+
"""
|
|
139
|
+
raise NotImplementedError
|
|
140
|
+
|
|
141
|
+
def optimize(
|
|
142
|
+
self, starting_point: DesignType, config: dict[str, Any] | None = None
|
|
143
|
+
) -> tuple[DesignType, Sequence[OptiStep]]:
|
|
144
|
+
r"""Some simulators have built-in optimization. This function optimizes the design starting from `starting_point`.
|
|
145
|
+
|
|
146
|
+
This is optional and will probably be implemented only for some problems.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
starting_point (DesignType): The starting point for the optimization.
|
|
150
|
+
config (dict): A dictionary with configuration (e.g., boundary conditions, filenames) for the optimization.
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
Tuple[DesignType, list[OptiStep]]: The optimized design and the optimization history.
|
|
154
|
+
"""
|
|
155
|
+
raise NotImplementedError
|
|
156
|
+
|
|
157
|
+
def reset(self, seed: int | None = None) -> None:
|
|
158
|
+
r"""Reset the simulator and numpy random to a given seed.
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
seed (int, optional): The seed to reset to. If None, a random seed is used.
|
|
162
|
+
"""
|
|
163
|
+
self.seed = seed
|
|
164
|
+
self.np_random = np.random.default_rng(seed)
|
|
165
|
+
|
|
166
|
+
def render(self, design: DesignType, *, open_window: bool = False) -> Any:
|
|
167
|
+
r"""Render the design in a human-readable format.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
design (DesignType): The design to render.
|
|
171
|
+
open_window (bool): Whether to open a window to display the design.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
Any: The rendered design.
|
|
175
|
+
"""
|
|
176
|
+
raise NotImplementedError
|
|
177
|
+
|
|
178
|
+
def random_design(self) -> tuple[DesignType, int]:
|
|
179
|
+
r"""Generate a random design.
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
DesignType: The random design.
|
|
183
|
+
idx: The index of the design in the dataset.
|
|
184
|
+
"""
|
|
185
|
+
raise NotImplementedError
|
|
186
|
+
|
|
187
|
+
def check_constraints(self, design: DesignType, config: dict[str, Any]) -> constraint.Violations:
|
|
188
|
+
"""Check if config and design violate any constraints declared in `Config` and `design_space`.
|
|
189
|
+
|
|
190
|
+
Return a :class:`constraint.Violations` object containing all violations.
|
|
191
|
+
"""
|
|
192
|
+
if self.Config is not None:
|
|
193
|
+
checked_config = self.Config(**config)
|
|
194
|
+
violations = constraint.check_field_constraints(checked_config)
|
|
195
|
+
else:
|
|
196
|
+
violations = constraint.Violations([], 0)
|
|
197
|
+
|
|
198
|
+
@constraint.constraint
|
|
199
|
+
def design_constraint(design: DesignType) -> None:
|
|
200
|
+
assert self.design_space.contains(design), "design ∉ design_space"
|
|
201
|
+
|
|
202
|
+
violations.n_constraints += 1 + len(self.design_constraints)
|
|
203
|
+
for c in (design_constraint, *self.design_constraints):
|
|
204
|
+
design_violation = c.check_dict({"design": design, **config})
|
|
205
|
+
if design_violation is not None:
|
|
206
|
+
violations.violations.append(design_violation)
|
|
207
|
+
|
|
208
|
+
return violations
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Contains all the different problems modeled in the library."""
|