Skip to content

Validation

The preflight and the dependency walk behind it. See Study Schema for the finding codes.

mdo_framework.validation

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/.

LinearConstraint dataclass

Linear inequality over design variables, as sum(c * x) <= bound.

Attributes:

Name Type Description
expression str

Original constraint text.

coefficients dict[str, float]

Coefficient of each referenced variable, none being zero.

bound float

Right-hand side of the normalized inequality.

Source code in src/mdo_framework/validation.py
44
45
46
47
48
49
50
51
52
53
54
55
56
@dataclass(frozen=True)
class LinearConstraint:
    """Linear inequality over design variables, as ``sum(c * x) <= bound``.

    Attributes:
        expression: Original constraint text.
        coefficients: Coefficient of each referenced variable, none being zero.
        bound: Right-hand side of the normalized inequality.
    """

    expression: str
    coefficients: dict[str, float]
    bound: float

ParameterConstraintError

Bases: ValueError

Raised when a parameter constraint expression is not usable.

Source code in src/mdo_framework/validation.py
59
60
class ParameterConstraintError(ValueError):
    """Raised when a parameter constraint expression is not usable."""

check_tool_signature(tool, func)

Check that a tool function accepts exactly the graph inputs by keyword.

Parameters:

Name Type Description Default
tool ToolSpec

Tool declaration whose inputs are passed as keyword arguments.

required
func Callable[..., Any]

Python callable registered for the tool.

required

Returns:

Type Description
list[Finding]

The error findings and the warning findings. A tool whose inputs are

list[Finding]

not all passed as distinct arguments gets ARG_MAP_COLLISION errors

tuple[list[Finding], list[Finding]]

and no signature check, as there is no single call to check.

Source code in src/mdo_framework/validation.py
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
def check_tool_signature(
    tool: ToolSpec, func: Callable[..., Any]
) -> tuple[list[Finding], list[Finding]]:
    """Check that a tool function accepts exactly the graph inputs by keyword.

    Args:
        tool: Tool declaration whose inputs are passed as keyword arguments.
        func: Python callable registered for the tool.

    Returns:
        The error findings and the warning findings. A tool whose inputs are
        not all passed as distinct arguments gets ``ARG_MAP_COLLISION`` errors
        and no signature check, as there is no single call to check.
    """
    collisions = _collision_findings(tool)
    if collisions:
        return collisions, []
    try:
        signature = inspect.signature(func)
    except (TypeError, ValueError):
        return [], [
            Finding(
                code="SIGNATURE_UNCHECKED",
                message=f"{tool.name}: signature is not introspectable",
                names=(tool.name,),
            )
        ]
    parameters = list(signature.parameters.values())
    if any(item.kind is inspect.Parameter.VAR_KEYWORD for item in parameters):
        return [], [
            Finding(
                code="SIGNATURE_UNCHECKED",
                message=f"{tool.name} accepts **kwargs; inputs cannot be checked",
                names=(tool.name,),
            )
        ]

    errors: list[Finding] = []
    arguments = [tool.arg_map.get(name, name) for name in tool.inputs]
    renames = {
        name: argument
        for name, argument in zip(tool.inputs, arguments, strict=True)
        if name != argument
    }
    try:
        signature.bind(**dict.fromkeys(arguments))
    except TypeError as exc:
        called_with = f"the graph inputs {list(tool.inputs)}"
        if renames:
            mapping = ", ".join(f"{name} -> {arg}" for name, arg in renames.items())
            called_with += f" as the arguments {arguments} ({mapping})"
        errors.append(
            Finding(
                code="SIGNATURE_MISMATCH",
                message=(
                    f"tool '{tool.name}' is called with {called_with} "
                    f"but its signature {signature} does not accept them: {exc}"
                ),
                names=(tool.name, *tool.inputs),
            )
        )
    warnings = [
        Finding(
            code="DEFAULTED_ARG_UNWIRED",
            message=(
                f"tool '{tool.name}' parameter '{item.name}' has a default "
                f"value and is not a graph input{_renamed_hint(item.name, renames)}; "
                "the default will be used"
            ),
            names=(tool.name, item.name),
        )
        for item in parameters
        if item.default is not inspect.Parameter.empty and item.name not in arguments
    ]
    return errors, warnings

dependency_findings(walk)

Turn the unresolved parts of a dependency walk into error findings.

Parameters:

Name Type Description Default
walk DependencyWalk

Result of walk_dependencies.

required

Returns:

Type Description
list[Finding]

UNKNOWN_OUTPUT, NOT_PRODUCED and UNPRODUCED_STATE findings,

list[Finding]

in that order.

Source code in src/mdo_framework/validation.py
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
def dependency_findings(walk: DependencyWalk) -> list[Finding]:
    """Turn the unresolved parts of a dependency walk into error findings.

    Args:
        walk: Result of ``walk_dependencies``.

    Returns:
        ``UNKNOWN_OUTPUT``, ``NOT_PRODUCED`` and ``UNPRODUCED_STATE`` findings,
        in that order.
    """
    errors = [
        Finding(
            code="UNKNOWN_OUTPUT",
            message=f"'{name}' is not a declared variable",
            names=(name,),
        )
        for name in walk.unknown_targets
    ]
    errors.extend(
        Finding(
            code="NOT_PRODUCED",
            message=f"'{name}' is not produced by any tool",
            names=(name,),
        )
        for name in walk.unproduced_targets
    )
    errors.extend(
        Finding(
            code="UNPRODUCED_STATE",
            message=(
                f"state variable '{name}' is an input of a required tool "
                "but no tool produces it"
            ),
            names=(name,),
        )
        for name in walk.unproduced_states
    )
    return errors

parse_parameter_constraints(expressions, design_variables)

Parse linear constraints written in the Ax grammar.

Each expression is <lhs> <= <rhs> or <lhs> >= <rhs> where a side is a sum of numbers, names and <number>*<name> terms. It is normalized to sum(coefficient * variable) <= bound.

Parameters:

Name Type Description Default
expressions Sequence[str]

Constraint expressions.

required
design_variables Sequence[DesignVariable]

Design variables the expressions may reference.

required

Returns:

Type Description
list[LinearConstraint]

One normalized constraint per expression, in order.

Raises:

Type Description
ParameterConstraintError

If an expression cannot be parsed, references an unknown variable or a choice variable, or has no variable left.

Source code in src/mdo_framework/validation.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def parse_parameter_constraints(
    expressions: Sequence[str], design_variables: Sequence[DesignVariable]
) -> list[LinearConstraint]:
    """Parse linear constraints written in the Ax grammar.

    Each expression is ``<lhs> <= <rhs>`` or ``<lhs> >= <rhs>`` where a side is
    a sum of numbers, names and ``<number>*<name>`` terms. It is normalized to
    ``sum(coefficient * variable) <= bound``.

    Args:
        expressions: Constraint expressions.
        design_variables: Design variables the expressions may reference.

    Returns:
        One normalized constraint per expression, in order.

    Raises:
        ParameterConstraintError: If an expression cannot be parsed, references
            an unknown variable or a choice variable, or has no variable left.
    """
    by_name = {variable.name: variable for variable in design_variables}
    return [_parse_constraint(expression, by_name) for expression in expressions]

thread_safety_findings(schema, couplings)

Flag the coupled tools that do not declare thread_safe.

A tool belongs to a coupled group when it produces a coupling variable; a tool that only reads one runs outside the group.

Parameters:

Name Type Description Default
schema StudySchema

Study whose tools are checked.

required
couplings Collection[str]

Names of the coupling variables, as returned by walk_dependencies.

required

Returns:

Type Description
list[Finding]

One TOOL_NOT_THREAD_SAFE finding per such tool, in tool order.

Source code in src/mdo_framework/validation.py
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
def thread_safety_findings(
    schema: StudySchema, couplings: Collection[str]
) -> list[Finding]:
    """Flag the coupled tools that do not declare ``thread_safe``.

    A tool belongs to a coupled group when it produces a coupling variable;
    a tool that only reads one runs outside the group.

    Args:
        schema: Study whose tools are checked.
        couplings: Names of the coupling variables, as returned by
            ``walk_dependencies``.

    Returns:
        One ``TOOL_NOT_THREAD_SAFE`` finding per such tool, in tool order.
    """
    return [
        Finding(
            code="TOOL_NOT_THREAD_SAFE",
            message=(
                f"tool '{tool.name}' is in a coupled group evaluated in parallel "
                "but is not declared thread_safe; set thread_safe=True on the "
                "tool or run the MDA sequentially"
            ),
            names=(tool.name,),
        )
        for tool in schema.tools
        if not tool.thread_safe and any(name in couplings for name in tool.outputs)
    ]

validate_registry(schema, registry)

Check every schema tool against the tool registry.

Parameters:

Name Type Description Default
schema StudySchema

Study whose tools must be registered.

required
registry Mapping[str, Callable[..., Any]]

Tool name to Python function.

required

Returns:

Type Description
ValidationReport

Report whose errors are UNREGISTERED_TOOL for every missing tool,

ValidationReport

then, for each tool in order, its ARG_MAP_UNKNOWN_INPUT errors, its

ValidationReport

ARG_MAP_COLLISION errors and, if it is registered and has no

ValidationReport

collision, the signature errors. The warnings are the signature

ValidationReport

warnings.

Source code in src/mdo_framework/validation.py
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
def validate_registry(
    schema: StudySchema, registry: Mapping[str, Callable[..., Any]]
) -> ValidationReport:
    """Check every schema tool against the tool registry.

    Args:
        schema: Study whose tools must be registered.
        registry: Tool name to Python function.

    Returns:
        Report whose errors are ``UNREGISTERED_TOOL`` for every missing tool,
        then, for each tool in order, its ``ARG_MAP_UNKNOWN_INPUT`` errors, its
        ``ARG_MAP_COLLISION`` errors and, if it is registered and has no
        collision, the signature errors. The warnings are the signature
        warnings.
    """
    errors = [
        Finding(
            code="UNREGISTERED_TOOL",
            message=f"tool '{tool.name}' has no registered function",
            names=(tool.name,),
        )
        for tool in schema.tools
        if tool.name not in registry
    ]
    warnings: list[Finding] = []
    for tool in schema.tools:
        errors.extend(_unknown_input_findings(tool))
        if tool.name in registry:
            tool_errors, tool_warnings = check_tool_signature(tool, registry[tool.name])
            errors.extend(tool_errors)
            warnings.extend(tool_warnings)
        else:
            errors.extend(_collision_findings(tool))
    return ValidationReport(errors=tuple(errors), warnings=tuple(warnings))

validate_study(schema, *, objectives, constraints=(), parameter_constraints=(), registry=None)

Check that a study can run, without calling any tool.

Every applicable finding is reported; nothing stops at the first error.

Parameters:

Name Type Description Default
schema StudySchema

Study to validate.

required
objectives Sequence[ObjectiveSpec]

Objectives, whose names are the first targets.

required
constraints Sequence[ConstraintSpec]

Constraints, whose names follow the objectives as targets.

()
parameter_constraints Sequence[str]

Linear constraints on the design variables, in the Ax grammar.

()
registry Mapping[str, Callable[..., Any]] | None

Optional mapping of tool name to Python function. When given, every schema tool must be registered with a compatible signature.

None

Returns:

Type Description
ValidationReport

Report listing the errors and warnings.

Source code in src/mdo_framework/validation.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
def validate_study(
    schema: StudySchema,
    *,
    objectives: Sequence[ObjectiveSpec],
    constraints: Sequence[ConstraintSpec] = (),
    parameter_constraints: Sequence[str] = (),
    registry: Mapping[str, Callable[..., Any]] | None = None,
) -> ValidationReport:
    """Check that a study can run, without calling any tool.

    Every applicable finding is reported; nothing stops at the first error.

    Args:
        schema: Study to validate.
        objectives: Objectives, whose names are the first targets.
        constraints: Constraints, whose names follow the objectives as targets.
        parameter_constraints: Linear constraints on the design variables, in
            the Ax grammar.
        registry: Optional mapping of tool name to Python function. When given,
            every schema tool must be registered with a compatible signature.

    Returns:
        Report listing the errors and warnings.
    """
    targets = [item.name for item in (*objectives, *constraints)]
    walk = walk_dependencies(schema, targets)
    has_targets = bool(targets)

    errors = _resolution_errors(walk, has_targets)
    signature_warnings: tuple[Finding, ...] = ()
    if registry is not None:
        registry_report = validate_registry(schema, registry)
        errors.extend(registry_report.errors)
        signature_warnings = registry_report.warnings
    errors.extend(_search_space_errors(walk.design_variables, parameter_constraints))

    warnings = [
        *_coupling_warnings(schema, walk),
        *_unused_warnings(schema, walk, has_targets),
        *signature_warnings,
        *_partial_initial_warnings(walk.design_variables),
        *_constraint_scale_warnings(constraints),
    ]
    return ValidationReport(errors=tuple(errors), warnings=tuple(warnings))

mdo_framework.core.dependencies

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/.

DependencyWalk dataclass

Everything a set of target outputs depends on in a study.

Variables and tools follow the order of the schema (FalkorDB insertion order), never the traversal or alphabetical order.

Attributes:

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

Required range and choice variables.

fixed_parameters tuple[FixedParam, ...]

Required fixed parameters.

tools tuple[str, ...]

Names of the required tools.

unknown_targets tuple[str, ...]

Targets that are not declared variables, in target order.

unproduced_targets tuple[str, ...]

Declared targets that no tool produces, in target order.

unproduced_states tuple[str, ...]

Required state inputs that no tool produces.

couplings tuple[str, ...]

State variables exchanged inside a tool cycle, over the whole schema and not only the required tools.

Source code in src/mdo_framework/core/dependencies.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@dataclass(frozen=True)
class DependencyWalk:
    """Everything a set of target outputs depends on in a study.

    Variables and tools follow the order of the schema (FalkorDB insertion
    order), never the traversal or alphabetical order.

    Attributes:
        design_variables: Required range and choice variables.
        fixed_parameters: Required fixed parameters.
        tools: Names of the required tools.
        unknown_targets: Targets that are not declared variables, in target order.
        unproduced_targets: Declared targets that no tool produces, in target order.
        unproduced_states: Required state inputs that no tool produces.
        couplings: State variables exchanged inside a tool cycle, over the whole
            schema and not only the required tools.
    """

    design_variables: tuple[DesignVariable, ...]
    fixed_parameters: tuple[FixedParam, ...]
    tools: tuple[str, ...]
    unknown_targets: tuple[str, ...]
    unproduced_targets: tuple[str, ...]
    unproduced_states: tuple[str, ...]
    couplings: tuple[str, ...]

walk_dependencies(schema, targets)

Resolve the tools and inputs required to compute the target outputs.

Parameters:

Name Type Description Default
schema StudySchema

Study whose variables and tools are traversed.

required
targets Sequence[str]

Names of the variables to compute.

required

Returns:

Type Description
DependencyWalk

The required design variables, fixed parameters and tools, the targets

DependencyWalk

and inputs that cannot be resolved, and the coupling variables.

Source code in src/mdo_framework/core/dependencies.py
 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
def walk_dependencies(schema: StudySchema, targets: Sequence[str]) -> DependencyWalk:
    """Resolve the tools and inputs required to compute the target outputs.

    Args:
        schema: Study whose variables and tools are traversed.
        targets: Names of the variables to compute.

    Returns:
        The required design variables, fixed parameters and tools, the targets
        and inputs that cannot be resolved, and the coupling variables.
    """
    variables = {variable.name: variable for variable in schema.variables}
    producers = schema.producers()
    tools = {tool.name: tool for tool in schema.tools}
    unique_targets = list(dict.fromkeys(targets))

    required_tools: set[str] = set()
    required_inputs: set[str] = set()
    unproduced_states: set[str] = set()
    pending = [producers[name] for name in unique_targets if name in producers]
    while pending:
        tool_name = pending.pop()
        if tool_name in required_tools:
            continue
        required_tools.add(tool_name)
        for input_name in tools[tool_name].inputs:
            if not isinstance(variables[input_name], StateVar):
                required_inputs.add(input_name)
            elif input_name in producers:
                pending.append(producers[input_name])
            else:
                unproduced_states.add(input_name)

    ordered_inputs = [
        variable for variable in schema.variables if variable.name in required_inputs
    ]
    return DependencyWalk(
        design_variables=tuple(
            variable
            for variable in ordered_inputs
            if not isinstance(variable, FixedParam)
        ),
        fixed_parameters=tuple(
            variable for variable in ordered_inputs if isinstance(variable, FixedParam)
        ),
        tools=tuple(tool.name for tool in schema.tools if tool.name in required_tools),
        unknown_targets=tuple(name for name in unique_targets if name not in variables),
        unproduced_targets=tuple(
            name
            for name in unique_targets
            if name in variables and name not in producers
        ),
        unproduced_states=tuple(
            variable.name
            for variable in schema.variables
            if variable.name in unproduced_states
        ),
        couplings=_find_couplings(schema),
    )