Skip to content

BayesianOptimizer

The optimizer API supports:

  • Local and remote evaluation backends.
  • Typed ObjectiveSpec and ConstraintSpec inputs (<= and >=, with an optional per-constraint tolerance) and the design variables resolved from the study schema.
  • A result with the best point, its feasibility and constraint margins, the Pareto front of multi-objective runs, a trial history with one record per trial (phase, status, parameters, objectives, constraints), the stop_reason and the evaluation counts.
  • Typed failures for configuration, transport, contract, and execution errors; the execution errors carry the partial_result of the run.

mdo_framework.optimization.optimizer.BayesianOptimizer

Bayesian optimizer on the backend-neutral driver of GEMSEO.

Parameters:

Name Type Description Default
evaluator Evaluator

Local or remote implementation of the Evaluator protocol.

required
design_variables Sequence[DesignVariable]

Design variables, in the order of the design space.

required
objectives Sequence[ObjectiveSpec]

Objectives to optimize, at least one.

required
constraints Sequence[ConstraintSpec]

Inequality constraints on the outputs.

()
parameter_constraints Sequence[str]

Linear constraints between design variables.

()
use_bonsai bool

Whether to use the experimental BONSAI acquisition of Ax.

False
algorithm str

Backend, a key of ALGORITHMS.

'Ax_Bayesian'

Raises:

Type Description
OptimizationConfigurationError

If there is no design variable or objective, the algorithm is unknown, or use_bonsai is not supported by it.

Source code in src/mdo_framework/optimization/optimizer.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
class BayesianOptimizer:
    """Bayesian optimizer on the backend-neutral driver of GEMSEO.

    Args:
        evaluator: Local or remote implementation of the Evaluator protocol.
        design_variables: Design variables, in the order of the design space.
        objectives: Objectives to optimize, at least one.
        constraints: Inequality constraints on the outputs.
        parameter_constraints: Linear constraints between design variables.
        use_bonsai: Whether to use the experimental BONSAI acquisition of Ax.
        algorithm: Backend, a key of ``ALGORITHMS``.

    Raises:
        OptimizationConfigurationError: If there is no design variable or
            objective, the algorithm is unknown, or ``use_bonsai`` is not
            supported by it.
    """

    def __init__(
        self,
        evaluator: Evaluator,
        design_variables: Sequence[DesignVariable],
        objectives: Sequence[ObjectiveSpec],
        constraints: Sequence[ConstraintSpec] = (),
        parameter_constraints: Sequence[str] = (),
        use_bonsai: bool = False,
        algorithm: str = "Ax_Bayesian",
    ) -> None:
        if not design_variables:
            raise OptimizationConfigurationError(
                "At least one design variable is required."
            )
        if not objectives:
            raise OptimizationConfigurationError("At least one objective is required.")
        if algorithm not in ALGORITHMS:
            raise OptimizationConfigurationError(
                f"Unknown algorithm {algorithm!r}. Available: {sorted(ALGORITHMS)}."
            )
        settings_class = ALGORITHMS[algorithm].ALGORITHM_INFOS[algorithm].Settings
        if use_bonsai and "use_bonsai" not in settings_class.model_fields:
            raise OptimizationConfigurationError(
                f"use_bonsai is not supported by the algorithm {algorithm!r}."
            )
        self.evaluator = evaluator
        self.design_variables = tuple(design_variables)
        self.objectives = tuple(objectives)
        self.constraints = tuple(constraints)
        self.parameter_constraints = tuple(parameter_constraints)
        self.use_bonsai = use_bonsai
        self.algorithm = algorithm
        self._settings_class = settings_class

    def _build_output_names(self) -> list[str]:
        names = [objective.name for objective in self.objectives]
        names += [constraint.name for constraint in self.constraints]
        return list(dict.fromkeys(names))

    def _build_discipline(self) -> Discipline:
        if hasattr(self.evaluator, "problem"):
            return self.evaluator.problem
        return RemoteDiscipline(
            self.evaluator,
            self.design_variables,
            self._build_output_names(),
        )

    def _prepare_scenario_context(self) -> tuple[Discipline, DesignSpace, list[str]]:
        return (
            self._build_discipline(),
            _build_design_space(self.design_variables),
            [objective.name for objective in self.objectives],
        )

    def _create_scenario(
        self,
        *,
        discipline: Discipline,
        design_space: DesignSpace,
        objective_names: list[str],
        scenario_type: str | None = None,
        maximize_objective: bool | None = None,
        name: str | None = None,
    ) -> Any:
        scenario_kwargs: dict[str, Any] = {
            "formulation_name": "MDF",
            "objective_name": objective_names,
            "design_space": design_space,
        }
        if scenario_type is not None:
            scenario_kwargs["scenario_type"] = scenario_type
        if maximize_objective is not None:
            scenario_kwargs["maximize_objective"] = maximize_objective
        if name is not None:
            scenario_kwargs["name"] = name

        scenario = create_scenario([discipline], **scenario_kwargs)
        add_constraints(scenario, self.constraints)
        return scenario

    def explore(self, n_samples: int = 10, n_processes: int = 1) -> dict[str, Any]:
        """Runs a Design of Experiments (DOE) exploration using GEMSEO DOEScenario.

        Args:
            n_samples: Number of samples to evaluate.
            n_processes: Number of concurrent processes.

        Returns:
            A dictionary containing the exploration history.
        """
        discipline, design_space, objective_names = self._prepare_scenario_context()
        recorder = _FailureRecorder(discipline)

        scenario = self._create_scenario(
            discipline=recorder,
            design_space=design_space,
            objective_names=objective_names,
            scenario_type="DOE",
        )

        try:
            scenario.execute(
                algo_name="Sobol",
                n_samples=n_samples,
                n_processes=n_processes,
            )

            # Post-process
            try:
                from gemseo.settings.post import ScatterPlotMatrix_Settings

                scenario.post_process(
                    "ScatterPlotMatrix",
                    settings_model=ScatterPlotMatrix_Settings(save=True, show=False),
                )
            except Exception as pp_err:
                logger.warning(f"Failed to post-process DOE: {pp_err}")

            return {
                "history": scenario.to_dataset(),
            }
        except (
            OptimizationConfigurationError,
            OptimizationExecutionError,
            RemoteEvaluationContractError,
            RemoteEvaluationTransportError,
        ):
            raise
        except Exception as e:
            evaluated = len(scenario.formulation.optimization_problem.database)
            if recorder.failures and not evaluated:
                raise recorder.failures[0] from e
            logger.error(f"Exploration failed: {e}")
            raise OptimizationExecutionError(f"Exploration failed: {str(e)}") from e

    def optimize(
        self,
        n_steps: int = 10,
        n_init: int = 5,
        evaluate_x0: bool | None = None,
        max_consecutive_failures: int = 5,
        seed: int | None = None,
    ) -> dict[str, Any]:
        """Runs Bayesian optimization using a GEMSEO MDOScenario.

        The tools are called ``n_init + n_steps`` times, plus once for the
        start point x0 when it is evaluated. Fewer calls happen only when the
        run stops early: the search space is exhausted, ``max_consecutive_failures``
        trials fail in a row or the time limit is reached.

        Args:
            n_steps: Model-driven trials, at least 1.
            n_init: Initial trials, at least 1.
            evaluate_x0: Whether to evaluate the start point first. ``None``
                evaluates it when every design variable declares ``initial``.
            max_consecutive_failures: Failed trials in a row that end the run,
                at least 1.
            seed: Seed of the backend, ``None`` for a random one.

        Returns:
            The result: ``best_parameters``, ``best_objectives`` (by objective
            name), ``feasible``, ``constraints`` (value, margin, satisfied and
            tolerance at the best point), ``pareto_front`` (several objectives
            only), ``history`` (one entry per trial), ``stop_reason`` and
            ``evaluations`` (per phase).

        Raises:
            OptimizationConfigurationError: If a budget is < 1, or the design
                space or the backend settings are invalid.
            OptimizationExecutionError: If no trial completed or the run was
                aborted. Its ``partial_result`` keeps the trials made so far.
        """
        for budget_name, budget in (
            ("n_steps", n_steps),
            ("n_init", n_init),
            ("max_consecutive_failures", max_consecutive_failures),
        ):
            if budget < 1:
                raise OptimizationConfigurationError(
                    f"{budget_name} must be >= 1, got {budget}."
                )
        discipline, design_space, objective_names = self._prepare_scenario_context()
        scenario = self._create_scenario(
            discipline=discipline,
            design_space=design_space,
            objective_names=objective_names,
            maximize_objective=len(self.objectives) == 1
            and not self.objectives[0].minimize,
            name=f"MDOScenario_{self.algorithm}",
        )
        settings_kwargs: dict[str, Any] = {
            "design_variables": self.design_variables,
            "objectives": self.objectives,
            "constraints": self.constraints,
            "parameter_constraints": self.parameter_constraints,
            "n_init": n_init,
            "n_steps": n_steps,
            "evaluate_x0": evaluate_x0,
            "seed": seed,
            "max_consecutive_failures": max_consecutive_failures,
        }
        if self.use_bonsai:
            settings_kwargs["use_bonsai"] = True
        library = ALGORITHMS[self.algorithm](self.algorithm)

        try:
            library.execute(
                scenario.formulation.optimization_problem,
                settings_model=self._settings_class(**settings_kwargs),
            )
            if library.result is not None and library.result.best is not None:
                self._write_reports(scenario)
        except (
            OptimizationConfigurationError,
            OptimizationExecutionError,
            RemoteEvaluationContractError,
            RemoteEvaluationTransportError,
        ) as error:
            if getattr(error, "partial_result", None) is None:
                error.partial_result = self._partial_result(library)
            raise
        except Exception as e:
            logger.error(f"Optimization failed: {e}", exc_info=True)
            raise OptimizationExecutionError(
                f"Optimization failed: {e}",
                partial_result=self._partial_result(library),
            ) from e

        result = library.result
        if result is None or result.best is None:
            raise OptimizationExecutionError(
                _no_completed_trial_message(result),
                partial_result=self._partial_result(library),
            )
        return _result_contract(result)

    @staticmethod
    def _partial_result(library: BaseBOLibrary) -> dict[str, Any] | None:
        """Result contract of the trials a library made, if it got to run."""
        if library.result is None:
            return None
        return _result_contract(library.result)

    @staticmethod
    def _write_reports(scenario: Any) -> None:
        scenario.xdsmize(show_html=False)
        try:
            from gemseo.settings.post import OptHistoryView_Settings

            scenario.post_process(
                settings_model=OptHistoryView_Settings(save=True, show=False)
            )
        except Exception as pp_err:
            logger.warning(f"Failed to post-process: {pp_err}")

explore(n_samples=10, n_processes=1)

Runs a Design of Experiments (DOE) exploration using GEMSEO DOEScenario.

Parameters:

Name Type Description Default
n_samples int

Number of samples to evaluate.

10
n_processes int

Number of concurrent processes.

1

Returns:

Type Description
dict[str, Any]

A dictionary containing the exploration history.

Source code in src/mdo_framework/optimization/optimizer.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
def explore(self, n_samples: int = 10, n_processes: int = 1) -> dict[str, Any]:
    """Runs a Design of Experiments (DOE) exploration using GEMSEO DOEScenario.

    Args:
        n_samples: Number of samples to evaluate.
        n_processes: Number of concurrent processes.

    Returns:
        A dictionary containing the exploration history.
    """
    discipline, design_space, objective_names = self._prepare_scenario_context()
    recorder = _FailureRecorder(discipline)

    scenario = self._create_scenario(
        discipline=recorder,
        design_space=design_space,
        objective_names=objective_names,
        scenario_type="DOE",
    )

    try:
        scenario.execute(
            algo_name="Sobol",
            n_samples=n_samples,
            n_processes=n_processes,
        )

        # Post-process
        try:
            from gemseo.settings.post import ScatterPlotMatrix_Settings

            scenario.post_process(
                "ScatterPlotMatrix",
                settings_model=ScatterPlotMatrix_Settings(save=True, show=False),
            )
        except Exception as pp_err:
            logger.warning(f"Failed to post-process DOE: {pp_err}")

        return {
            "history": scenario.to_dataset(),
        }
    except (
        OptimizationConfigurationError,
        OptimizationExecutionError,
        RemoteEvaluationContractError,
        RemoteEvaluationTransportError,
    ):
        raise
    except Exception as e:
        evaluated = len(scenario.formulation.optimization_problem.database)
        if recorder.failures and not evaluated:
            raise recorder.failures[0] from e
        logger.error(f"Exploration failed: {e}")
        raise OptimizationExecutionError(f"Exploration failed: {str(e)}") from e

optimize(n_steps=10, n_init=5, evaluate_x0=None, max_consecutive_failures=5, seed=None)

Runs Bayesian optimization using a GEMSEO MDOScenario.

The tools are called n_init + n_steps times, plus once for the start point x0 when it is evaluated. Fewer calls happen only when the run stops early: the search space is exhausted, max_consecutive_failures trials fail in a row or the time limit is reached.

Parameters:

Name Type Description Default
n_steps int

Model-driven trials, at least 1.

10
n_init int

Initial trials, at least 1.

5
evaluate_x0 bool | None

Whether to evaluate the start point first. None evaluates it when every design variable declares initial.

None
max_consecutive_failures int

Failed trials in a row that end the run, at least 1.

5
seed int | None

Seed of the backend, None for a random one.

None

Returns:

Type Description
dict[str, Any]

The result: best_parameters, best_objectives (by objective

dict[str, Any]

name), feasible, constraints (value, margin, satisfied and

dict[str, Any]

tolerance at the best point), pareto_front (several objectives

dict[str, Any]

only), history (one entry per trial), stop_reason and

dict[str, Any]

evaluations (per phase).

Raises:

Type Description
OptimizationConfigurationError

If a budget is < 1, or the design space or the backend settings are invalid.

OptimizationExecutionError

If no trial completed or the run was aborted. Its partial_result keeps the trials made so far.

Source code in src/mdo_framework/optimization/optimizer.py
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
def optimize(
    self,
    n_steps: int = 10,
    n_init: int = 5,
    evaluate_x0: bool | None = None,
    max_consecutive_failures: int = 5,
    seed: int | None = None,
) -> dict[str, Any]:
    """Runs Bayesian optimization using a GEMSEO MDOScenario.

    The tools are called ``n_init + n_steps`` times, plus once for the
    start point x0 when it is evaluated. Fewer calls happen only when the
    run stops early: the search space is exhausted, ``max_consecutive_failures``
    trials fail in a row or the time limit is reached.

    Args:
        n_steps: Model-driven trials, at least 1.
        n_init: Initial trials, at least 1.
        evaluate_x0: Whether to evaluate the start point first. ``None``
            evaluates it when every design variable declares ``initial``.
        max_consecutive_failures: Failed trials in a row that end the run,
            at least 1.
        seed: Seed of the backend, ``None`` for a random one.

    Returns:
        The result: ``best_parameters``, ``best_objectives`` (by objective
        name), ``feasible``, ``constraints`` (value, margin, satisfied and
        tolerance at the best point), ``pareto_front`` (several objectives
        only), ``history`` (one entry per trial), ``stop_reason`` and
        ``evaluations`` (per phase).

    Raises:
        OptimizationConfigurationError: If a budget is < 1, or the design
            space or the backend settings are invalid.
        OptimizationExecutionError: If no trial completed or the run was
            aborted. Its ``partial_result`` keeps the trials made so far.
    """
    for budget_name, budget in (
        ("n_steps", n_steps),
        ("n_init", n_init),
        ("max_consecutive_failures", max_consecutive_failures),
    ):
        if budget < 1:
            raise OptimizationConfigurationError(
                f"{budget_name} must be >= 1, got {budget}."
            )
    discipline, design_space, objective_names = self._prepare_scenario_context()
    scenario = self._create_scenario(
        discipline=discipline,
        design_space=design_space,
        objective_names=objective_names,
        maximize_objective=len(self.objectives) == 1
        and not self.objectives[0].minimize,
        name=f"MDOScenario_{self.algorithm}",
    )
    settings_kwargs: dict[str, Any] = {
        "design_variables": self.design_variables,
        "objectives": self.objectives,
        "constraints": self.constraints,
        "parameter_constraints": self.parameter_constraints,
        "n_init": n_init,
        "n_steps": n_steps,
        "evaluate_x0": evaluate_x0,
        "seed": seed,
        "max_consecutive_failures": max_consecutive_failures,
    }
    if self.use_bonsai:
        settings_kwargs["use_bonsai"] = True
    library = ALGORITHMS[self.algorithm](self.algorithm)

    try:
        library.execute(
            scenario.formulation.optimization_problem,
            settings_model=self._settings_class(**settings_kwargs),
        )
        if library.result is not None and library.result.best is not None:
            self._write_reports(scenario)
    except (
        OptimizationConfigurationError,
        OptimizationExecutionError,
        RemoteEvaluationContractError,
        RemoteEvaluationTransportError,
    ) as error:
        if getattr(error, "partial_result", None) is None:
            error.partial_result = self._partial_result(library)
        raise
    except Exception as e:
        logger.error(f"Optimization failed: {e}", exc_info=True)
        raise OptimizationExecutionError(
            f"Optimization failed: {e}",
            partial_result=self._partial_result(library),
        ) from e

    result = library.result
    if result is None or result.best is None:
        raise OptimizationExecutionError(
            _no_completed_trial_message(result),
            partial_result=self._partial_result(library),
        )
    return _result_contract(result)

Evaluator

mdo_framework.optimization.optimizer.Evaluator

Bases: Protocol

Source code in src/mdo_framework/optimization/optimizer.py
147
148
149
150
151
152
153
154
class Evaluator(Protocol):
    def evaluate(
        self,
        parameters: dict[str, Any],
        objectives: list[str],
    ) -> dict[str, float]:
        """Evaluates the requested objectives given the design parameters."""
        ...

evaluate(parameters, objectives)

Evaluates the requested objectives given the design parameters.

Source code in src/mdo_framework/optimization/optimizer.py
148
149
150
151
152
153
154
def evaluate(
    self,
    parameters: dict[str, Any],
    objectives: list[str],
) -> dict[str, float]:
    """Evaluates the requested objectives given the design parameters."""
    ...

LocalEvaluator

mdo_framework.core.evaluators.LocalEvaluator

Evaluates the design parameters locally using a GEMSEO MDA instance.

Parameters:

Name Type Description Default
problem Discipline

An instantiated GEMSEO MDA (or Discipline) object.

required
variable_specs dict[str, ParameterDefinition] | None

Optional parameter definitions per variable name (GraphProblemBuilder.variable_specs). Required to pass declared choice values to evaluate; they are converted to GEMSEO indices.

None
Source code in src/mdo_framework/core/evaluators.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class LocalEvaluator:
    """Evaluates the design parameters locally using a GEMSEO MDA instance.

    Args:
        problem: An instantiated GEMSEO MDA (or Discipline) object.
        variable_specs: Optional parameter definitions per variable name
            (``GraphProblemBuilder.variable_specs``). Required to pass declared
            choice values to ``evaluate``; they are converted to GEMSEO indices.
    """

    def __init__(
        self,
        problem: Discipline,
        variable_specs: dict[str, ParameterDefinition] | None = None,
    ):
        self.problem = problem
        self.variable_specs = variable_specs or {}

    def evaluate(
        self,
        parameters: dict[str, Any],
        objectives: list[str],
    ) -> dict[str, float]:
        # GEMSEO uses a dictionary with string keys and numpy array values for local_data
        input_data = encode_tool_inputs(parameters, self.variable_specs)

        # We need to provide all required inputs for the MDA, not just parameters.
        # This will be passed and merged internally by execute.
        output_data = self.problem.execute(input_data)

        results = {}
        for obj in objectives:
            val = output_data.get(obj)
            if val is None:
                raise KeyError(f"Missing objective or constraint output: {obj}")
            results[obj] = (
                float(val[0])
                if isinstance(val, np.ndarray) and val.size > 0
                else float(val)
            )
        return results

RemoteEvaluator

RemoteEvaluator distinguishes transport failures from invalid execution-service responses so service layers can map them to different HTTP statuses.

mdo_framework.optimization.optimizer.RemoteEvaluator

Evaluates the design parameters remotely by communicating with the Execution microservice.

Parameters:

Name Type Description Default
service_url str

The URL of the execution service.

required
Source code in src/mdo_framework/optimization/optimizer.py
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
class RemoteEvaluator:
    """Evaluates the design parameters remotely by communicating with the Execution microservice.

    Args:
        service_url: The URL of the execution service.

    """

    def __init__(
        self,
        service_url: str,
        client: httpx.Client | None = None,
        timeout: httpx.Timeout | None = None,
    ):
        self.service_url = service_url.rstrip("/")
        self._owns_client = client is None
        self.client = client or httpx.Client(
            base_url=self.service_url,
            timeout=timeout or httpx.Timeout(30.0, connect=5.0),
        )

    def close(self) -> None:
        if self._owns_client:
            self.client.close()

    def evaluate(
        self,
        parameters: dict[str, Any],
        objectives: list[str],
    ) -> dict[str, float]:
        payload = {
            "inputs": parameters,
            "objectives": objectives,
        }
        try:
            response = self.client.post(f"{self.service_url}/evaluate", json=payload)
            response.raise_for_status()
        except httpx.TimeoutException as exc:
            raise RemoteEvaluationTransportError(
                "Execution service request timed out."
            ) from exc
        except httpx.HTTPStatusError as exc:
            if exc.response.status_code >= 500:
                raise RemoteEvaluationTransportError(
                    f"Execution service returned HTTP {exc.response.status_code}."
                ) from exc
            detail = _response_detail(exc.response)
            if (error := evaluation_error_from_payload(detail)) is not None:
                raise error from exc
            raise RemoteEvaluationContractError(
                "Execution service rejected the evaluation request with "
                f"HTTP {exc.response.status_code}"
                + (f": {detail}" if detail is not None else ".")
            ) from exc
        except httpx.RequestError as exc:
            raise RemoteEvaluationTransportError(
                "Execution service request failed."
            ) from exc

        try:
            data = response.json()
        except ValueError as exc:
            raise RemoteEvaluationContractError(
                "Execution service returned invalid JSON."
            ) from exc

        results = data.get("results")
        if not isinstance(results, dict):
            raise RemoteEvaluationContractError(
                "Execution service response is missing a 'results' object."
            )

        missing_objectives = [name for name in objectives if name not in results]
        if missing_objectives:
            raise RemoteEvaluationContractError(
                "Execution service response is missing requested objectives: "
                + ", ".join(missing_objectives)
                + "."
            )

        normalized_results: dict[str, float] = {}
        for objective_name in objectives:
            try:
                normalized_results[objective_name] = float(results[objective_name])
            except (TypeError, ValueError) as exc:
                raise RemoteEvaluationContractError(
                    f"Execution service returned a non-numeric value for {objective_name}."
                ) from exc
        return normalized_results