Skip to content

Schema

The typed study contract. See Study Schema for the rules and the published JSON Schema.

mdo_framework.schema

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

Finite = Annotated[float, Field(strict=True, allow_inf_nan=False)] module-attribute

Finite float: rejects NaN, infinities, bool and str (int is widened).

Name = Annotated[str, StringConstraints(pattern=NAME_PATTERN, max_length=MAX_NAME_LENGTH), AfterValidator(_reject_python_keyword)] module-attribute

Identifier usable as a keyword argument: pattern, length and keyword checked.

Scalar = StrictBool | StrictInt | Annotated[StrictFloat, Field(allow_inf_nan=False)] | StrictStr module-attribute

Exact-typed scalar: bool, int, finite float or str.

ChoiceVar

Bases: _Strict

Categorical design variable taking one of several homogeneous values.

Attributes:

Name Type Description
kind Literal['choice']

Discriminator, always "choice".

name Name

Variable name.

choices list[Scalar]

At least two unique values sharing one Python type.

ordered StrictBool | None

True if the order of choices is meaningful, False if they are unordered categories, None for the backend default.

initial Scalar | None

Optional starting value, one of choices.

units str | None

Optional free-form unit label.

Source code in src/mdo_framework/schema.py
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
class ChoiceVar(_Strict):
    """Categorical design variable taking one of several homogeneous values.

    Attributes:
        kind: Discriminator, always ``"choice"``.
        name: Variable name.
        choices: At least two unique values sharing one Python type.
        ordered: ``True`` if the order of ``choices`` is meaningful, ``False``
            if they are unordered categories, ``None`` for the backend default.
        initial: Optional starting value, one of ``choices``.
        units: Optional free-form unit label.
    """

    kind: Literal["choice"] = "choice"
    name: Name
    choices: list[Scalar]
    ordered: StrictBool | None = None
    initial: Scalar | None = None
    units: str | None = None

    @model_validator(mode="after")
    def _check_choices(self) -> "ChoiceVar":
        violations: list[str] = []
        if len(self.choices) < 2:
            violations.append(
                "choices must contain at least 2 values; declare a single value "
                "as a fixed parameter"
            )
        if len({type(choice) for choice in self.choices}) > 1:
            violations.append("choices must all be of the same type")
        if len({(type(choice), choice) for choice in self.choices}) < len(self.choices):
            violations.append("choices must be unique")
        if self.initial is not None and not any(
            type(choice) is type(self.initial) and choice == self.initial
            for choice in self.choices
        ):
            violations.append(
                f"initial ({self.initial!r}) must be one of the choices "
                "with the same type"
            )
        _raise_if_any(violations)
        return self

    @property
    def value_type(self) -> Literal["bool", "int", "float", "str"]:
        """Type name of the choices, as expected by the parameter codec."""
        return _VALUE_TYPE_NAMES[type(self.choices[0])]

value_type property

Type name of the choices, as expected by the parameter codec.

ConstraintSpec

Bases: _Strict

Inequality constraint on a produced variable.

Attributes:

Name Type Description
name Name

Name of the produced variable to constrain.

bound Finite

Constraint bound.

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

"<=" for an upper bound, ">=" for a lower bound.

tolerance Annotated[Finite, Field(ge=0)]

Violation of the bound, in the units of the variable, that still counts as satisfied.

scale Annotated[Finite, Field(gt=0)] | None

Typical magnitude of the variable, used to compare violations of different constraints. None when unknown.

Source code in src/mdo_framework/schema.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
class ConstraintSpec(_Strict):
    """Inequality constraint on a produced variable.

    Attributes:
        name: Name of the produced variable to constrain.
        bound: Constraint bound.
        op: ``"<="`` for an upper bound, ``">="`` for a lower bound.
        tolerance: Violation of the bound, in the units of the variable, that
            still counts as satisfied.
        scale: Typical magnitude of the variable, used to compare violations of
            different constraints. ``None`` when unknown.
    """

    name: Name
    bound: Finite
    op: Literal["<=", ">="] = "<="
    tolerance: Annotated[Finite, Field(ge=0)] = 0.0
    scale: Annotated[Finite, Field(gt=0)] | None = None

Finding

Bases: _Strict

Single validation issue.

Attributes:

Name Type Description
code str

Stable machine-readable code.

message str

Human-readable description.

names tuple[str, ...]

Variable, tool or field names involved.

Source code in src/mdo_framework/schema.py
335
336
337
338
339
340
341
342
343
344
345
346
class Finding(_Strict):
    """Single validation issue.

    Attributes:
        code: Stable machine-readable code.
        message: Human-readable description.
        names: Variable, tool or field names involved.
    """

    code: str
    message: str
    names: tuple[str, ...] = ()

FixedParam

Bases: _Strict

Constant input passed unchanged to the tools that declare it.

Attributes:

Name Type Description
kind Literal['fixed']

Discriminator, always "fixed".

name Name

Variable name.

value Scalar

The constant value.

units str | None

Optional free-form unit label.

Source code in src/mdo_framework/schema.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
class FixedParam(_Strict):
    """Constant input passed unchanged to the tools that declare it.

    Attributes:
        kind: Discriminator, always ``"fixed"``.
        name: Variable name.
        value: The constant value.
        units: Optional free-form unit label.
    """

    kind: Literal["fixed"] = "fixed"
    name: Name
    value: Scalar
    units: str | None = None

ObjectiveSpec

Bases: _Strict

Optimization objective.

Attributes:

Name Type Description
name Name

Name of the produced variable to optimize.

minimize bool

True to minimize, False to maximize.

threshold Finite | None

Optional reference point for multi-objective runs.

Source code in src/mdo_framework/schema.py
301
302
303
304
305
306
307
308
309
310
311
312
class ObjectiveSpec(_Strict):
    """Optimization objective.

    Attributes:
        name: Name of the produced variable to optimize.
        minimize: ``True`` to minimize, ``False`` to maximize.
        threshold: Optional reference point for multi-objective runs.
    """

    name: Name
    minimize: bool = True
    threshold: Finite | None = None

RangeVar

Bases: _Strict

Continuous or integer design variable bounded by [lower, upper].

Attributes:

Name Type Description
kind Literal['range']

Discriminator, always "range".

name Name

Variable name.

lower Finite

Inclusive lower bound.

upper Finite

Inclusive upper bound, strictly above lower.

value_type Literal['float', 'int']

"int" for integral values, "float" otherwise.

scaling Literal['linear', 'log']

"log" to search the range on a logarithmic scale, which requires lower > 0; "linear" otherwise.

initial Finite | None

Optional starting point within the bounds.

units str | None

Optional free-form unit label.

Source code in src/mdo_framework/schema.py
 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
class RangeVar(_Strict):
    """Continuous or integer design variable bounded by ``[lower, upper]``.

    Attributes:
        kind: Discriminator, always ``"range"``.
        name: Variable name.
        lower: Inclusive lower bound.
        upper: Inclusive upper bound, strictly above ``lower``.
        value_type: ``"int"`` for integral values, ``"float"`` otherwise.
        scaling: ``"log"`` to search the range on a logarithmic scale, which
            requires ``lower > 0``; ``"linear"`` otherwise.
        initial: Optional starting point within the bounds.
        units: Optional free-form unit label.
    """

    kind: Literal["range"] = "range"
    name: Name
    lower: Finite
    upper: Finite
    value_type: Literal["float", "int"] = "float"
    scaling: Literal["linear", "log"] = "linear"
    initial: Finite | None = None
    units: str | None = None

    @model_validator(mode="after")
    def _check_bounds(self) -> "RangeVar":
        violations: list[str] = []
        if not self.lower < self.upper:
            violations.append(
                f"lower ({self.lower}) must be strictly below upper ({self.upper})"
            )
        if self.scaling == "log" and not self.lower > 0:
            violations.append(
                f"lower ({self.lower}) must be positive when scaling is 'log'"
            )
        if self.value_type == "int":
            for label, value in (
                ("lower", self.lower),
                ("upper", self.upper),
                ("initial", self.initial),
            ):
                if value is not None and not value.is_integer():
                    violations.append(
                        f"{label} ({value}) must be integral when value_type is 'int'"
                    )
        if self.initial is not None and not self.lower <= self.initial <= self.upper:
            violations.append(
                f"initial ({self.initial}) must lie within [{self.lower}, {self.upper}]"
            )
        _raise_if_any(violations)
        return self

StateVar

Bases: _Strict

Variable produced by a tool (an output or a coupling variable).

Attributes:

Name Type Description
kind Literal['state']

Discriminator, always "state".

name Name

Variable name.

initial_guess Finite | Annotated[list[Finite], Field(min_length=1)] | None

Optional scalar or non-empty list used to seed couplings.

units str | None

Optional free-form unit label.

Source code in src/mdo_framework/schema.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
class StateVar(_Strict):
    """Variable produced by a tool (an output or a coupling variable).

    Attributes:
        kind: Discriminator, always ``"state"``.
        name: Variable name.
        initial_guess: Optional scalar or non-empty list used to seed couplings.
        units: Optional free-form unit label.
    """

    kind: Literal["state"] = "state"
    name: Name
    initial_guess: Finite | Annotated[list[Finite], Field(min_length=1)] | None = None
    units: str | None = None

StudySchema

Bases: _Strict

Typed, shared description of a study: variables and tools.

Variable order is significant: design variables keep their declaration order.

Attributes:

Name Type Description
schema_version Literal['1']

Schema format version.

variables list[Variable]

Declared variables.

tools list[ToolSpec]

Declared tools.

Source code in src/mdo_framework/schema.py
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
class StudySchema(_Strict):
    """Typed, shared description of a study: variables and tools.

    Variable order is significant: design variables keep their declaration order.

    Attributes:
        schema_version: Schema format version.
        variables: Declared variables.
        tools: Declared tools.
    """

    schema_version: Literal["1"] = "1"
    variables: list[Variable] = []
    tools: list[ToolSpec] = []

    @model_validator(mode="after")
    def _check_structure(self) -> "StudySchema":
        findings = [
            *self._duplicate_name_findings(),
            *self._undeclared_ref_findings(),
            *self._producer_findings(),
        ]
        if findings:
            raise PydanticCustomError(
                "study_structure",
                "; ".join(f"{finding.code}: {finding.message}" for finding in findings),
                {"findings": [finding.model_dump() for finding in findings]},
            )
        return self

    def _duplicate_name_findings(self) -> list[Finding]:
        findings: list[Finding] = []
        for label, names in (
            ("variable", [variable.name for variable in self.variables]),
            ("tool", [tool.name for tool in self.tools]),
        ):
            for name in dict.fromkeys(names):
                if names.count(name) > 1:
                    findings.append(
                        Finding(
                            code="DUPLICATE_NAME",
                            message=f"{label} '{name}' is declared more than once",
                            names=(name,),
                        )
                    )
        return findings

    def _undeclared_ref_findings(self) -> list[Finding]:
        declared = {variable.name for variable in self.variables}
        findings: list[Finding] = []
        for tool in self.tools:
            for role, names in (("input", tool.inputs), ("output", tool.outputs)):
                findings.extend(
                    Finding(
                        code="UNDECLARED_REF",
                        message=(
                            f"tool '{tool.name}' {role} '{name}' "
                            "is not a declared variable"
                        ),
                        names=(name, tool.name),
                    )
                    for name in names
                    if name not in declared
                )
        return findings

    def _producer_findings(self) -> list[Finding]:
        kinds: dict[str, str] = {}
        for variable in self.variables:
            kinds.setdefault(variable.name, variable.kind)
        producing_tools: dict[str, list[str]] = {}
        for tool in self.tools:
            for name in tool.outputs:
                if name in kinds:
                    producing_tools.setdefault(name, []).append(tool.name)

        findings: list[Finding] = []
        for name, tools in producing_tools.items():
            if len(tools) > 1:
                findings.append(
                    Finding(
                        code="DUPLICATE_PRODUCER",
                        message=(
                            f"variable '{name}' is produced by more than one tool: "
                            f"{', '.join(tools)}"
                        ),
                        names=(name, *tools),
                    )
                )
            if kinds[name] in ("range", "choice"):
                code, what = "PRODUCED_DESIGN_VAR", "a design variable"
            elif kinds[name] == "fixed":
                code, what = "PRODUCED_FIXED", "a fixed parameter"
            else:
                continue
            findings.extend(
                Finding(
                    code=code,
                    message=f"tool '{tool}' outputs '{name}', which is {what}",
                    names=(name, tool),
                )
                for tool in tools
            )
        return findings

    def variable(self, name: str) -> Variable:
        """Return the variable called ``name``.

        Args:
            name: Variable name.

        Returns:
            The matching variable.

        Raises:
            KeyError: If no variable has this name.
        """
        for variable in self.variables:
            if variable.name == name:
                return variable
        raise KeyError(name)

    def tool(self, name: str) -> ToolSpec:
        """Return the tool called ``name``.

        Args:
            name: Tool name.

        Returns:
            The matching tool.

        Raises:
            KeyError: If no tool has this name.
        """
        for tool in self.tools:
            if tool.name == name:
                return tool
        raise KeyError(name)

    def producers(self) -> dict[str, str]:
        """Map every produced variable name to the tool that produces it.

        Returns:
            Dictionary of variable name to producing tool name.
        """
        return {name: tool.name for tool in self.tools for name in tool.outputs}

    def content_hash(self) -> str:
        """Hash the schema content, sensitive to variable and tool order.

        Returns:
            SHA-256 hex digest of the canonical JSON form.
        """
        canonical = json.dumps(
            self.model_dump(mode="json"), sort_keys=True, separators=(",", ":")
        )
        return hashlib.sha256(canonical.encode()).hexdigest()

content_hash()

Hash the schema content, sensitive to variable and tool order.

Returns:

Type Description
str

SHA-256 hex digest of the canonical JSON form.

Source code in src/mdo_framework/schema.py
534
535
536
537
538
539
540
541
542
543
def content_hash(self) -> str:
    """Hash the schema content, sensitive to variable and tool order.

    Returns:
        SHA-256 hex digest of the canonical JSON form.
    """
    canonical = json.dumps(
        self.model_dump(mode="json"), sort_keys=True, separators=(",", ":")
    )
    return hashlib.sha256(canonical.encode()).hexdigest()

producers()

Map every produced variable name to the tool that produces it.

Returns:

Type Description
dict[str, str]

Dictionary of variable name to producing tool name.

Source code in src/mdo_framework/schema.py
526
527
528
529
530
531
532
def producers(self) -> dict[str, str]:
    """Map every produced variable name to the tool that produces it.

    Returns:
        Dictionary of variable name to producing tool name.
    """
    return {name: tool.name for tool in self.tools for name in tool.outputs}

tool(name)

Return the tool called name.

Parameters:

Name Type Description Default
name str

Tool name.

required

Returns:

Type Description
ToolSpec

The matching tool.

Raises:

Type Description
KeyError

If no tool has this name.

Source code in src/mdo_framework/schema.py
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
def tool(self, name: str) -> ToolSpec:
    """Return the tool called ``name``.

    Args:
        name: Tool name.

    Returns:
        The matching tool.

    Raises:
        KeyError: If no tool has this name.
    """
    for tool in self.tools:
        if tool.name == name:
            return tool
    raise KeyError(name)

variable(name)

Return the variable called name.

Parameters:

Name Type Description Default
name str

Variable name.

required

Returns:

Type Description
Variable

The matching variable.

Raises:

Type Description
KeyError

If no variable has this name.

Source code in src/mdo_framework/schema.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
def variable(self, name: str) -> Variable:
    """Return the variable called ``name``.

    Args:
        name: Variable name.

    Returns:
        The matching variable.

    Raises:
        KeyError: If no variable has this name.
    """
    for variable in self.variables:
        if variable.name == name:
            return variable
    raise KeyError(name)

StudyValidationError

Bases: ValueError

Raised when a study fails validation.

Attributes:

Name Type Description
report

The full validation report.

Source code in src/mdo_framework/schema.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
class StudyValidationError(ValueError):
    """Raised when a study fails validation.

    Attributes:
        report: The full validation report.
    """

    def __init__(self, report: ValidationReport) -> None:
        """Build the error from a report.

        Args:
            report: Report whose errors are listed in the message.
        """
        self.report = report
        super().__init__(
            "; ".join(f"{finding.code}: {finding.message}" for finding in report.errors)
        )

__init__(report)

Build the error from a report.

Parameters:

Name Type Description Default
report ValidationReport

Report whose errors are listed in the message.

required
Source code in src/mdo_framework/schema.py
375
376
377
378
379
380
381
382
383
384
def __init__(self, report: ValidationReport) -> None:
    """Build the error from a report.

    Args:
        report: Report whose errors are listed in the message.
    """
    self.report = report
    super().__init__(
        "; ".join(f"{finding.code}: {finding.message}" for finding in report.errors)
    )

ToolNode

Bases: _Strict

Tool (discipline) as stored on a graph node, without its edges.

Attributes:

Name Type Description
name Name

Tool name.

fidelity Name

Fidelity level label.

deterministic StrictBool

Whether the tool returns the same outputs for the same inputs. A non-deterministic tool is never cached, so every evaluation calls it again.

thread_safe StrictBool

Whether the tool may run concurrently in several threads. Required of every tool in a coupled group to evaluate it in parallel.

arg_map dict[Name, Name]

Graph input name to Python argument name, for inputs whose argument has a different name. Two graph inputs cannot feed the same argument.

Source code in src/mdo_framework/schema.py
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
class ToolNode(_Strict):
    """Tool (discipline) as stored on a graph node, without its edges.

    Attributes:
        name: Tool name.
        fidelity: Fidelity level label.
        deterministic: Whether the tool returns the same outputs for the same
            inputs. A non-deterministic tool is never cached, so every
            evaluation calls it again.
        thread_safe: Whether the tool may run concurrently in several threads.
            Required of every tool in a coupled group to evaluate it in
            parallel.
        arg_map: Graph input name to Python argument name, for inputs whose
            argument has a different name. Two graph inputs cannot feed the
            same argument.
    """

    name: Name
    fidelity: Name = "high"
    deterministic: StrictBool = True
    thread_safe: StrictBool = False
    arg_map: dict[Name, Name] = {}

    @model_validator(mode="after")
    def _check_arg_map(self) -> "ToolNode":
        arguments = list(self.arg_map.values())
        repeated = sorted({name for name in arguments if arguments.count(name) > 1})
        if repeated:
            raise ValueError(
                f"arg_map values must be unique; several graph inputs feed {repeated}"
            )
        return self

ToolSpec

Bases: ToolNode

Tool (discipline) with its input and output variable names.

Attributes:

Name Type Description
name Name

Tool name.

fidelity Name

Fidelity level label.

deterministic StrictBool

Whether the tool is cacheable.

thread_safe StrictBool

Whether the tool may run concurrently in threads.

arg_map dict[Name, Name]

Graph input name to Python argument name.

inputs list[Name]

Unique names of the variables the tool reads.

outputs list[Name]

Unique names of the variables the tool produces.

Source code in src/mdo_framework/schema.py
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 ToolSpec(ToolNode):
    """Tool (discipline) with its input and output variable names.

    Attributes:
        name: Tool name.
        fidelity: Fidelity level label.
        deterministic: Whether the tool is cacheable.
        thread_safe: Whether the tool may run concurrently in threads.
        arg_map: Graph input name to Python argument name.
        inputs: Unique names of the variables the tool reads.
        outputs: Unique names of the variables the tool produces.
    """

    inputs: list[Name] = []
    outputs: list[Name] = []

    @model_validator(mode="after")
    def _check_ports(self) -> "ToolSpec":
        violations: list[str] = []
        if len(set(self.inputs)) < len(self.inputs):
            violations.append("inputs must be unique")
        if len(set(self.outputs)) < len(self.outputs):
            violations.append("outputs must be unique")
        shared = sorted(set(self.inputs) & set(self.outputs))
        if shared:
            violations.append(
                f"names cannot be both input and output of the same tool: {shared}"
            )
        _raise_if_any(violations)
        return self

ValidationReport

Bases: _Strict

Outcome of validating a study.

Attributes:

Name Type Description
errors tuple[Finding, ...]

Findings that make the study unusable.

warnings tuple[Finding, ...]

Findings that do not block the study.

valid bool

Computed flag, True when there are no errors.

Source code in src/mdo_framework/schema.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
class ValidationReport(_Strict):
    """Outcome of validating a study.

    Attributes:
        errors: Findings that make the study unusable.
        warnings: Findings that do not block the study.
        valid: Computed flag, ``True`` when there are no errors.
    """

    errors: tuple[Finding, ...] = ()
    warnings: tuple[Finding, ...] = ()

    @computed_field
    @property
    def valid(self) -> bool:
        """Whether the report contains no error."""
        return not self.errors

valid property

Whether the report contains no error.

argument_collisions(inputs, arg_map)

Find the Python arguments that several graph inputs would be passed as.

The argument of an input is its arg_map value, or its own name when it is not mapped.

Parameters:

Name Type Description Default
inputs Sequence[str]

Graph input names of a tool.

required
arg_map Mapping[str, str]

Graph input name to Python argument name.

required

Returns:

Type Description
dict[str, list[str]]

The colliding inputs, in order, per argument name. Empty when every

dict[str, list[str]]

input has its own argument.

Source code in src/mdo_framework/schema.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def argument_collisions(
    inputs: Sequence[str], arg_map: Mapping[str, str]
) -> dict[str, list[str]]:
    """Find the Python arguments that several graph inputs would be passed as.

    The argument of an input is its ``arg_map`` value, or its own name when it
    is not mapped.

    Args:
        inputs: Graph input names of a tool.
        arg_map: Graph input name to Python argument name.

    Returns:
        The colliding inputs, in order, per argument name. Empty when every
        input has its own argument.
    """
    by_argument: dict[str, list[str]] = {}
    for name in inputs:
        by_argument.setdefault(arg_map.get(name, name), []).append(name)
    return {
        argument: names for argument, names in by_argument.items() if len(names) > 1
    }

report_from_validation_error(exc)

Convert a failed StudySchema validation into a report.

Parameters:

Name Type Description Default
exc ValidationError

Error raised by StudySchema.model_validate.

required

Returns:

Type Description
ValidationReport

Report with one finding per structural violation, and a

ValidationReport

SCHEMA_INVALID finding for every other pydantic error.

Source code in src/mdo_framework/schema.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def report_from_validation_error(exc: ValidationError) -> ValidationReport:
    """Convert a failed ``StudySchema`` validation into a report.

    Args:
        exc: Error raised by ``StudySchema.model_validate``.

    Returns:
        Report with one finding per structural violation, and a
        ``SCHEMA_INVALID`` finding for every other pydantic error.
    """
    findings: list[Finding] = []
    for error in exc.errors(include_url=False):
        if error["type"] == "study_structure":
            findings.extend(Finding(**item) for item in error["ctx"]["findings"])
            continue
        location = error["loc"]
        findings.append(
            Finding(
                code="SCHEMA_INVALID",
                message=f"{'.'.join(map(str, location))}: {error['msg']}",
                names=tuple(part for part in location if isinstance(part, str)),
            )
        )
    return ValidationReport(errors=tuple(findings))