Skip to content

Bayesian Optimization Specs

The BO specification API describes optimization intent, controllable variables, objectives, and output constraints before fitting a surrogate or selecting a concrete acquisition implementation.

matgpr.bayesian_optimization_specs

Reusable Bayesian-optimization intent and search-space specifications.

This module defines JSON-friendly records for describing materials BO problems before a concrete optimizer is selected. The records are intentionally light: they capture objectives, controllable variables, output constraints, and the recommended acquisition-function families without fitting a model.

BOOptimizationMode

Bases: str, Enum

High-level BO workflow requested by the user.

Source code in matgpr/bayesian_optimization_specs.py
33
34
35
36
37
class BOOptimizationMode(str, Enum):
    """High-level BO workflow requested by the user."""

    FINITE_POOL_RANKING = "finite_pool_ranking"
    FEATURE_OPTIMIZATION = "feature_optimization"

BOFeatureType

Bases: str, Enum

Type of a controllable input variable.

Source code in matgpr/bayesian_optimization_specs.py
40
41
42
43
44
45
46
class BOFeatureType(str, Enum):
    """Type of a controllable input variable."""

    CONTINUOUS = "continuous"
    INTEGER = "integer"
    CATEGORICAL = "categorical"
    FIXED = "fixed"

BOObjectiveMode

Bases: str, Enum

How the target output should be optimized.

Source code in matgpr/bayesian_optimization_specs.py
49
50
51
52
53
54
55
class BOObjectiveMode(str, Enum):
    """How the target output should be optimized."""

    MAXIMIZE = "maximize"
    MINIMIZE = "minimize"
    TARGET_VALUE = "target_value"
    TARGET_RANGE = "target_range"

BOAcquisitionIntent

Bases: str, Enum

Acquisition-function family suitable for a BO request.

Source code in matgpr/bayesian_optimization_specs.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class BOAcquisitionIntent(str, Enum):
    """Acquisition-function family suitable for a BO request."""

    EXPECTED_IMPROVEMENT = "expected_improvement"
    NOISY_EXPECTED_IMPROVEMENT = "noisy_expected_improvement"
    UPPER_CONFIDENCE_BOUND = "upper_confidence_bound"
    LOWER_CONFIDENCE_BOUND = "lower_confidence_bound"
    PROBABILITY_OF_IMPROVEMENT = "probability_of_improvement"
    TARGET_PROBABILITY = "target_probability"
    CONSTRAINED_EXPECTED_IMPROVEMENT = "constrained_expected_improvement"
    CONSTRAINED_NOISY_EXPECTED_IMPROVEMENT = "constrained_noisy_expected_improvement"
    MULTI_OBJECTIVE_EHVI = "multi_objective_expected_hypervolume_improvement"
    SCALARIZED_EXPECTED_IMPROVEMENT = "scalarized_expected_improvement"
    THOMPSON_SAMPLING = "thompson_sampling"
    UNCERTAINTY_SAMPLING = "uncertainty_sampling"
    COST_AWARE_EXPECTED_IMPROVEMENT = "cost_aware_expected_improvement"

BOFeatureSpec dataclass

Specification for one controllable or fixed BO input feature.

Parameters:

Name Type Description Default
name str

Input feature or process variable name.

required
variable_type BOFeatureType | str

Whether the feature is continuous, integer, categorical, or fixed.

CONTINUOUS
lower_bound float | None

Numeric bounds for continuous and integer variables.

None
upper_bound float | None

Numeric bounds for continuous and integer variables.

None
values Sequence[Any] | None

Allowed category values for categorical variables.

None
fixed_value Any | None

Value for fixed context variables that should not be optimized.

None
units str | None

Optional units shown to users and persisted in audit records.

None
transform str | None

Optional transform name such as "log" or "standardized".

None
metadata Mapping[str, Any]

Extra JSON-safe information for applications.

dict()
Source code in matgpr/bayesian_optimization_specs.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
@dataclass(frozen=True, slots=True)
class BOFeatureSpec:
    """Specification for one controllable or fixed BO input feature.

    Parameters
    ----------
    name
        Input feature or process variable name.
    variable_type
        Whether the feature is continuous, integer, categorical, or fixed.
    lower_bound, upper_bound
        Numeric bounds for continuous and integer variables.
    values
        Allowed category values for categorical variables.
    fixed_value
        Value for fixed context variables that should not be optimized.
    units
        Optional units shown to users and persisted in audit records.
    transform
        Optional transform name such as ``"log"`` or ``"standardized"``.
    metadata
        Extra JSON-safe information for applications.
    """

    name: str
    variable_type: BOFeatureType | str = BOFeatureType.CONTINUOUS
    lower_bound: float | None = None
    upper_bound: float | None = None
    values: Sequence[Any] | None = None
    fixed_value: Any | None = None
    units: str | None = None
    transform: str | None = None
    metadata: Mapping[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        variable_type = _coerce_enum(BOFeatureType, self.variable_type)
        lower_bound = _optional_finite_float(self.lower_bound, "lower_bound")
        upper_bound = _optional_finite_float(self.upper_bound, "upper_bound")
        values = None if self.values is None else tuple(self.values)

        if lower_bound is not None and upper_bound is not None:
            if lower_bound > upper_bound:
                raise ValueError("lower_bound must be <= upper_bound")

        if variable_type in {BOFeatureType.CONTINUOUS, BOFeatureType.INTEGER}:
            if lower_bound is None or upper_bound is None:
                raise ValueError(
                    f"{variable_type.value} feature requires lower_bound and upper_bound"
                )
            if variable_type is BOFeatureType.INTEGER and (
                not lower_bound.is_integer() or not upper_bound.is_integer()
            ):
                raise ValueError("integer feature bounds must be integer-valued")
        elif variable_type is BOFeatureType.CATEGORICAL:
            if not values:
                raise ValueError("categorical feature requires non-empty values")
        elif variable_type is BOFeatureType.FIXED and self.fixed_value is None:
            raise ValueError("fixed feature requires fixed_value")

        object.__setattr__(self, "name", _clean_text(self.name, "name"))
        object.__setattr__(self, "variable_type", variable_type)
        object.__setattr__(self, "lower_bound", lower_bound)
        object.__setattr__(self, "upper_bound", upper_bound)
        object.__setattr__(self, "values", values)
        object.__setattr__(self, "units", _clean_optional_text(self.units))
        object.__setattr__(self, "transform", _clean_optional_text(self.transform))
        object.__setattr__(self, "metadata", dict(self.metadata))

    @property
    def is_controllable(self) -> bool:
        """Whether this feature should be optimized by the BO routine."""

        return self.variable_type is not BOFeatureType.FIXED

    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-safe feature specification."""

        return {
            "name": self.name,
            "variable_type": self.variable_type.value,
            "lower_bound": self.lower_bound,
            "upper_bound": self.upper_bound,
            "values": _json_safe(self.values),
            "fixed_value": _json_safe(self.fixed_value),
            "units": self.units,
            "transform": self.transform,
            "is_controllable": self.is_controllable,
            "metadata": _json_safe(self.metadata),
        }

is_controllable property

Whether this feature should be optimized by the BO routine.

to_dict()

Return a JSON-safe feature specification.

Source code in matgpr/bayesian_optimization_specs.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-safe feature specification."""

    return {
        "name": self.name,
        "variable_type": self.variable_type.value,
        "lower_bound": self.lower_bound,
        "upper_bound": self.upper_bound,
        "values": _json_safe(self.values),
        "fixed_value": _json_safe(self.fixed_value),
        "units": self.units,
        "transform": self.transform,
        "is_controllable": self.is_controllable,
        "metadata": _json_safe(self.metadata),
    }

BOObjectivePreference dataclass

Target objective preference for a BO campaign.

Use TARGET_VALUE or TARGET_RANGE for process-development settings where the best experiment is near a specification window rather than at an extreme value.

Source code in matgpr/bayesian_optimization_specs.py
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
@dataclass(frozen=True, slots=True)
class BOObjectivePreference:
    """Target objective preference for a BO campaign.

    Use ``TARGET_VALUE`` or ``TARGET_RANGE`` for process-development settings
    where the best experiment is near a specification window rather than at an
    extreme value.
    """

    target_name: str
    mode: BOObjectiveMode | str = BOObjectiveMode.MAXIMIZE
    target_value: float | None = None
    target_lower_bound: float | None = None
    target_upper_bound: float | None = None
    weight: float = 1.0
    units: str | None = None
    metadata: Mapping[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        mode = _coerce_enum(BOObjectiveMode, self.mode)
        target_value = _optional_finite_float(self.target_value, "target_value")
        target_lower_bound = _optional_finite_float(
            self.target_lower_bound,
            "target_lower_bound",
        )
        target_upper_bound = _optional_finite_float(
            self.target_upper_bound,
            "target_upper_bound",
        )
        if target_lower_bound is not None and target_upper_bound is not None:
            if target_lower_bound > target_upper_bound:
                raise ValueError("target_lower_bound must be <= target_upper_bound")
        if mode is BOObjectiveMode.TARGET_VALUE and target_value is None:
            raise ValueError("target_value mode requires target_value")
        if mode is BOObjectiveMode.TARGET_RANGE and (
            target_lower_bound is None or target_upper_bound is None
        ):
            raise ValueError("target_range mode requires target_lower_bound and target_upper_bound")

        weight = _positive_finite_float(self.weight, "weight")
        object.__setattr__(self, "target_name", _clean_text(self.target_name))
        object.__setattr__(self, "mode", mode)
        object.__setattr__(self, "target_value", target_value)
        object.__setattr__(self, "target_lower_bound", target_lower_bound)
        object.__setattr__(self, "target_upper_bound", target_upper_bound)
        object.__setattr__(self, "weight", weight)
        object.__setattr__(self, "units", _clean_optional_text(self.units))
        object.__setattr__(self, "metadata", dict(self.metadata))

    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-safe objective preference."""

        return {
            "target_name": self.target_name,
            "mode": self.mode.value,
            "target_value": self.target_value,
            "target_lower_bound": self.target_lower_bound,
            "target_upper_bound": self.target_upper_bound,
            "weight": self.weight,
            "units": self.units,
            "metadata": _json_safe(self.metadata),
        }

to_dict()

Return a JSON-safe objective preference.

Source code in matgpr/bayesian_optimization_specs.py
216
217
218
219
220
221
222
223
224
225
226
227
228
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-safe objective preference."""

    return {
        "target_name": self.target_name,
        "mode": self.mode.value,
        "target_value": self.target_value,
        "target_lower_bound": self.target_lower_bound,
        "target_upper_bound": self.target_upper_bound,
        "weight": self.weight,
        "units": self.units,
        "metadata": _json_safe(self.metadata),
    }

BOOutputConstraintSpec dataclass

Constraint on a predicted output or measured property.

Source code in matgpr/bayesian_optimization_specs.py
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
@dataclass(frozen=True, slots=True)
class BOOutputConstraintSpec:
    """Constraint on a predicted output or measured property."""

    target_name: str
    lower_bound: float | None = None
    upper_bound: float | None = None
    probability_threshold: float | None = None
    inclusive: bool = True
    units: str | None = None
    metadata: Mapping[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        lower_bound = _optional_finite_float(self.lower_bound, "lower_bound")
        upper_bound = _optional_finite_float(self.upper_bound, "upper_bound")
        if lower_bound is None and upper_bound is None:
            raise ValueError("output constraint requires at least one bound")
        if lower_bound is not None and upper_bound is not None:
            if lower_bound > upper_bound:
                raise ValueError("lower_bound must be <= upper_bound")
        probability_threshold = _optional_unit_interval_float(
            self.probability_threshold,
            "probability_threshold",
        )
        object.__setattr__(self, "target_name", _clean_text(self.target_name))
        object.__setattr__(self, "lower_bound", lower_bound)
        object.__setattr__(self, "upper_bound", upper_bound)
        object.__setattr__(self, "probability_threshold", probability_threshold)
        object.__setattr__(self, "inclusive", bool(self.inclusive))
        object.__setattr__(self, "units", _clean_optional_text(self.units))
        object.__setattr__(self, "metadata", dict(self.metadata))

    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-safe output-constraint specification."""

        return {
            "target_name": self.target_name,
            "lower_bound": self.lower_bound,
            "upper_bound": self.upper_bound,
            "probability_threshold": self.probability_threshold,
            "inclusive": self.inclusive,
            "units": self.units,
            "metadata": _json_safe(self.metadata),
        }

to_dict()

Return a JSON-safe output-constraint specification.

Source code in matgpr/bayesian_optimization_specs.py
263
264
265
266
267
268
269
270
271
272
273
274
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-safe output-constraint specification."""

    return {
        "target_name": self.target_name,
        "lower_bound": self.lower_bound,
        "upper_bound": self.upper_bound,
        "probability_threshold": self.probability_threshold,
        "inclusive": self.inclusive,
        "units": self.units,
        "metadata": _json_safe(self.metadata),
    }

BOOptimizationSpec dataclass

Complete app-neutral specification for a BO request.

Source code in matgpr/bayesian_optimization_specs.py
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
@dataclass(frozen=True, slots=True)
class BOOptimizationSpec:
    """Complete app-neutral specification for a BO request."""

    mode: BOOptimizationMode | str
    objectives: Sequence[BOObjectivePreference | Mapping[str, Any]]
    features: Sequence[BOFeatureSpec | Mapping[str, Any]] = ()
    output_constraints: Sequence[BOOutputConstraintSpec | Mapping[str, Any]] = ()
    acquisition_intent: BOAcquisitionIntent | str | None = None
    batch_size: int = 1
    random_seed: int | None = None
    cost_column: str | None = None
    metadata: Mapping[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        mode = _coerce_enum(BOOptimizationMode, self.mode)
        objectives = tuple(_coerce_objective(item) for item in self.objectives)
        features = tuple(_coerce_feature(item) for item in self.features)
        output_constraints = tuple(
            _coerce_output_constraint(item) for item in self.output_constraints
        )
        if not objectives:
            raise ValueError("BOOptimizationSpec requires at least one objective")
        if mode is BOOptimizationMode.FEATURE_OPTIMIZATION:
            if not any(feature.is_controllable for feature in features):
                raise ValueError("feature_optimization requires at least one controllable feature")
        acquisition_intent = (
            None
            if self.acquisition_intent is None
            else _coerce_enum(BOAcquisitionIntent, self.acquisition_intent)
        )
        batch_size = _positive_int(self.batch_size, "batch_size")
        random_seed = None if self.random_seed is None else int(self.random_seed)

        object.__setattr__(self, "mode", mode)
        object.__setattr__(self, "objectives", objectives)
        object.__setattr__(self, "features", features)
        object.__setattr__(self, "output_constraints", output_constraints)
        object.__setattr__(self, "acquisition_intent", acquisition_intent)
        object.__setattr__(self, "batch_size", batch_size)
        object.__setattr__(self, "random_seed", random_seed)
        object.__setattr__(
            self,
            "cost_column",
            _clean_optional_text(self.cost_column),
        )
        object.__setattr__(self, "metadata", dict(self.metadata))

    @property
    def objective_names(self) -> tuple[str, ...]:
        """Objective target names in request order."""

        return tuple(objective.target_name for objective in self.objectives)

    @property
    def controllable_feature_names(self) -> tuple[str, ...]:
        """Input features that are allowed to vary during optimization."""

        return tuple(feature.name for feature in self.features if feature.is_controllable)

    @property
    def fixed_feature_names(self) -> tuple[str, ...]:
        """Input features held fixed during optimization."""

        return tuple(
            feature.name
            for feature in self.features
            if feature.variable_type is BOFeatureType.FIXED
        )

    def recommended_acquisition_intents(self) -> tuple[BOAcquisitionIntent, ...]:
        """Return acquisition families that match the request semantics."""

        return recommend_bo_acquisition_intents(self)

    def to_dict(self) -> dict[str, Any]:
        """Return a JSON-safe BO optimization specification."""

        return {
            "mode": self.mode.value,
            "objectives": [objective.to_dict() for objective in self.objectives],
            "features": [feature.to_dict() for feature in self.features],
            "output_constraints": [constraint.to_dict() for constraint in self.output_constraints],
            "acquisition_intent": (
                None if self.acquisition_intent is None else self.acquisition_intent.value
            ),
            "recommended_acquisition_intents": [
                intent.value for intent in self.recommended_acquisition_intents()
            ],
            "batch_size": self.batch_size,
            "random_seed": self.random_seed,
            "cost_column": self.cost_column,
            "objective_names": list(self.objective_names),
            "controllable_feature_names": list(self.controllable_feature_names),
            "fixed_feature_names": list(self.fixed_feature_names),
            "metadata": _json_safe(self.metadata),
        }

objective_names property

Objective target names in request order.

controllable_feature_names property

Input features that are allowed to vary during optimization.

fixed_feature_names property

Input features held fixed during optimization.

recommended_acquisition_intents()

Return acquisition families that match the request semantics.

Source code in matgpr/bayesian_optimization_specs.py
347
348
349
350
def recommended_acquisition_intents(self) -> tuple[BOAcquisitionIntent, ...]:
    """Return acquisition families that match the request semantics."""

    return recommend_bo_acquisition_intents(self)

to_dict()

Return a JSON-safe BO optimization specification.

Source code in matgpr/bayesian_optimization_specs.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def to_dict(self) -> dict[str, Any]:
    """Return a JSON-safe BO optimization specification."""

    return {
        "mode": self.mode.value,
        "objectives": [objective.to_dict() for objective in self.objectives],
        "features": [feature.to_dict() for feature in self.features],
        "output_constraints": [constraint.to_dict() for constraint in self.output_constraints],
        "acquisition_intent": (
            None if self.acquisition_intent is None else self.acquisition_intent.value
        ),
        "recommended_acquisition_intents": [
            intent.value for intent in self.recommended_acquisition_intents()
        ],
        "batch_size": self.batch_size,
        "random_seed": self.random_seed,
        "cost_column": self.cost_column,
        "objective_names": list(self.objective_names),
        "controllable_feature_names": list(self.controllable_feature_names),
        "fixed_feature_names": list(self.fixed_feature_names),
        "metadata": _json_safe(self.metadata),
    }

recommend_bo_acquisition_intents(spec)

Recommend acquisition families for a BO request.

The recommendation is policy-light and optimizer-independent. Private platforms can layer cost, compute budget, saved-model, or user-interface policy on top while keeping the scientific semantics reusable.

Source code in matgpr/bayesian_optimization_specs.py
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
def recommend_bo_acquisition_intents(
    spec: BOOptimizationSpec | Mapping[str, Any],
) -> tuple[BOAcquisitionIntent, ...]:
    """Recommend acquisition families for a BO request.

    The recommendation is policy-light and optimizer-independent. Private
    platforms can layer cost, compute budget, saved-model, or user-interface
    policy on top while keeping the scientific semantics reusable.
    """

    optimization_spec = _coerce_optimization_spec(spec)
    if optimization_spec.acquisition_intent is not None:
        return (optimization_spec.acquisition_intent,)

    objective_modes = {objective.mode for objective in optimization_spec.objectives}
    intents: list[BOAcquisitionIntent] = []

    if len(optimization_spec.objectives) > 1:
        intents.extend(
            [
                BOAcquisitionIntent.MULTI_OBJECTIVE_EHVI,
                BOAcquisitionIntent.SCALARIZED_EXPECTED_IMPROVEMENT,
            ]
        )
    elif objective_modes & {BOObjectiveMode.TARGET_VALUE, BOObjectiveMode.TARGET_RANGE}:
        intents.append(BOAcquisitionIntent.TARGET_PROBABILITY)
    elif optimization_spec.output_constraints:
        intents.extend(
            [
                BOAcquisitionIntent.CONSTRAINED_NOISY_EXPECTED_IMPROVEMENT,
                BOAcquisitionIntent.CONSTRAINED_EXPECTED_IMPROVEMENT,
            ]
        )
    else:
        first_objective = optimization_spec.objectives[0]
        if first_objective.mode is BOObjectiveMode.MINIMIZE:
            intents.extend(
                [
                    BOAcquisitionIntent.LOWER_CONFIDENCE_BOUND,
                    BOAcquisitionIntent.NOISY_EXPECTED_IMPROVEMENT,
                ]
            )
        else:
            intents.extend(
                [
                    BOAcquisitionIntent.NOISY_EXPECTED_IMPROVEMENT,
                    BOAcquisitionIntent.EXPECTED_IMPROVEMENT,
                    BOAcquisitionIntent.UPPER_CONFIDENCE_BOUND,
                ]
            )

    if optimization_spec.output_constraints and not any(
        intent
        in {
            BOAcquisitionIntent.CONSTRAINED_NOISY_EXPECTED_IMPROVEMENT,
            BOAcquisitionIntent.CONSTRAINED_EXPECTED_IMPROVEMENT,
        }
        for intent in intents
    ):
        intents.append(BOAcquisitionIntent.CONSTRAINED_NOISY_EXPECTED_IMPROVEMENT)
    if optimization_spec.batch_size > 1:
        intents.append(BOAcquisitionIntent.THOMPSON_SAMPLING)
    if optimization_spec.cost_column is not None:
        intents.append(BOAcquisitionIntent.COST_AWARE_EXPECTED_IMPROVEMENT)

    return tuple(dict.fromkeys(intents))