Skip to content

ToolComponent

mdo_framework.core.components.ToolComponent

Bases: Discipline

GEMSEO discipline that wraps a Python function.

The function is called with keyword arguments only, one per input. It returns a dict keyed by output name, or a bare value when the tool has a single output; a list or an array is a vector value of a single output, a tuple is never accepted. Anything else, a non-finite value included, is a ToolOutputError; an exception raised by the function becomes a ToolExecutionError. Two inputs cannot be passed as the same argument. Jacobians are approximated by finite differences.

Source code in src/mdo_framework/core/components.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
class ToolComponent(Discipline):
    """GEMSEO discipline that wraps a Python function.

    The function is called with keyword arguments only, one per input. It returns
    a dict keyed by output name, or a bare value when the tool has a single
    output; a list or an array is a vector value of a single output, a tuple is
    never accepted. Anything else, a non-finite value included, is a
    ``ToolOutputError``; an exception raised by the function becomes a
    ``ToolExecutionError``. Two inputs cannot be passed as the same argument.
    Jacobians are approximated by finite differences.
    """

    def __init__(
        self,
        name: str,
        func: Callable[..., Any],
        inputs: Sequence[str],
        outputs: Sequence[str],
        *,
        specs: Mapping[str, ParameterDefinition] | None = None,
        defaults: Mapping[str, Any] | None = None,
        deterministic: bool = True,
        arg_map: Mapping[str, str] | None = None,
    ) -> None:
        """Initializes the tool component.

        Args:
            name: The name of the discipline.
            func: The Python callable executing the tool logic.
            inputs: Input variable names.
            outputs: Output variable names.
            specs: Parameter definitions per input name, used to decode choice
                indices and integers before calling ``func``.
            defaults: Value of the inputs that may be omitted when executing, per
                input name. An input without a default is required.
            deterministic: Whether the same inputs always give the same outputs.
                If false, the discipline is never cached.
            arg_map: Python argument name per input name, for the inputs whose
                argument is named differently.
        """
        super().__init__(name=name)
        self.func = func
        self._input_names = tuple(inputs)
        self._output_names = tuple(outputs)
        self._specs = dict(specs or {})
        self._arg_map = dict(arg_map or {})
        collisions = argument_collisions(self._input_names, self._arg_map)
        if collisions:
            clashes = "; ".join(
                f"'{argument}' would receive {names}"
                for argument, names in collisions.items()
            )
            raise ValueError(
                f"Tool '{name}': several inputs are passed as the same argument: "
                f"{clashes}; map each input to its own argument"
            )
        self.input_grammar.update_from_names(self._input_names)
        self.output_grammar.update_from_names(self._output_names)
        self.default_input_data = {
            input_name: np.atleast_1d(value)
            for input_name, value in (defaults or {}).items()
        }
        self.set_jacobian_approximation()
        if not deterministic:
            self.set_cache(CacheType.NONE)

    def linearize(
        self,
        input_data: StrKeyMapping = READ_ONLY_EMPTY_DICT,
        compute_all_jacobians: bool = False,
        execute: bool = True,
    ) -> JacobianData:
        """Approximates the Jacobian at ``input_data`` by finite differences.

        GEMSEO's finite differences only perturb the differentiated inputs and
        take the others from the defaults, which a design variable lacks. They are
        taken from ``input_data`` for the duration of the call instead.
        """
        defaults = self.input_grammar.defaults
        saved = dict(defaults)
        defaults.update(self.io.prepare_input_data(input_data))
        try:
            return super().linearize(input_data, compute_all_jacobians, execute)
        finally:
            defaults.clear()
            defaults.update(saved)

    def _run(self, input_data: StrKeyMapping) -> dict[str, np.ndarray]:
        kwargs = {
            self._arg_map.get(name, name): to_tool_value(
                self._specs.get(name), input_data[name]
            )
            for name in self._input_names
        }
        try:
            result = self.func(**kwargs)
        except MemoryError:
            raise
        except InfeasiblePointError as exc:
            # The tool's own verdict on the point; only the tool name is added.
            raise InfeasiblePointError(exc.message, tool=self.name) from exc
        except Exception as exc:
            raise ToolExecutionError(
                f"{type(exc).__name__}: {exc}", tool=self.name
            ) from exc
        return self._normalise_outputs(result)

    def _normalise_outputs(self, result: Any) -> dict[str, np.ndarray]:
        if result is None:
            raise self._output_error(
                f"returned None; expected values for {list(self._output_names)}"
            )
        if isinstance(result, Mapping):
            values = self._values_by_name(result)
        elif isinstance(result, tuple):
            raise self._output_error(
                "returned a tuple, which is never matched to the outputs "
                f"{list(self._output_names)}; return a dict keyed by output name, "
                "or a single value for a tool with one output"
            )
        elif len(self._output_names) == 1:
            values = {self._output_names[0]: result}
        else:
            raise self._output_error(
                f"returned a {type(result).__name__} for the outputs "
                f"{list(self._output_names)}; return a dict keyed by output name"
            )

        outputs: dict[str, np.ndarray] = {}
        for output_name, value in values.items():
            try:
                outputs[output_name] = np.atleast_1d(np.asarray(value, dtype=float))
            except (TypeError, ValueError) as exc:
                raise self._output_error(
                    f"output '{output_name}' is not numeric: {exc}"
                ) from exc
        non_finite = [
            output_name
            for output_name, array in outputs.items()
            if not np.all(np.isfinite(array))
        ]
        if non_finite:
            raise self._output_error(
                f"non-finite value (NaN or infinity) in the outputs {non_finite}"
            )
        return outputs

    def _values_by_name(self, result: Mapping[str, Any]) -> dict[str, Any]:
        missing = [name for name in self._output_names if name not in result]
        unexpected = [name for name in result if name not in self._output_names]
        if missing or unexpected:
            raise self._output_error(
                "the returned dict does not match the declared outputs "
                f"{list(self._output_names)}: missing {missing}, "
                f"unexpected {unexpected}"
            )
        return {name: result[name] for name in self._output_names}

    def _output_error(self, message: str) -> ToolOutputError:
        return ToolOutputError(message, tool=self.name)

__init__(name, func, inputs, outputs, *, specs=None, defaults=None, deterministic=True, arg_map=None)

Initializes the tool component.

Parameters:

Name Type Description Default
name str

The name of the discipline.

required
func Callable[..., Any]

The Python callable executing the tool logic.

required
inputs Sequence[str]

Input variable names.

required
outputs Sequence[str]

Output variable names.

required
specs Mapping[str, ParameterDefinition] | None

Parameter definitions per input name, used to decode choice indices and integers before calling func.

None
defaults Mapping[str, Any] | None

Value of the inputs that may be omitted when executing, per input name. An input without a default is required.

None
deterministic bool

Whether the same inputs always give the same outputs. If false, the discipline is never cached.

True
arg_map Mapping[str, str] | None

Python argument name per input name, for the inputs whose argument is named differently.

None
Source code in src/mdo_framework/core/components.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def __init__(
    self,
    name: str,
    func: Callable[..., Any],
    inputs: Sequence[str],
    outputs: Sequence[str],
    *,
    specs: Mapping[str, ParameterDefinition] | None = None,
    defaults: Mapping[str, Any] | None = None,
    deterministic: bool = True,
    arg_map: Mapping[str, str] | None = None,
) -> None:
    """Initializes the tool component.

    Args:
        name: The name of the discipline.
        func: The Python callable executing the tool logic.
        inputs: Input variable names.
        outputs: Output variable names.
        specs: Parameter definitions per input name, used to decode choice
            indices and integers before calling ``func``.
        defaults: Value of the inputs that may be omitted when executing, per
            input name. An input without a default is required.
        deterministic: Whether the same inputs always give the same outputs.
            If false, the discipline is never cached.
        arg_map: Python argument name per input name, for the inputs whose
            argument is named differently.
    """
    super().__init__(name=name)
    self.func = func
    self._input_names = tuple(inputs)
    self._output_names = tuple(outputs)
    self._specs = dict(specs or {})
    self._arg_map = dict(arg_map or {})
    collisions = argument_collisions(self._input_names, self._arg_map)
    if collisions:
        clashes = "; ".join(
            f"'{argument}' would receive {names}"
            for argument, names in collisions.items()
        )
        raise ValueError(
            f"Tool '{name}': several inputs are passed as the same argument: "
            f"{clashes}; map each input to its own argument"
        )
    self.input_grammar.update_from_names(self._input_names)
    self.output_grammar.update_from_names(self._output_names)
    self.default_input_data = {
        input_name: np.atleast_1d(value)
        for input_name, value in (defaults or {}).items()
    }
    self.set_jacobian_approximation()
    if not deterministic:
        self.set_cache(CacheType.NONE)

linearize(input_data=READ_ONLY_EMPTY_DICT, compute_all_jacobians=False, execute=True)

Approximates the Jacobian at input_data by finite differences.

GEMSEO's finite differences only perturb the differentiated inputs and take the others from the defaults, which a design variable lacks. They are taken from input_data for the duration of the call instead.

Source code in src/mdo_framework/core/components.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def linearize(
    self,
    input_data: StrKeyMapping = READ_ONLY_EMPTY_DICT,
    compute_all_jacobians: bool = False,
    execute: bool = True,
) -> JacobianData:
    """Approximates the Jacobian at ``input_data`` by finite differences.

    GEMSEO's finite differences only perturb the differentiated inputs and
    take the others from the defaults, which a design variable lacks. They are
    taken from ``input_data`` for the duration of the call instead.
    """
    defaults = self.input_grammar.defaults
    saved = dict(defaults)
    defaults.update(self.io.prepare_input_data(input_data))
    try:
        return super().linearize(input_data, compute_all_jacobians, execute)
    finally:
        defaults.clear()
        defaults.update(saved)