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