Skip to content

Bayesian-optimization layer

BayesianOptimizer runs one of these GEMSEO libraries. BaseBOLibrary owns everything that must not depend on the backend; a backend only implements _setup, _ask and _tell.

Algorithm Library Backend
Ax_Bayesian (default) AxOptimizationLibrary Ax: Sobol for n_init trials, then BoTorch.
BO_RandomSearch RandomSearchLibrary Seeded uniform sampling (log-uniform for scaling="log"), the reference backend of the tests.

Driver

mdo_framework.optimization.bo_library

This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

BaseBOLibrary

Bases: BaseOptimizationLibrary

GEMSEO driver running an ask-evaluate-tell loop for any backend.

The driver owns everything that must not depend on the backend: the budget, the time limit, the guarded start point, the classification of failures, the bindings between user names and GEMSEO functions, and the feasibility of a trial. A backend only proposes candidates and learns their outcome. It never sees GEMSEO names or NaN, never decides to stop and never evaluates x0.

Attributes:

Name Type Description
result BORunResult | None

Outcome of the last run, set even when the run is aborted.

Source code in src/mdo_framework/optimization/bo_library.py
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
class BaseBOLibrary(BaseOptimizationLibrary):
    """GEMSEO driver running an ask-evaluate-tell loop for any backend.

    The driver owns everything that must not depend on the backend: the
    budget, the time limit, the guarded start point, the classification of
    failures, the bindings between user names and GEMSEO functions, and the
    feasibility of a trial. A backend only proposes candidates and learns
    their outcome. It never sees GEMSEO names or NaN, never decides to stop
    and never evaluates x0.

    Attributes:
        result: Outcome of the last run, set even when the run is aborted.
    """

    MAX_STALLED_GENERATIONS = 5
    """Generations adding no new evaluation that end the run."""

    def __init__(self, algo_name: str) -> None:
        super().__init__(algo_name=algo_name)
        self.result: BORunResult | None = None
        self._space: BOSpace | None = None
        self._bindings: tuple[MetricBinding, ...] = ()
        self._start: dict[str, Any] = {}
        self._records: list[TrialRecord] = []
        self._outcomes: dict[tuple[float, ...], TrialOutcome] = {}

    @abstractmethod
    def _setup(
        self,
        space: BOSpace,
        bindings: tuple[MetricBinding, ...],
        prior: tuple[TrialRecord, ...],
    ) -> None:
        """Prepare the backend before the first ask.

        Args:
            space: Design space of the run.
            bindings: Objectives and constraints, by user name.
            prior: Trials already evaluated: the start point, if any.
        """

    @abstractmethod
    def _ask(self, n: int) -> list[Candidate]:
        """Propose candidates.

        Args:
            n: Maximum number of candidates to propose.

        Returns:
            At most ``n`` candidates, none if the backend has nothing to
            propose. More are tolerated: the driver abandons the surplus.
        """

    @abstractmethod
    def _tell(self, candidate: Candidate, outcome: TrialOutcome) -> None:
        """Report what became of a candidate.

        Args:
            candidate: Candidate returned by ``_ask``.
            outcome: Its outcome. A failed one has no metrics, an abandoned one
                was never evaluated. A candidate already evaluated gets the
                outcome it had.
        """

    def _check_stopping_criteria(self) -> None:
        BaseDriverLibrary._check_stopping_criteria(self)

    def _finalize_previous_iteration(self) -> None:
        # GEMSEO updates its progress bar from the last stored point, and a
        # failed evaluation stores none: an empty database must not abort.
        if len(self._problem.database) == 0:
            self._problem.evaluation_counter.current += 1
            return
        super()._finalize_previous_iteration()

    def _pre_run(self, problem: OptimizationProblem) -> None:
        settings = self._settings
        self.result = None
        self._records = []
        self._outcomes = {}
        self._bindings = build_metric_bindings(
            problem, settings.objectives, settings.constraints
        )
        self._space = self._build_space()
        self._start = self._space.start_point()
        problem.design_space.set_current_value(self._space.to_vector(self._start))
        problem.stop_if_nan = False
        self._check_constraints_handling(problem)
        self._init_iter_observer(
            problem,
            settings.max_iter,
            message="",
            progress_bar_data_name=settings.progress_bar_data_name,
        )

    def _build_space(self) -> BOSpace:
        settings = self._settings
        try:
            linear_constraints = parse_parameter_constraints(
                settings.parameter_constraints, settings.design_variables
            )
        except ParameterConstraintError as error:
            raise OptimizationConfigurationError(str(error)) from error
        return BOSpace(
            design_variables=settings.design_variables,
            linear_constraints=tuple(linear_constraints),
            parameter_constraints=settings.parameter_constraints,
        )

    def _run(self, problem: OptimizationProblem) -> tuple[Any, Any]:
        stop_reason: StopReason = "aborted"
        try:
            stop_reason = self._drive()
        finally:
            self.result = BORunResult(tuple(self._records), stop_reason, self._bindings)
        return f"Optimization stopped: {stop_reason}.", None

    def _drive(self) -> StopReason:
        settings = self._settings
        counter = self._problem.evaluation_counter
        if settings.x0_enabled:
            stop = self._try(Candidate(self._start), "x0")
            if stop is not None:
                return stop
        self._setup(self._space, self._bindings, tuple(self._records))
        cardinality = self._space.cardinality()
        stalled = 0
        while True:
            remaining = settings.max_iter - _evaluations_done(counter)
            if remaining <= 0:
                return "budget"
            if cardinality is not None and len(self._outcomes) >= cardinality:
                return "search_space_exhausted"
            requested = min(settings.batch_size, remaining)
            candidates = self._ask(requested)
            evaluated = _evaluations_done(counter)
            stop: StopReason | None = None
            for position, candidate in enumerate(candidates):
                if position >= requested:
                    self._abandon(candidate, "surplus")
                elif stop is None:
                    stop = self._try(candidate, self._next_phase())
                else:
                    self._abandon(candidate, stop)
            if stop is not None:
                return stop
            stalled = 0 if _evaluations_done(counter) > evaluated else stalled + 1
            if stalled >= self.MAX_STALLED_GENERATIONS:
                return "search_space_exhausted"

    def _next_phase(self) -> Phase:
        # Only evaluated candidates use the initial design's slots.
        started = sum(
            1
            for record in self._records
            if record.phase != "x0" and record.outcome.status != "abandoned"
        )
        return "init" if started < self._settings.n_init else "bo"

    def _try(self, candidate: Candidate, phase: Phase) -> StopReason | None:
        """Evaluate a candidate, record it, and tell the backend.

        A point already evaluated in this run, successfully or not, is not
        evaluated again, nor recorded: the backend is told the outcome it had.
        A point GEMSEO's database already holds from an earlier run is not
        recorded either. An abandoned point was never evaluated, so proposing
        it again within the request evaluates it.

        Returns:
            The reason to stop the run, ``None`` to go on.
        """
        key = tuple(self._space.to_vector(candidate.parameters).tolist())
        if (known := self._outcomes.get(key)) is not None:
            if phase != "x0":
                self._tell(candidate, known)
            return None
        counter = self._problem.evaluation_counter
        before = _evaluations_done(counter)
        stop: StopReason | None = None
        try:
            outcome = self._evaluate(candidate)
        except MaxIterReachedException:  # pragma: no cover
            # Safety net: the loop never asks for more than the remaining
            # budget, so GEMSEO's own budget signal is not expected here.
            stop = "budget"
        except MaxTimeReached:
            stop = "max_time"
        if stop is not None:
            self._abandon(candidate, stop, phase)
            return stop
        self._outcomes[key] = outcome
        if _evaluations_done(counter) > before:
            self._records.append(
                TrialRecord(len(self._records), phase, candidate.parameters, outcome)
            )
        if phase != "x0":
            self._tell(candidate, outcome)
        if self._failures_in_a_row() >= self._settings.max_consecutive_failures:
            return "consecutive_failures"
        return None

    def _abandon(
        self, candidate: Candidate, reason: str, phase: Phase | None = None
    ) -> None:
        """Record and tell a candidate that will not be evaluated.

        Args:
            candidate: The candidate.
            reason: Why: the stop reason of the run, or ``"surplus"`` for a
                candidate beyond the number requested from the backend.
            phase: Phase of the candidate, the next phase by default.
        """
        outcome = TrialOutcome("abandoned", reason=reason)
        phase = phase or self._next_phase()
        self._records.append(
            TrialRecord(len(self._records), phase, candidate.parameters, outcome)
        )
        if phase != "x0":
            self._tell(candidate, outcome)

    def _failures_in_a_row(self) -> int:
        # Abandoned candidates were never evaluated: they do not end a streak.
        count = 0
        for record in reversed(self._records):
            if record.outcome.status == "abandoned":
                continue
            if record.outcome.status != "failed":
                break
            count += 1
        return count

    def _evaluate(self, candidate: Candidate) -> TrialOutcome:
        x = self._space.to_vector(candidate.parameters)
        try:
            output_data, _ = self._problem.evaluate_functions(
                x, design_vector_is_normalized=False
            )
        except EvaluationError as error:
            return TrialOutcome("failed", reason=f"{error.code}: {error}")
        metrics = {
            binding.name: binding.user_value(output_data) for binding in self._bindings
        }
        invalid = [name for name, value in metrics.items() if not math.isfinite(value)]
        if invalid:
            return TrialOutcome(
                "failed", reason=f"NON_FINITE_OUTPUT: {', '.join(invalid)}"
            )
        return TrialOutcome("completed", metrics)

MAX_STALLED_GENERATIONS = 5 class-attribute instance-attribute

Generations adding no new evaluation that end the run.

BaseBOSettings

Bases: BaseOptimizerSettings

Settings shared by the backends of the Bayesian optimization driver.

The budget is set by the phases, never by max_iter: the run makes n_init initial trials and n_steps model-driven trials, after the start point x0 when it is evaluated. max_iter is derived from them and only accepted if it agrees. The GEMSEO tolerances ftol_*, xtol_* and scaling_threshold are ignored: only the budget and max_time stop a run, so a plateau never ends it early.

Attributes:

Name Type Description
design_variables tuple[DesignVariable, ...]

Design variables, in the order of the design space.

objectives tuple[ObjectiveSpec, ...]

Objectives, in the order of the objective function.

constraints tuple[ConstraintSpec, ...]

Inequality constraints, in the order they were added.

parameter_constraints tuple[str, ...]

Linear constraints between design variables.

n_init PositiveInt

Number of initial trials.

n_steps PositiveInt

Number of model-driven trials.

evaluate_x0 bool | None

Whether to evaluate x0 first. None evaluates it when every design variable declares an initial value.

seed int | None

Seed of the backend, None for a random one.

batch_size PositiveInt

Maximum number of candidates asked at once.

max_consecutive_failures PositiveInt

Failed trials in a row that end the run.

Source code in src/mdo_framework/optimization/bo_library.py
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
class BaseBOSettings(BaseOptimizerSettings):
    """Settings shared by the backends of the Bayesian optimization driver.

    The budget is set by the phases, never by ``max_iter``: the run makes
    ``n_init`` initial trials and ``n_steps`` model-driven trials, after the
    start point x0 when it is evaluated. ``max_iter`` is derived from them and
    only accepted if it agrees. The GEMSEO tolerances ``ftol_*``, ``xtol_*``
    and ``scaling_threshold`` are ignored: only the budget and ``max_time``
    stop a run, so a plateau never ends it early.

    Attributes:
        design_variables: Design variables, in the order of the design space.
        objectives: Objectives, in the order of the objective function.
        constraints: Inequality constraints, in the order they were added.
        parameter_constraints: Linear constraints between design variables.
        n_init: Number of initial trials.
        n_steps: Number of model-driven trials.
        evaluate_x0: Whether to evaluate x0 first. ``None`` evaluates it when
            every design variable declares an ``initial`` value.
        seed: Seed of the backend, ``None`` for a random one.
        batch_size: Maximum number of candidates asked at once.
        max_consecutive_failures: Failed trials in a row that end the run.
    """

    design_variables: tuple[DesignVariable, ...] = Field(min_length=1)
    objectives: tuple[ObjectiveSpec, ...] = Field(min_length=1)
    constraints: tuple[ConstraintSpec, ...] = ()
    parameter_constraints: tuple[str, ...] = ()
    n_init: PositiveInt = 5
    n_steps: PositiveInt = 10
    evaluate_x0: bool | None = None
    seed: int | None = None
    batch_size: PositiveInt = 1
    max_consecutive_failures: PositiveInt = 5
    ineq_tolerance: NonNegativeFloat = 0.0
    normalize_design_space: bool = False
    max_iter: PositiveInt = 1

    @property
    def x0_enabled(self) -> bool:
        """Whether x0 is evaluated."""
        if self.evaluate_x0 is not None:
            return self.evaluate_x0
        return all(variable.initial is not None for variable in self.design_variables)

    @model_validator(mode="after")
    def _derive_max_iter(self) -> "BaseBOSettings":
        budget = int(self.x0_enabled) + self.n_init + self.n_steps
        if "max_iter" in self.model_fields_set and self.max_iter != budget:
            raise ValueError(
                f"max_iter={self.max_iter} contradicts the phases, which make "
                f"{budget} evaluations: drop max_iter and set n_init and n_steps"
            )
        self.max_iter = budget
        return self

x0_enabled property

Whether x0 is evaluated.

add_constraints(scenario, constraints)

Add the constraints of a study to a GEMSEO scenario.

The tolerance is folded into the bound, so that GEMSEO, which runs with a zero tolerance, agrees with the feasibility of the library.

Parameters:

Name Type Description Default
scenario Any

GEMSEO scenario to add the constraints to.

required
constraints Sequence[ConstraintSpec]

Constraint declarations.

required
Source code in src/mdo_framework/optimization/bo_library.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def add_constraints(scenario: Any, constraints: Sequence[ConstraintSpec]) -> None:
    """Add the constraints of a study to a GEMSEO scenario.

    The tolerance is folded into the bound, so that GEMSEO, which runs with a
    zero tolerance, agrees with the feasibility of the library.

    Args:
        scenario: GEMSEO scenario to add the constraints to.
        constraints: Constraint declarations.
    """
    for spec in constraints:
        scenario.add_constraint(
            spec.name,
            constraint_type="ineq",
            value=gemseo_bound(spec),
            positive=spec.op == ">=",
        )

build_metric_bindings(problem, objectives, constraints)

Bind every user output to the GEMSEO function that computes it.

Parameters:

Name Type Description Default
problem OptimizationProblem

GEMSEO problem built from the study.

required
objectives Sequence[ObjectiveSpec]

Objective declarations, in the order of the objective.

required
constraints Sequence[ConstraintSpec]

Constraint declarations, in the order they were added.

required

Returns:

Type Description
tuple[MetricBinding, ...]

The objective bindings followed by the constraint bindings.

Raises:

Type Description
OptimizationConfigurationError

If the problem does not hold exactly these objectives and constraints.

Source code in src/mdo_framework/optimization/bo_library.py
 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
def build_metric_bindings(
    problem: OptimizationProblem,
    objectives: Sequence[ObjectiveSpec],
    constraints: Sequence[ConstraintSpec],
) -> tuple[MetricBinding, ...]:
    """Bind every user output to the GEMSEO function that computes it.

    Args:
        problem: GEMSEO problem built from the study.
        objectives: Objective declarations, in the order of the objective.
        constraints: Constraint declarations, in the order they were added.

    Returns:
        The objective bindings followed by the constraint bindings.

    Raises:
        OptimizationConfigurationError: If the problem does not hold exactly
            these objectives and constraints.
    """
    objective = problem.objective
    names = [spec.name for spec in objectives]
    if list(objective.output_names) != names:
        raise OptimizationConfigurationError(
            f"the objective of the problem computes {list(objective.output_names)}, "
            f"but the study declares the objectives {names}"
        )
    if len(problem.constraints) != len(constraints):
        raise OptimizationConfigurationError(
            f"the problem has {len(problem.constraints)} constraints, "
            f"but the study declares {len(constraints)}"
        )
    sign = 1.0 if problem.minimize_objective else -1.0
    bindings = [
        MetricBinding(
            name=spec.name,
            role="objective",
            gemseo_name=objective.name,
            index=index,
            sign=sign,
            minimize=spec.minimize,
            threshold=spec.threshold,
        )
        for index, spec in enumerate(objectives)
    ]
    for function, spec in zip(problem.constraints, constraints, strict=True):
        if list(function.output_names) != [spec.name]:
            raise OptimizationConfigurationError(
                f"the constraint {function.name!r} computes "
                f"{list(function.output_names)}, but the study declares the "
                f"constraint {spec.name!r} at this position"
            )
        bindings.append(
            MetricBinding(
                name=spec.name,
                role="constraint",
                gemseo_name=function.name,
                index=0,
                sign=1.0 if spec.op == "<=" else -1.0,
                offset=gemseo_bound(spec),
                op=spec.op,
                bound=spec.bound,
                tolerance=spec.tolerance,
                scale=spec.scale or 1.0,
            )
        )
    return tuple(bindings)

Types

mdo_framework.optimization.bo_types

This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

MAX_ENUMERATED_POINTS = 100000 module-attribute

Largest discrete space whose points are checked against the constraints.

BORunResult dataclass

Outcome of a Bayesian optimization run.

Attributes:

Name Type Description
records Sequence[TrialRecord]

Every trial, in run order.

stop_reason StopReason

Why the run stopped.

bindings Sequence[MetricBinding]

Objective and constraint bindings of the run.

Source code in src/mdo_framework/optimization/bo_types.py
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
@dataclass(frozen=True)
class BORunResult:
    """Outcome of a Bayesian optimization run.

    Attributes:
        records: Every trial, in run order.
        stop_reason: Why the run stopped.
        bindings: Objective and constraint bindings of the run.
    """

    records: Sequence[TrialRecord]
    stop_reason: StopReason
    bindings: Sequence[MetricBinding]

    @property
    def evaluations(self) -> dict[str, int]:
        """Evaluations per phase, which exclude abandoned trials, and failures."""
        evaluated = [r for r in self.records if r.outcome.status != "abandoned"]
        counts = {
            phase: sum(record.phase == phase for record in evaluated)
            for phase in ("x0", "init", "bo")
        }
        counts["failed"] = sum(r.outcome.status == "failed" for r in self.records)
        return counts

    @property
    def best(self) -> TrialRecord | None:
        """The record to report, see ``select_best``."""
        return select_best(self.records, self.bindings)

    @property
    def pareto_front(self) -> list[TrialRecord]:
        """Feasible records not dominated by another, empty for one objective."""
        if len(_objectives(self.bindings)) < 2:
            return []
        return _pareto_front(self.records, self.bindings)

    @property
    def feasible(self) -> bool:
        """Whether the reported record respects every constraint."""
        best = self.best
        return best is not None and best.feasible(self.bindings)

best property

The record to report, see select_best.

evaluations property

Evaluations per phase, which exclude abandoned trials, and failures.

feasible property

Whether the reported record respects every constraint.

pareto_front property

Feasible records not dominated by another, empty for one objective.

BOSpace dataclass

Design space of a run: variables and linear constraints between them.

Attributes:

Name Type Description
design_variables tuple[DesignVariable, ...]

Range and choice variables, in schema order.

linear_constraints tuple[LinearConstraint, ...]

The parameter constraints, parsed.

parameter_constraints tuple[str, ...]

The same constraints as expressions, for backends that take them verbatim.

Source code in src/mdo_framework/optimization/bo_types.py
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
@dataclass(frozen=True)
class BOSpace:
    """Design space of a run: variables and linear constraints between them.

    Attributes:
        design_variables: Range and choice variables, in schema order.
        linear_constraints: The parameter constraints, parsed.
        parameter_constraints: The same constraints as expressions, for
            backends that take them verbatim.
    """

    design_variables: tuple[DesignVariable, ...]
    linear_constraints: tuple[LinearConstraint, ...] = ()
    parameter_constraints: tuple[str, ...] = ()

    @property
    def names(self) -> tuple[str, ...]:
        """Design variable names, in schema order."""
        return tuple(variable.name for variable in self.design_variables)

    def to_vector(self, parameters: Mapping[str, Scalar]) -> np.ndarray:
        """Encode user values as a GEMSEO design vector.

        Args:
            parameters: User value of every design variable.

        Returns:
            The vector, in schema order, with choices as indices.
        """
        return np.array(
            [
                encode_parameter_value(
                    to_parameter_definition(variable), parameters[variable.name]
                )
                for variable in self.design_variables
            ],
            dtype=float,
        )

    def from_vector(self, x: Sequence[float] | np.ndarray) -> dict[str, Scalar]:
        """Decode a GEMSEO design vector into user values.

        Args:
            x: Design vector, in schema order.

        Returns:
            User values: floats, ints, and the declared choice values.
        """
        return {
            variable.name: decode_parameter_value(
                to_parameter_definition(variable), value
            )
            for variable, value in zip(self.design_variables, x, strict=True)
        }

    def _violated_constraint(
        self, parameters: Mapping[str, Scalar]
    ) -> LinearConstraint | None:
        for constraint in self.linear_constraints:
            total = sum(
                coefficient * float(parameters[name])
                for name, coefficient in constraint.coefficients.items()
            )
            limit = constraint.bound + LINEAR_CONSTRAINT_SLACK * max(
                1.0, abs(constraint.bound)
            )
            if not total <= limit:
                return constraint
        return None

    def contains(self, parameters: Mapping[str, Scalar]) -> bool:
        """Return whether a point is in the design space.

        Args:
            parameters: User value of every design variable.

        Returns:
            ``True`` if every value is within bounds, integral for integer
            variables and a declared choice, and the linear constraints hold.
        """
        for variable in self.design_variables:
            if variable.name not in parameters:
                return False
            if not _admits(variable, parameters[variable.name]):
                return False
        return self._violated_constraint(parameters) is None

    def box_centre(self) -> dict[str, Scalar]:
        """Return the centre of the variable bounds, ignoring constraints."""
        return {variable.name: _centre(variable) for variable in self.design_variables}

    def cardinality(self) -> int | None:
        """Return the number of distinct points of a finite space.

        Returns:
            The number of points satisfying the linear constraints when every
            variable is discrete, ``None`` when a variable is continuous or
            the constraints apply to more than ``MAX_ENUMERATED_POINTS``
            candidate points.
        """
        values = [_discrete_values(variable) for variable in self.design_variables]
        if any(value is None for value in values):
            return None
        total = math.prod(len(value) for value in values)
        if not self.linear_constraints:
            return total
        if total > MAX_ENUMERATED_POINTS:
            return None
        return sum(
            self._violated_constraint(dict(zip(self.names, point, strict=True))) is None
            for point in itertools.product(*values)
        )

    def chebyshev_centre(self) -> dict[str, Scalar]:
        """Return the centre of the largest ball inside the linear constraints.

        The ball is measured in unit-box coordinates over the range variables;
        integers are rounded and choices sit at the box centre.

        Raises:
            OptimizationConfigurationError: If the constraints leave no point
                in the design space, or rounding integers leaves it.
        """
        point = self.box_centre()
        if not self.linear_constraints:
            return point
        ranges = [v for v in self.design_variables if isinstance(v, RangeVar)]
        centres = _largest_inscribed_ball(ranges, self.linear_constraints)
        for variable, unit in zip(ranges, centres, strict=True):
            value = variable.lower + unit * (variable.upper - variable.lower)
            if variable.value_type == "int":
                point[variable.name] = _round_half_up(value, variable)
            else:
                point[variable.name] = float(value)
        violated = self._violated_constraint(point)
        if violated is not None:
            raise OptimizationConfigurationError(
                "The Chebyshev centre rounded to integers violates the parameter "
                f"constraint {violated.expression!r}."
            )
        return point

    def start_point(self) -> dict[str, Scalar]:
        """Return the point the run starts from.

        Declared ``initial`` values are used, the box centre elsewhere. If that
        violates a linear constraint and no variable declares an initial value,
        the Chebyshev centre is used instead.

        Raises:
            OptimizationConfigurationError: If declared initial values violate
                a linear constraint, or no Chebyshev centre exists.
        """
        point = {
            variable.name: _initial_or_centre(variable)
            for variable in self.design_variables
        }
        violated = self._violated_constraint(point)
        if violated is None:
            return point
        if all(variable.initial is None for variable in self.design_variables):
            return self.chebyshev_centre()
        raise OptimizationConfigurationError(
            f"The declared initial values violate the parameter constraint "
            f"{violated.expression!r}; change them or remove them to let the "
            "optimizer choose a feasible start point."
        )

names property

Design variable names, in schema order.

box_centre()

Return the centre of the variable bounds, ignoring constraints.

Source code in src/mdo_framework/optimization/bo_types.py
567
568
569
def box_centre(self) -> dict[str, Scalar]:
    """Return the centre of the variable bounds, ignoring constraints."""
    return {variable.name: _centre(variable) for variable in self.design_variables}

cardinality()

Return the number of distinct points of a finite space.

Returns:

Type Description
int | None

The number of points satisfying the linear constraints when every

int | None

variable is discrete, None when a variable is continuous or

int | None

the constraints apply to more than MAX_ENUMERATED_POINTS

int | None

candidate points.

Source code in src/mdo_framework/optimization/bo_types.py
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def cardinality(self) -> int | None:
    """Return the number of distinct points of a finite space.

    Returns:
        The number of points satisfying the linear constraints when every
        variable is discrete, ``None`` when a variable is continuous or
        the constraints apply to more than ``MAX_ENUMERATED_POINTS``
        candidate points.
    """
    values = [_discrete_values(variable) for variable in self.design_variables]
    if any(value is None for value in values):
        return None
    total = math.prod(len(value) for value in values)
    if not self.linear_constraints:
        return total
    if total > MAX_ENUMERATED_POINTS:
        return None
    return sum(
        self._violated_constraint(dict(zip(self.names, point, strict=True))) is None
        for point in itertools.product(*values)
    )

chebyshev_centre()

Return the centre of the largest ball inside the linear constraints.

The ball is measured in unit-box coordinates over the range variables; integers are rounded and choices sit at the box centre.

Raises:

Type Description
OptimizationConfigurationError

If the constraints leave no point in the design space, or rounding integers leaves it.

Source code in src/mdo_framework/optimization/bo_types.py
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
def chebyshev_centre(self) -> dict[str, Scalar]:
    """Return the centre of the largest ball inside the linear constraints.

    The ball is measured in unit-box coordinates over the range variables;
    integers are rounded and choices sit at the box centre.

    Raises:
        OptimizationConfigurationError: If the constraints leave no point
            in the design space, or rounding integers leaves it.
    """
    point = self.box_centre()
    if not self.linear_constraints:
        return point
    ranges = [v for v in self.design_variables if isinstance(v, RangeVar)]
    centres = _largest_inscribed_ball(ranges, self.linear_constraints)
    for variable, unit in zip(ranges, centres, strict=True):
        value = variable.lower + unit * (variable.upper - variable.lower)
        if variable.value_type == "int":
            point[variable.name] = _round_half_up(value, variable)
        else:
            point[variable.name] = float(value)
    violated = self._violated_constraint(point)
    if violated is not None:
        raise OptimizationConfigurationError(
            "The Chebyshev centre rounded to integers violates the parameter "
            f"constraint {violated.expression!r}."
        )
    return point

contains(parameters)

Return whether a point is in the design space.

Parameters:

Name Type Description Default
parameters Mapping[str, Scalar]

User value of every design variable.

required

Returns:

Type Description
bool

True if every value is within bounds, integral for integer

bool

variables and a declared choice, and the linear constraints hold.

Source code in src/mdo_framework/optimization/bo_types.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
def contains(self, parameters: Mapping[str, Scalar]) -> bool:
    """Return whether a point is in the design space.

    Args:
        parameters: User value of every design variable.

    Returns:
        ``True`` if every value is within bounds, integral for integer
        variables and a declared choice, and the linear constraints hold.
    """
    for variable in self.design_variables:
        if variable.name not in parameters:
            return False
        if not _admits(variable, parameters[variable.name]):
            return False
    return self._violated_constraint(parameters) is None

from_vector(x)

Decode a GEMSEO design vector into user values.

Parameters:

Name Type Description Default
x Sequence[float] | ndarray

Design vector, in schema order.

required

Returns:

Type Description
dict[str, Scalar]

User values: floats, ints, and the declared choice values.

Source code in src/mdo_framework/optimization/bo_types.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
def from_vector(self, x: Sequence[float] | np.ndarray) -> dict[str, Scalar]:
    """Decode a GEMSEO design vector into user values.

    Args:
        x: Design vector, in schema order.

    Returns:
        User values: floats, ints, and the declared choice values.
    """
    return {
        variable.name: decode_parameter_value(
            to_parameter_definition(variable), value
        )
        for variable, value in zip(self.design_variables, x, strict=True)
    }

start_point()

Return the point the run starts from.

Declared initial values are used, the box centre elsewhere. If that violates a linear constraint and no variable declares an initial value, the Chebyshev centre is used instead.

Raises:

Type Description
OptimizationConfigurationError

If declared initial values violate a linear constraint, or no Chebyshev centre exists.

Source code in src/mdo_framework/optimization/bo_types.py
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
def start_point(self) -> dict[str, Scalar]:
    """Return the point the run starts from.

    Declared ``initial`` values are used, the box centre elsewhere. If that
    violates a linear constraint and no variable declares an initial value,
    the Chebyshev centre is used instead.

    Raises:
        OptimizationConfigurationError: If declared initial values violate
            a linear constraint, or no Chebyshev centre exists.
    """
    point = {
        variable.name: _initial_or_centre(variable)
        for variable in self.design_variables
    }
    violated = self._violated_constraint(point)
    if violated is None:
        return point
    if all(variable.initial is None for variable in self.design_variables):
        return self.chebyshev_centre()
    raise OptimizationConfigurationError(
        f"The declared initial values violate the parameter constraint "
        f"{violated.expression!r}; change them or remove them to let the "
        "optimizer choose a feasible start point."
    )

to_vector(parameters)

Encode user values as a GEMSEO design vector.

Parameters:

Name Type Description Default
parameters Mapping[str, Scalar]

User value of every design variable.

required

Returns:

Type Description
ndarray

The vector, in schema order, with choices as indices.

Source code in src/mdo_framework/optimization/bo_types.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
def to_vector(self, parameters: Mapping[str, Scalar]) -> np.ndarray:
    """Encode user values as a GEMSEO design vector.

    Args:
        parameters: User value of every design variable.

    Returns:
        The vector, in schema order, with choices as indices.
    """
    return np.array(
        [
            encode_parameter_value(
                to_parameter_definition(variable), parameters[variable.name]
            )
            for variable in self.design_variables
        ],
        dtype=float,
    )

Candidate dataclass

A point proposed by a backend.

Attributes:

Name Type Description
parameters Mapping[str, Scalar]

User values of the design variables, in schema order.

key Hashable | None

Backend handle used to report the outcome, e.g. an Ax trial index.

Source code in src/mdo_framework/optimization/bo_types.py
44
45
46
47
48
49
50
51
52
53
54
@dataclass(frozen=True)
class Candidate:
    """A point proposed by a backend.

    Attributes:
        parameters: User values of the design variables, in schema order.
        key: Backend handle used to report the outcome, e.g. an Ax trial index.
    """

    parameters: Mapping[str, Scalar]
    key: Hashable | None = None

MetricBinding dataclass

Link between a user output and the GEMSEO function that computes it.

The user value is sign * gemseo_value[index] + offset.

Attributes:

Name Type Description
name str

User output name of the objective or constraint.

role Literal['objective', 'constraint']

"objective" or "constraint".

gemseo_name str

Name of the GEMSEO function holding the value.

index int

Position of the value in that function's output.

sign float

Factor undoing the GEMSEO transformation.

offset float

Term undoing the GEMSEO transformation, in user units.

minimize bool

Direction of an objective.

threshold float | None

Reference point of an objective, in user units.

op Literal['<=', '>='] | None

"<=" or ">=" for a constraint.

bound float | None

Bound of a constraint, in user units.

tolerance float

Violation of the bound still accepted, in user units.

scale float

Typical magnitude of a constraint, to compare violations.

Source code in src/mdo_framework/optimization/bo_types.py
 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
@dataclass(frozen=True)
class MetricBinding:
    """Link between a user output and the GEMSEO function that computes it.

    The user value is ``sign * gemseo_value[index] + offset``.

    Attributes:
        name: User output name of the objective or constraint.
        role: ``"objective"`` or ``"constraint"``.
        gemseo_name: Name of the GEMSEO function holding the value.
        index: Position of the value in that function's output.
        sign: Factor undoing the GEMSEO transformation.
        offset: Term undoing the GEMSEO transformation, in user units.
        minimize: Direction of an objective.
        threshold: Reference point of an objective, in user units.
        op: ``"<="`` or ``">="`` for a constraint.
        bound: Bound of a constraint, in user units.
        tolerance: Violation of the bound still accepted, in user units.
        scale: Typical magnitude of a constraint, to compare violations.
    """

    name: str
    role: Literal["objective", "constraint"]
    gemseo_name: str
    index: int
    sign: float
    offset: float = 0.0
    minimize: bool = True
    threshold: float | None = None
    op: Literal["<=", ">="] | None = None
    bound: float | None = None
    tolerance: float = 0.0
    scale: float = 1.0

    def __post_init__(self) -> None:
        if self.role == "constraint" and (self.op is None or self.bound is None):
            raise ValueError(f"constraint {self.name!r} needs an operator and a bound")

    def user_value(self, output_data: Mapping[str, Any]) -> float:
        """Return the raw user value from the output data of GEMSEO.

        Args:
            output_data: GEMSEO function values, by GEMSEO function name.

        Returns:
            The value of the user output, in user units.
        """
        values = np.asarray(output_data[self.gemseo_name], dtype=float).ravel()
        return float(self.sign * values[self.index] + self.offset)

    def margin(self, value: float) -> float:
        """Return the distance to the bound, positive when inside it.

        Args:
            value: Raw user value of the constraint output.

        Returns:
            ``bound - value`` for ``<=``, ``value - bound`` for ``>=``.

        Raises:
            ValueError: If the binding is not a constraint.
        """
        if self.role != "constraint":
            raise ValueError(f"{self.name!r} is not a constraint, it has no margin")
        if self.op == "<=":
            return self.bound - value
        return value - self.bound

    def satisfied(self, value: float) -> bool:
        """Return whether a value respects the bound within the tolerance.

        Args:
            value: Raw user value of the output.

        Returns:
            ``value <= bound + tolerance`` for ``<=`` and
            ``value >= bound - tolerance`` for ``>=``, computed with the bound
            GEMSEO enforces so both agree at the edge; always ``True`` for an
            objective.
        """
        if self.role != "constraint":
            return True
        limit = _folded_bound(self.op, self.bound, self.tolerance)
        if self.op == "<=":
            return value <= limit
        return value >= limit

    def violation(self, value: float) -> float:
        """Return how far a value lies past the bound, in units of ``scale``.

        Args:
            value: Raw user value of the output.

        Returns:
            Zero when ``satisfied(value)``, otherwise the distance from the
            folded bound GEMSEO enforces divided by ``scale``; zero for an
            objective.
        """
        if self.satisfied(value):
            return 0.0
        limit = _folded_bound(self.op, self.bound, self.tolerance)
        excess = value - limit if self.op == "<=" else limit - value
        return excess / self.scale

margin(value)

Return the distance to the bound, positive when inside it.

Parameters:

Name Type Description Default
value float

Raw user value of the constraint output.

required

Returns:

Type Description
float

bound - value for <=, value - bound for >=.

Raises:

Type Description
ValueError

If the binding is not a constraint.

Source code in src/mdo_framework/optimization/bo_types.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def margin(self, value: float) -> float:
    """Return the distance to the bound, positive when inside it.

    Args:
        value: Raw user value of the constraint output.

    Returns:
        ``bound - value`` for ``<=``, ``value - bound`` for ``>=``.

    Raises:
        ValueError: If the binding is not a constraint.
    """
    if self.role != "constraint":
        raise ValueError(f"{self.name!r} is not a constraint, it has no margin")
    if self.op == "<=":
        return self.bound - value
    return value - self.bound

satisfied(value)

Return whether a value respects the bound within the tolerance.

Parameters:

Name Type Description Default
value float

Raw user value of the output.

required

Returns:

Type Description
bool

value <= bound + tolerance for <= and

bool

value >= bound - tolerance for >=, computed with the bound

bool

GEMSEO enforces so both agree at the edge; always True for an

bool

objective.

Source code in src/mdo_framework/optimization/bo_types.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def satisfied(self, value: float) -> bool:
    """Return whether a value respects the bound within the tolerance.

    Args:
        value: Raw user value of the output.

    Returns:
        ``value <= bound + tolerance`` for ``<=`` and
        ``value >= bound - tolerance`` for ``>=``, computed with the bound
        GEMSEO enforces so both agree at the edge; always ``True`` for an
        objective.
    """
    if self.role != "constraint":
        return True
    limit = _folded_bound(self.op, self.bound, self.tolerance)
    if self.op == "<=":
        return value <= limit
    return value >= limit

user_value(output_data)

Return the raw user value from the output data of GEMSEO.

Parameters:

Name Type Description Default
output_data Mapping[str, Any]

GEMSEO function values, by GEMSEO function name.

required

Returns:

Type Description
float

The value of the user output, in user units.

Source code in src/mdo_framework/optimization/bo_types.py
133
134
135
136
137
138
139
140
141
142
143
def user_value(self, output_data: Mapping[str, Any]) -> float:
    """Return the raw user value from the output data of GEMSEO.

    Args:
        output_data: GEMSEO function values, by GEMSEO function name.

    Returns:
        The value of the user output, in user units.
    """
    values = np.asarray(output_data[self.gemseo_name], dtype=float).ravel()
    return float(self.sign * values[self.index] + self.offset)

violation(value)

Return how far a value lies past the bound, in units of scale.

Parameters:

Name Type Description Default
value float

Raw user value of the output.

required

Returns:

Type Description
float

Zero when satisfied(value), otherwise the distance from the

float

folded bound GEMSEO enforces divided by scale; zero for an

float

objective.

Source code in src/mdo_framework/optimization/bo_types.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def violation(self, value: float) -> float:
    """Return how far a value lies past the bound, in units of ``scale``.

    Args:
        value: Raw user value of the output.

    Returns:
        Zero when ``satisfied(value)``, otherwise the distance from the
        folded bound GEMSEO enforces divided by ``scale``; zero for an
        objective.
    """
    if self.satisfied(value):
        return 0.0
    limit = _folded_bound(self.op, self.bound, self.tolerance)
    excess = value - limit if self.op == "<=" else limit - value
    return excess / self.scale

TrialOutcome dataclass

What evaluating a candidate produced.

Attributes:

Name Type Description
status TrialStatus

"completed" if every metric is available, "failed" if the evaluation did not produce usable values, "abandoned" if it was never evaluated because the run stopped.

metrics Mapping[str, float]

Raw user value of each objective and constraint output.

reason str | None

Why the trial failed or was abandoned, None otherwise.

Source code in src/mdo_framework/optimization/bo_types.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@dataclass(frozen=True)
class TrialOutcome:
    """What evaluating a candidate produced.

    Attributes:
        status: ``"completed"`` if every metric is available, ``"failed"`` if
            the evaluation did not produce usable values, ``"abandoned"`` if
            it was never evaluated because the run stopped.
        metrics: Raw user value of each objective and constraint output.
        reason: Why the trial failed or was abandoned, ``None`` otherwise.
    """

    status: TrialStatus
    metrics: Mapping[str, float] = field(default_factory=dict)
    reason: str | None = None

TrialRecord dataclass

A candidate together with its outcome.

Attributes:

Name Type Description
index int

Position of the trial in the run.

phase Phase

"x0" for the start point, "init" for the initial design, "bo" for the model-driven trials.

parameters Mapping[str, Scalar]

User values of the design variables.

outcome TrialOutcome

What the evaluation produced.

Source code in src/mdo_framework/optimization/bo_types.py
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
@dataclass(frozen=True)
class TrialRecord:
    """A candidate together with its outcome.

    Attributes:
        index: Position of the trial in the run.
        phase: ``"x0"`` for the start point, ``"init"`` for the initial
            design, ``"bo"`` for the model-driven trials.
        parameters: User values of the design variables.
        outcome: What the evaluation produced.
    """

    index: int
    phase: Phase
    parameters: Mapping[str, Scalar]
    outcome: TrialOutcome

    def feasible(self, bindings: Sequence[MetricBinding]) -> bool:
        """Return whether the trial completed within every constraint."""
        if self.outcome.status != "completed":
            return False
        return all(
            binding.satisfied(self.outcome.metrics[binding.name])
            for binding in _constraints(bindings)
        )

    def violation(self, bindings: Sequence[MetricBinding]) -> float:
        """Return the total violation, net of tolerance, in constraint scales."""
        return sum(
            binding.violation(self.outcome.metrics[binding.name])
            for binding in _constraints(bindings)
        )

    def to_history_entry(self, bindings: Sequence[MetricBinding]) -> dict[str, Any]:
        """Return the record as a history entry keyed by user names only.

        Args:
            bindings: Objective and constraint bindings of the run.

        Returns:
            The entry. ``objectives`` holds every metric and ``constraints``
            their margins; both are empty unless the trial completed.
        """
        completed = self.outcome.status == "completed"
        metrics = self.outcome.metrics
        return {
            "index": self.index,
            "phase": self.phase,
            "status": self.outcome.status,
            "reason": self.outcome.reason,
            "parameters": dict(self.parameters),
            "objectives": (
                {binding.name: metrics[binding.name] for binding in bindings}
                if completed
                else {}
            ),
            "constraints": (
                {
                    binding.name: {
                        "value": metrics[binding.name],
                        "margin": binding.margin(metrics[binding.name]),
                        "satisfied": binding.satisfied(metrics[binding.name]),
                    }
                    for binding in _constraints(bindings)
                }
                if completed
                else {}
            ),
            "feasible": self.feasible(bindings),
        }

feasible(bindings)

Return whether the trial completed within every constraint.

Source code in src/mdo_framework/optimization/bo_types.py
217
218
219
220
221
222
223
224
def feasible(self, bindings: Sequence[MetricBinding]) -> bool:
    """Return whether the trial completed within every constraint."""
    if self.outcome.status != "completed":
        return False
    return all(
        binding.satisfied(self.outcome.metrics[binding.name])
        for binding in _constraints(bindings)
    )

to_history_entry(bindings)

Return the record as a history entry keyed by user names only.

Parameters:

Name Type Description Default
bindings Sequence[MetricBinding]

Objective and constraint bindings of the run.

required

Returns:

Type Description
dict[str, Any]

The entry. objectives holds every metric and constraints

dict[str, Any]

their margins; both are empty unless the trial completed.

Source code in src/mdo_framework/optimization/bo_types.py
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
def to_history_entry(self, bindings: Sequence[MetricBinding]) -> dict[str, Any]:
    """Return the record as a history entry keyed by user names only.

    Args:
        bindings: Objective and constraint bindings of the run.

    Returns:
        The entry. ``objectives`` holds every metric and ``constraints``
        their margins; both are empty unless the trial completed.
    """
    completed = self.outcome.status == "completed"
    metrics = self.outcome.metrics
    return {
        "index": self.index,
        "phase": self.phase,
        "status": self.outcome.status,
        "reason": self.outcome.reason,
        "parameters": dict(self.parameters),
        "objectives": (
            {binding.name: metrics[binding.name] for binding in bindings}
            if completed
            else {}
        ),
        "constraints": (
            {
                binding.name: {
                    "value": metrics[binding.name],
                    "margin": binding.margin(metrics[binding.name]),
                    "satisfied": binding.satisfied(metrics[binding.name]),
                }
                for binding in _constraints(bindings)
            }
            if completed
            else {}
        ),
        "feasible": self.feasible(bindings),
    }

violation(bindings)

Return the total violation, net of tolerance, in constraint scales.

Source code in src/mdo_framework/optimization/bo_types.py
226
227
228
229
230
231
def violation(self, bindings: Sequence[MetricBinding]) -> float:
    """Return the total violation, net of tolerance, in constraint scales."""
    return sum(
        binding.violation(self.outcome.metrics[binding.name])
        for binding in _constraints(bindings)
    )

gemseo_bound(spec)

Return the bound GEMSEO enforces for a constraint.

The tolerance is folded into the bound, so GEMSEO runs with a zero tolerance and its feasibility matches MetricBinding.satisfied.

Parameters:

Name Type Description Default
spec ConstraintSpec

Constraint declaration.

required

Returns:

Type Description
float

bound + tolerance for <=, bound - tolerance for >=.

Source code in src/mdo_framework/optimization/bo_types.py
74
75
76
77
78
79
80
81
82
83
84
85
86
def gemseo_bound(spec: ConstraintSpec) -> float:
    """Return the bound GEMSEO enforces for a constraint.

    The tolerance is folded into the bound, so GEMSEO runs with a zero
    tolerance and its feasibility matches ``MetricBinding.satisfied``.

    Args:
        spec: Constraint declaration.

    Returns:
        ``bound + tolerance`` for ``<=``, ``bound - tolerance`` for ``>=``.
    """
    return _folded_bound(spec.op, spec.bound, spec.tolerance)

select_best(records, bindings)

Pick the record to report as the result of a run.

Parameters:

Name Type Description Default
records Sequence[TrialRecord]

Trial records, in run order.

required
bindings Sequence[MetricBinding]

Objective and constraint bindings of the run.

required

Returns:

Type Description
TrialRecord | None

With one objective, the feasible completed record that is best in the

TrialRecord | None

user direction; with several, the Pareto-front point closest to the

TrialRecord | None

ideal point. Without a feasible record, the completed record with the

TrialRecord | None

least total violation. Earlier records win ties. None if no trial

TrialRecord | None

completed.

Source code in src/mdo_framework/optimization/bo_types.py
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
def select_best(
    records: Sequence[TrialRecord], bindings: Sequence[MetricBinding]
) -> TrialRecord | None:
    """Pick the record to report as the result of a run.

    Args:
        records: Trial records, in run order.
        bindings: Objective and constraint bindings of the run.

    Returns:
        With one objective, the feasible completed record that is best in the
        user direction; with several, the Pareto-front point closest to the
        ideal point. Without a feasible record, the completed record with the
        least total violation. Earlier records win ties. ``None`` if no trial
        completed.
    """
    objectives = _objectives(bindings)
    if any(record.feasible(bindings) for record in records):
        if len(objectives) == 1:
            return min(
                (record for record in records if record.feasible(bindings)),
                key=lambda record: _minimised(record, objectives),
            )
        return _compromise(_pareto_front(records, bindings), objectives)
    completed = [record for record in records if record.outcome.status == "completed"]
    return min(completed, key=lambda record: record.violation(bindings), default=None)

Random search

This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

RandomSearchLibrary

Bases: BaseBOLibrary

Seeded random search, the reference backend of the driver.

It draws every design variable uniformly (log-uniformly on a log scale, among the choices for a choice variable), keeps the draws that satisfy the parameter constraints, and never proposes a point twice. It learns nothing from the outcomes, so it needs no objective model.

Source code in src/mdo_framework/optimization/random_search.py
 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
class RandomSearchLibrary(BaseBOLibrary):
    """Seeded random search, the reference backend of the driver.

    It draws every design variable uniformly (log-uniformly on a log scale,
    among the choices for a choice variable), keeps the draws that satisfy the
    parameter constraints, and never proposes a point twice. It learns nothing
    from the outcomes, so it needs no objective model.
    """

    LIBRARY_NAME = "GraphMDO"

    ALGORITHM_INFOS = {
        "BO_RandomSearch": OptimizationAlgorithmDescription(
            algorithm_name="BO_RandomSearch",
            internal_algorithm_name="BO_RandomSearch",
            library_name=LIBRARY_NAME,
            description="Seeded random search, reference backend of the BO driver.",
            website="",
            Settings=RandomSearchSettings,
            handle_equality_constraints=False,
            handle_inequality_constraints=True,
            handle_multiobjective=True,
            handle_integer_variables=True,
            positive_constraints=False,
            require_gradient=False,
            for_linear_problems=False,
        )
    }

    MAX_DRAWS = 1000
    """Draws made to find one new point satisfying the parameter constraints."""

    def __init__(self, algo_name: str = "BO_RandomSearch") -> None:
        super().__init__(algo_name=algo_name)
        self._rng = np.random.default_rng()
        self._seen: set[tuple[Scalar, ...]] = set()

    def _setup(
        self,
        space: BOSpace,
        bindings: tuple[MetricBinding, ...],
        prior: tuple[TrialRecord, ...],
    ) -> None:
        self._rng = np.random.default_rng(self._settings.seed)
        self._seen = {self._key(record.parameters) for record in prior}

    def _ask(self, n: int) -> list[Candidate]:
        candidates = []
        for _ in range(n):
            point = self._draw_new_point()
            if point is None:
                break
            candidates.append(Candidate(point))
        return candidates

    def _tell(self, candidate: Candidate, outcome: TrialOutcome) -> None:
        """Learn nothing: the draws do not depend on the outcomes."""

    def _key(self, parameters: Mapping[str, Scalar]) -> tuple[Scalar, ...]:
        return tuple(parameters[name] for name in self._space.names)

    def _draw_new_point(self) -> dict[str, Scalar] | None:
        """Return a new point satisfying the parameter constraints.

        Raises:
            OptimizationConfigurationError: If no draw satisfies them.
        """
        satisfied = False
        for _ in range(self.MAX_DRAWS):
            point = {
                variable.name: self._draw(variable)
                for variable in self._space.design_variables
            }
            if not self._space.contains(point):
                continue
            satisfied = True
            key = self._key(point)
            if key not in self._seen:
                self._seen.add(key)
                return point
        if not satisfied:
            raise OptimizationConfigurationError(
                f"no point satisfying the parameter constraints "
                f"{list(self._space.parameter_constraints)} found in "
                f"{self.MAX_DRAWS} draws: the constraints leave a space too "
                "small to sample"
            )
        return None

    def _draw(self, variable: DesignVariable) -> Scalar:
        if isinstance(variable, ChoiceVar):
            return variable.choices[int(self._rng.integers(len(variable.choices)))]
        return self._draw_range(variable)

    def _draw_range(self, variable: RangeVar) -> Scalar:
        lower, upper = variable.lower, variable.upper
        if variable.value_type == "int":
            return int(self._rng.integers(math.ceil(lower), math.floor(upper) + 1))
        if variable.scaling == "log":
            value = math.exp(self._rng.uniform(math.log(lower), math.log(upper)))
            return min(max(value, lower), upper)
        return float(self._rng.uniform(lower, upper))

MAX_DRAWS = 1000 class-attribute instance-attribute

Draws made to find one new point satisfying the parameter constraints.

RandomSearchSettings

Bases: BaseBOSettings

Settings of the random-search backend, those of the driver.

Source code in src/mdo_framework/optimization/random_search.py
25
26
class RandomSearchSettings(BaseBOSettings):
    """Settings of the random-search backend, those of the driver."""

Ax backend

mdo_framework.optimization.ax_algo_lib

This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

AxOptimizationLibrary

Bases: BaseBOLibrary

Bayesian optimization backend running on the Ax client API.

It only maps the three hooks of the driver onto an Ax experiment: the search space, the metrics and the generation strategy of the experiment, the trials Ax proposes, and the outcome of each. Everything else belongs to the driver.

Source code in src/mdo_framework/optimization/ax_algo_lib.py
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
class AxOptimizationLibrary(BaseBOLibrary):
    """Bayesian optimization backend running on the Ax client API.

    It only maps the three hooks of the driver onto an Ax experiment: the
    search space, the metrics and the generation strategy of the experiment,
    the trials Ax proposes, and the outcome of each. Everything else belongs to
    the driver.
    """

    LIBRARY_NAME = "Ax_Platform"

    ALGORITHM_INFOS = {
        "Ax_Bayesian": OptimizationAlgorithmDescription(
            algorithm_name="Ax_Bayesian",
            internal_algorithm_name="Ax_Bayesian",
            library_name=LIBRARY_NAME,
            description="Bayesian optimization with the Ax platform.",
            website="https://ax.dev/",
            Settings=AxSettings,
            handle_equality_constraints=False,
            handle_inequality_constraints=True,
            handle_multiobjective=True,
            handle_integer_variables=True,
            positive_constraints=False,
            require_gradient=False,
            for_linear_problems=False,
        )
    }

    def __init__(
        self,
        algo_name: str = "Ax_Bayesian",
        client_factory: Callable[..., Client] | None = None,
    ) -> None:
        """Create the library.

        Args:
            algo_name: Name of the algorithm.
            client_factory: Callable building the Ax client from the keyword
                ``random_seed``. By default, the ``Client`` of this module,
                looked up when a run starts.
        """
        super().__init__(algo_name=algo_name)
        self._client_factory = client_factory
        self._client: Client | None = None
        self._failed_points: set[tuple[Any, ...]] = set()

    def _setup(
        self,
        space: BOSpace,
        bindings: tuple[MetricBinding, ...],
        prior: tuple[TrialRecord, ...],
    ) -> None:
        settings = self._settings
        factory = self._client_factory or Client
        self._failed_points = set()
        with _quiet_ax():
            client = factory(random_seed=settings.seed)
            client.configure_experiment(
                parameters=[_parameter_config(v) for v in space.design_variables],
                parameter_constraints=list(space.parameter_constraints) or None,
                name=EXPERIMENT_NAME,
            )
            client.set_optimization_config(_optimization_config(bindings))
            client.set_generation_strategy(self._generation_strategy(bindings))
            self._client = client
            for record in prior:
                self._attach(record)

    def _generation_strategy(
        self, bindings: tuple[MetricBinding, ...]
    ) -> GenerationStrategy:
        """Return Sobol for the initial trials, then BoTorch.

        The acquisition function is hard-coded for a single objective only: a
        multi-objective run needs the hypervolume one Ax picks itself. Both
        steps reject points of earlier trials, abandoned ones included.
        """
        settings = self._settings
        n_objectives = sum(1 for b in bindings if b.role == "objective")
        generator_kwargs = None
        if settings.use_bonsai:
            logger.warning("Experimental feature BONSAI algorithm is activated.")
        elif n_objectives == 1:
            generator_kwargs = {"botorch_acqf_class": qLogNoisyExpectedImprovement}
        return GenerationStrategy(
            name="bonsai" if settings.use_bonsai else "botorch_modular",
            nodes=[
                GenerationStep(
                    generator=Models.SOBOL,
                    num_trials=settings.n_init,
                    min_trials_observed=1,
                    should_deduplicate=True,
                ),
                GenerationStep(
                    generator=Models.BOTORCH_MODULAR,
                    num_trials=-1,
                    generator_kwargs=generator_kwargs,
                    should_deduplicate=True,
                ),
            ],
        )

    def _attach(self, record: TrialRecord) -> None:
        """Attach a point evaluated before the run as the baseline trial."""
        index = self._client.attach_baseline(parameters=dict(record.parameters))
        self._report(index, record.parameters, record.outcome)

    def _ask(self, n: int) -> list[Candidate]:
        with _quiet_ax():
            try:
                trials = self._client.get_next_trials(max_trials=n)
            except DataRequiredError as error:
                raise OptimizationExecutionError(
                    "Ax cannot propose a new design before the initial trials "
                    f"have an outcome: {error}"
                ) from error
            except OptimizationComplete:
                # Ax found no new point; the driver decides when to stop.
                return []
        return [Candidate(dict(p), key=index) for index, p in trials.items()]

    def _tell(self, candidate: Candidate, outcome: TrialOutcome) -> None:
        with _quiet_ax():
            self._report(candidate.key, candidate.parameters, outcome)

    def _report(
        self, index: int, parameters: Mapping[str, Any], outcome: TrialOutcome
    ) -> None:
        if outcome.status == "completed":
            self._client.complete_trial(
                trial_index=index, raw_data=_raw_data(self._bindings, outcome.metrics)
            )
            return
        point = tuple(parameters[name] for name in self._space.names)
        if outcome.status == "failed" and point not in self._failed_points:
            self._failed_points.add(point)
            self._client.mark_trial_failed(
                trial_index=index, failed_reason=outcome.reason
            )
            return
        # Ax retries the points of failed trials but avoids abandoned ones. The
        # driver never evaluates a failed point twice, so a repeat is abandoned.
        self._client.mark_trial_abandoned(trial_index=index)

__init__(algo_name='Ax_Bayesian', client_factory=None)

Create the library.

Parameters:

Name Type Description Default
algo_name str

Name of the algorithm.

'Ax_Bayesian'
client_factory Callable[..., Client] | None

Callable building the Ax client from the keyword random_seed. By default, the Client of this module, looked up when a run starts.

None
Source code in src/mdo_framework/optimization/ax_algo_lib.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def __init__(
    self,
    algo_name: str = "Ax_Bayesian",
    client_factory: Callable[..., Client] | None = None,
) -> None:
    """Create the library.

    Args:
        algo_name: Name of the algorithm.
        client_factory: Callable building the Ax client from the keyword
            ``random_seed``. By default, the ``Client`` of this module,
            looked up when a run starts.
    """
    super().__init__(algo_name=algo_name)
    self._client_factory = client_factory
    self._client: Client | None = None
    self._failed_points: set[tuple[Any, ...]] = set()

AxSettings

Bases: BaseBOSettings

Settings of the Ax backend.

Attributes:

Name Type Description
use_bonsai bool

Whether to use the experimental BONSAI acquisition of Ax instead of the default one.

Source code in src/mdo_framework/optimization/ax_algo_lib.py
144
145
146
147
148
149
150
151
152
class AxSettings(BaseBOSettings):
    """Settings of the Ax backend.

    Attributes:
        use_bonsai: Whether to use the experimental BONSAI acquisition of Ax
            instead of the default one.
    """

    use_bonsai: bool = False

Errors

mdo_framework.optimization.errors

This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

OptimizationConfigurationError

Bases: ValueError

Raised when the optimization request is invalid for the current backend.

Source code in src/mdo_framework/optimization/errors.py
11
12
class OptimizationConfigurationError(ValueError):
    """Raised when the optimization request is invalid for the current backend."""

OptimizationExecutionError

Bases: RuntimeError

Raised when optimization cannot produce a valid result.

Attributes:

Name Type Description
partial_result

What the run produced before it was aborted, for example its trial history; None if nothing is available.

Source code in src/mdo_framework/optimization/errors.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class OptimizationExecutionError(RuntimeError):
    """Raised when optimization cannot produce a valid result.

    Attributes:
        partial_result: What the run produced before it was aborted, for
            example its trial history; ``None`` if nothing is available.
    """

    def __init__(
        self, message: str, *, partial_result: Mapping[str, Any] | None = None
    ) -> None:
        """Build the error.

        Args:
            message: Why the optimization failed.
            partial_result: What the run produced before it was aborted.
        """
        super().__init__(message)
        self.partial_result = partial_result

__init__(message, *, partial_result=None)

Build the error.

Parameters:

Name Type Description Default
message str

Why the optimization failed.

required
partial_result Mapping[str, Any] | None

What the run produced before it was aborted.

None
Source code in src/mdo_framework/optimization/errors.py
23
24
25
26
27
28
29
30
31
32
33
def __init__(
    self, message: str, *, partial_result: Mapping[str, Any] | None = None
) -> None:
    """Build the error.

    Args:
        message: Why the optimization failed.
        partial_result: What the run produced before it was aborted.
    """
    super().__init__(message)
    self.partial_result = partial_result