remotivelabs.topology.fmu

 1from __future__ import annotations
 2
 3try:
 4    import fmpy  # noqa: F401
 5    import numpy  # noqa: F401
 6except ImportError as e:
 7    raise ImportError("remotivelabs.topology.fmu requires the 'fmu' extra: pip install remotivelabs-topology[fmu]") from e
 8
 9from remotivelabs.topology.fmu.behavioral_model import FMUBehavioralModel, InputMapping
10from remotivelabs.topology.fmu.simulation import FMUSimulation, FMUVars
11
12__all__ = ["FMUBehavioralModel", "InputMapping", "FMUSimulation", "FMUVars"]
class FMUBehavioralModel(remotivelabs.topology.behavioral_model.behavioral_model.BehavioralModel):
22class FMUBehavioralModel(BehavioralModel):
23    """
24    An FMUBehavioralModel is used to connect the behavior of an FMU simulation to a Remotive topology.
25
26    Provide InputMapping to specify which frames/signals should be mapped to which FMU inputs.
27    """
28
29    def __init__(  # noqa: PLR0913
30        self,
31        model_name: str,
32        fmu: FMUSimulation,
33        input_mapping: InputMapping,
34        broker_client: BrokerClient,
35        namespaces: list[GenericNamespace] = [],
36    ) -> None:
37        self._fmu = fmu
38        self._input_mapping = input_mapping
39        self._fmu_namespaces: dict[str, GenericNamespace] = {ns.name: ns for ns in namespaces}
40        for ns_name in input_mapping:
41            if ns_name not in self._fmu_namespaces:
42                self._fmu_namespaces[ns_name] = GenericNamespace(name=ns_name, broker_client=broker_client)
43
44        input_handlers = [
45            self._fmu_namespaces[ns_name].create_input_handler(
46                [filters.FrameFilter(frame_name) for frame_name in frame_signals],
47                self._on_frame,
48            )
49            for ns_name, frame_signals in input_mapping.items()
50        ]
51
52        super().__init__(
53            model_name,
54            broker_client=broker_client,
55            namespaces=list(self._fmu_namespaces.values()),
56            input_handlers=input_handlers,
57            control_handlers=[
58                (RebootRequest.type, self._on_reboot),
59            ],
60        )
61
62    async def __aenter__(self) -> FMUBehavioralModel:
63        self._signals: dict[str, dict[str, SignalInfo]] = {
64            ns_name: {signal.name: signal for signal in await ns.list_signal_infos()} for ns_name, ns in self._fmu_namespaces.items()
65        }
66        await super().__aenter__()
67        return self
68
69    async def _on_reboot(self, request: ControlRequest) -> ControlResponse:  # noqa: ARG002
70        logger.debug(f"Rebooting {self._name}")
71        self._fmu.reset()
72        await super().reset_restbuses()
73        return ControlResponse(status="ok")
74
75    async def _on_frame(self, frame: Frame) -> None:
76        ns_signals = self._input_mapping.get(frame.namespace, {})
77        frame_signals = ns_signals.get(frame.name, {})
78        for signal_name, input_name in frame_signals.items():
79            signal_info = self._signals[frame.namespace][signal_name]
80            signal_value = frame.signals.get(signal_name)
81            if isinstance(signal_value, (int, float)) and signal_value >= signal_info.min and signal_value <= signal_info.max:
82                self._fmu.set_input_value(input_name, signal_value)
83
84    async def run_forever(self) -> None:
85        """Run the FMUBehavioralModel indefinitely, processing inputs and control requests."""
86
87        async def on_tick(elapsed_time: float, since_last_tick: float, total_drift: float, interval: float) -> bool | None:  # noqa: ARG001
88            await self._fmu.step()
89            return None
90
91        step_size = self._fmu.step_size
92        logger.info(f"Starting ticker with step size {step_size}s")
93        await asyncio.gather(
94            create_ticker(step_size, on_tick),
95            super().run_forever(),
96        )

An FMUBehavioralModel is used to connect the behavior of an FMU simulation to a Remotive topology.

Provide InputMapping to specify which frames/signals should be mapped to which FMU inputs.

FMUBehavioralModel( model_name: str, fmu: FMUSimulation, input_mapping: dict[str, dict[str, dict[str, str]]], broker_client: remotivelabs.broker.client.BrokerClient, namespaces: list[remotivelabs.topology.namespaces.generic.GenericNamespace] = [])
29    def __init__(  # noqa: PLR0913
30        self,
31        model_name: str,
32        fmu: FMUSimulation,
33        input_mapping: InputMapping,
34        broker_client: BrokerClient,
35        namespaces: list[GenericNamespace] = [],
36    ) -> None:
37        self._fmu = fmu
38        self._input_mapping = input_mapping
39        self._fmu_namespaces: dict[str, GenericNamespace] = {ns.name: ns for ns in namespaces}
40        for ns_name in input_mapping:
41            if ns_name not in self._fmu_namespaces:
42                self._fmu_namespaces[ns_name] = GenericNamespace(name=ns_name, broker_client=broker_client)
43
44        input_handlers = [
45            self._fmu_namespaces[ns_name].create_input_handler(
46                [filters.FrameFilter(frame_name) for frame_name in frame_signals],
47                self._on_frame,
48            )
49            for ns_name, frame_signals in input_mapping.items()
50        ]
51
52        super().__init__(
53            model_name,
54            broker_client=broker_client,
55            namespaces=list(self._fmu_namespaces.values()),
56            input_handlers=input_handlers,
57            control_handlers=[
58                (RebootRequest.type, self._on_reboot),
59            ],
60        )

Initialize the BehavioralModel instance.

Prometheus metrics are opt-in: set the METRICS_PORT environment variable to enable a process-wide exporter that serves /metrics on that port.

Arguments:
  • name: Identifier for the ECU stub instance, then name which receives control messages.
  • broker_client: The client used for communication with the broker.
  • namespaces: list of Namespace instances (CanNamespace, SomeIPNamespace, etc.).
  • input_handlers: Optional list of (namespace, handler) pairs to receive callbacks on inputs. Create these using the namespace's create_input_handler method.
  • control_handlers: Optional list of (command, handler) pairs for routing control messages.
  • input_filters: Optional filters applied to every input handler across all namespaces. Useful for cross-cutting concerns like excluding E2E signals: input_filters=[E2eSignalsFilter(exclude=True)].
  • on_change: When True (default), a frame is only delivered when at least one of its signals has changed. The delivered frame always contains all signals, including unchanged ones. When False, every frame is delivered regardless of whether its signals have changed.
Note:

Start the instance using a context manager:

async with BehavioralModel(...) as bm:
    ...
    await bm.run_forever()

Or use the start/stop methods directly:

bm = BehavioralModel(...)
await bm.start()
# ...
await bm.stop()

async def run_forever(self) -> None:
84    async def run_forever(self) -> None:
85        """Run the FMUBehavioralModel indefinitely, processing inputs and control requests."""
86
87        async def on_tick(elapsed_time: float, since_last_tick: float, total_drift: float, interval: float) -> bool | None:  # noqa: ARG001
88            await self._fmu.step()
89            return None
90
91        step_size = self._fmu.step_size
92        logger.info(f"Starting ticker with step size {step_size}s")
93        await asyncio.gather(
94            create_ticker(step_size, on_tick),
95            super().run_forever(),
96        )

Run the FMUBehavioralModel indefinitely, processing inputs and control requests.

InputMapping = dict[str, dict[str, dict[str, str]]]
class FMUSimulation:
 47class FMUSimulation:
 48    """
 49    Wraps the FMPy simulate_fmu function into coSimulation (manual stepping) specific model.
 50    FMU should be version 2 or 3 Co-Simulation FMU, and should be configured to use fixed step size
 51    and manual stepping (i.e. no internal solver).
 52    """
 53
 54    _path: Path
 55    _unzipdir: Path | str
 56
 57    _on_output: OnOutput | None
 58    _before_step: BeforeStep | None
 59
 60    _fmu_instance: FMU2Slave | FMU3Slave
 61    _model_description: ModelDescription
 62    _input_vars: FmuVariableMap  # manual mapping from FMU var types to their internal representation
 63    _output_vars: FmuVariableMap  # manual mapping from FMU var types to their internal representation
 64
 65    _last_inputs: FMUVars
 66    _last_outputs: FMUVars
 67
 68    _step_event: asyncio.Event
 69
 70    def __init__(
 71        self, path: Path, on_output: OnOutput | None = None, before_step: BeforeStep | None = None, step_size: float | None = None
 72    ) -> None:
 73        self._path = path
 74        self._on_output = on_output
 75        self._before_step = before_step
 76        self._model_description = read_model_description(self._path)
 77        if self._model_description.defaultExperiment is None:
 78            raise UnsupportedFMUSimulationError("Missing defaultExperiment")
 79
 80        self._step_size = step_size if step_size is not None else float(self._model_description.defaultExperiment.stepSize)
 81
 82        # Make sure the FMU supports coSimulation (stepping) and has the required attributes
 83        if self._model_description.coSimulation is None:
 84            raise UnsupportedFMUSimulationError("The FMU does not support coSimulation")
 85
 86        # Instantiate the FMU
 87        self._unzipdir = extract(self._path)
 88        fmu_instance = instantiate_fmu(unzipdir=self._unzipdir, model_description=self._model_description)
 89        self._fmu_instance = fmu_instance
 90
 91        # parse variable references from model description
 92        self._input_vars, self._output_vars = _parse_fmu_variable_info(self._model_description)
 93        self._input_var_names = {name for vars in self._input_vars.values() for name, _ in vars}
 94        self._output_var_names = {name for vars in self._output_vars.values() for name, _ in vars}
 95
 96        self._input = {var.name: 0 for var in self._model_description.modelVariables if var.causality == "input"}
 97
 98        # Initialize the FMU
 99        self.reset()
100
101        # step event is used to notify
102        self._step_event = asyncio.Event()
103
104    def print(self) -> None:
105        """Print the model information and variables of an FMU."""
106        dump(str(self._path))
107
108    @property
109    def step_size(self) -> float:
110        """Get the step size of the FMU model."""
111        return self._step_size
112
113    @property
114    def input_var_names(self) -> set[str]:
115        """Get all input variable names known to the FMU model."""
116        return self._input_var_names
117
118    @property
119    def inputs(self) -> FMUVars:
120        """Get the inputs for the last step."""
121        return self._last_inputs
122
123    @property
124    def output_var_names(self) -> set[str]:
125        """Get all output variable names known to the FMU model."""
126        return self._output_var_names
127
128    @property
129    def outputs(self) -> FMUVars:
130        """Get the outputs from the last step."""
131        return self._last_outputs
132
133    def reset(self) -> None:
134        """Reset the FMU to its initial state."""
135        self._fmu_instance.reset()
136        if isinstance(self._fmu_instance, FMU2Slave):
137            self._fmu_instance.setupExperiment(startTime=0.0)
138        self._fmu_instance.enterInitializationMode()
139        self._fmu_instance.exitInitializationMode()
140        self._last_inputs = {}
141        self._last_outputs = {}
142        self._current_time = 0.0
143
144    def _encode_inputs(self, inputs: FMUVars) -> None:
145        """Set inputs for the next step."""
146        any_input_set: bool = False
147
148        # loop over the supported input variable types (boolean, float64, int32, string)
149        for typ, items in self._input_vars.items():
150            # Filter variables by name (input must be present in the FMU model)
151            valid_inputs = [(vr, inputs[name]) for name, vr in items if name in inputs]
152            if not valid_inputs:
153                continue
154
155            any_input_set = True  # At least one input was set
156
157            # values are set as list of names and list of values
158            vrs, vals = zip(*valid_inputs)
159            match typ:
160                case "Boolean":
161                    self._fmu_instance.setBoolean(list(vrs), list(vals))
162                case "Float64":  # FMI 3.0
163                    self._fmu_instance.setFloat64(list(vrs), list(vals))
164                case "Real":  # FMI 2.0
165                    self._fmu_instance.setReal(list(vrs), list(vals))
166                case "Int32":  # FMI 3.0
167                    self._fmu_instance.setInt32(list(vrs), list(vals))
168                case "Integer":  # FMI 2.0
169                    self._fmu_instance.setInteger(list(vrs), list(vals))
170                case "String":
171                    self._fmu_instance.setString(list(vrs), list(vals))
172                case _:
173                    raise ValueError(f"Unsupported input variable type: {typ}")
174
175        if not any_input_set:
176            logger.warning("No valid input variables were set for the FMU model")
177
178    def _decode_outputs(self) -> FMUVars:
179        """Get outputs from the last step."""
180        outputs: FMUVars = {}
181
182        for typ, items in self._output_vars.items():
183            names, vrs = zip(*items)
184            match typ:
185                case "Boolean":
186                    values = self._fmu_instance.getBoolean(list(vrs))
187                case "Float64":  # FMI 3.0
188                    values = self._fmu_instance.getFloat64(list(vrs))
189                case "Real":  # FMI 2.0
190                    values = self._fmu_instance.getReal(list(vrs))
191                case "Int32":  # FMI 3.0
192                    values = self._fmu_instance.getInt32(list(vrs))
193                case "Integer":  # FMI 2.0
194                    values = self._fmu_instance.getInteger(list(vrs))
195                case "String":
196                    values = self._fmu_instance.getString(list(vrs))
197                case _:
198                    raise ValueError(f"Unsupported output variable type: {typ}")
199            outputs.update(dict(zip(names, values)))
200
201        return outputs
202
203    async def step(self) -> FMUVars:
204        """Advance the simulation by a given step time, applying inputs."""
205        inputs = self._input
206        if self._before_step is not None:
207            inputs = await self._before_step(inputs)
208
209        # Update inputs for the next step
210        self._last_inputs = inputs
211        self._encode_inputs(inputs)
212
213        # step forward (current time and step size are ignored by the FMU)
214        self._fmu_instance.doStep(currentCommunicationPoint=self._current_time, communicationStepSize=self._step_size)
215        self._current_time += self._step_size
216
217        # Read outputs from the last step
218        self._last_outputs = self._decode_outputs()
219        if self._on_output is not None:
220            await self._on_output(self._last_outputs)
221
222        # Notify anyone waiting for the next step
223        await self._notify_next_step()
224
225        return self.outputs
226
227    async def wait_for_step(self) -> FMUVars:
228        """Block until the next step has been completed and return the outputs."""
229        await self._step_event.wait()
230        return self.outputs
231
232    async def _notify_next_step(self) -> None:
233        """Notify anyone waiting for the next step that it has been completed."""
234        self._step_event.set()
235        await asyncio.sleep(0)
236        self._step_event.clear()
237
238    def set_input_value(self, input_name: str, value: Any) -> None:
239        """Set a single input value which will be applied in all future steps."""
240        if input_name in self._input_var_names:
241            self._input[input_name] = value
242        else:
243            logger.error(f"Attempted to set unknown input '{input_name}' with value '{value}'.")
244            raise ValueError(f"Input '{input_name}' is not a valid input variable for the FMU model.")

Wraps the FMPy simulate_fmu function into coSimulation (manual stepping) specific model. FMU should be version 2 or 3 Co-Simulation FMU, and should be configured to use fixed step size and manual stepping (i.e. no internal solver).

FMUSimulation( path: pathlib._local.Path, on_output: Optional[Callable[[dict[str, Any]], Awaitable[NoneType]]] = None, before_step: Optional[Callable[[dict[str, Any]], Awaitable[dict[str, Any]]]] = None, step_size: float | None = None)
 70    def __init__(
 71        self, path: Path, on_output: OnOutput | None = None, before_step: BeforeStep | None = None, step_size: float | None = None
 72    ) -> None:
 73        self._path = path
 74        self._on_output = on_output
 75        self._before_step = before_step
 76        self._model_description = read_model_description(self._path)
 77        if self._model_description.defaultExperiment is None:
 78            raise UnsupportedFMUSimulationError("Missing defaultExperiment")
 79
 80        self._step_size = step_size if step_size is not None else float(self._model_description.defaultExperiment.stepSize)
 81
 82        # Make sure the FMU supports coSimulation (stepping) and has the required attributes
 83        if self._model_description.coSimulation is None:
 84            raise UnsupportedFMUSimulationError("The FMU does not support coSimulation")
 85
 86        # Instantiate the FMU
 87        self._unzipdir = extract(self._path)
 88        fmu_instance = instantiate_fmu(unzipdir=self._unzipdir, model_description=self._model_description)
 89        self._fmu_instance = fmu_instance
 90
 91        # parse variable references from model description
 92        self._input_vars, self._output_vars = _parse_fmu_variable_info(self._model_description)
 93        self._input_var_names = {name for vars in self._input_vars.values() for name, _ in vars}
 94        self._output_var_names = {name for vars in self._output_vars.values() for name, _ in vars}
 95
 96        self._input = {var.name: 0 for var in self._model_description.modelVariables if var.causality == "input"}
 97
 98        # Initialize the FMU
 99        self.reset()
100
101        # step event is used to notify
102        self._step_event = asyncio.Event()
def print(self) -> None:
104    def print(self) -> None:
105        """Print the model information and variables of an FMU."""
106        dump(str(self._path))

Print the model information and variables of an FMU.

step_size: float
108    @property
109    def step_size(self) -> float:
110        """Get the step size of the FMU model."""
111        return self._step_size

Get the step size of the FMU model.

input_var_names: set[str]
113    @property
114    def input_var_names(self) -> set[str]:
115        """Get all input variable names known to the FMU model."""
116        return self._input_var_names

Get all input variable names known to the FMU model.

inputs: dict[str, typing.Any]
118    @property
119    def inputs(self) -> FMUVars:
120        """Get the inputs for the last step."""
121        return self._last_inputs

Get the inputs for the last step.

output_var_names: set[str]
123    @property
124    def output_var_names(self) -> set[str]:
125        """Get all output variable names known to the FMU model."""
126        return self._output_var_names

Get all output variable names known to the FMU model.

outputs: dict[str, typing.Any]
128    @property
129    def outputs(self) -> FMUVars:
130        """Get the outputs from the last step."""
131        return self._last_outputs

Get the outputs from the last step.

def reset(self) -> None:
133    def reset(self) -> None:
134        """Reset the FMU to its initial state."""
135        self._fmu_instance.reset()
136        if isinstance(self._fmu_instance, FMU2Slave):
137            self._fmu_instance.setupExperiment(startTime=0.0)
138        self._fmu_instance.enterInitializationMode()
139        self._fmu_instance.exitInitializationMode()
140        self._last_inputs = {}
141        self._last_outputs = {}
142        self._current_time = 0.0

Reset the FMU to its initial state.

async def step(self) -> dict[str, typing.Any]:
203    async def step(self) -> FMUVars:
204        """Advance the simulation by a given step time, applying inputs."""
205        inputs = self._input
206        if self._before_step is not None:
207            inputs = await self._before_step(inputs)
208
209        # Update inputs for the next step
210        self._last_inputs = inputs
211        self._encode_inputs(inputs)
212
213        # step forward (current time and step size are ignored by the FMU)
214        self._fmu_instance.doStep(currentCommunicationPoint=self._current_time, communicationStepSize=self._step_size)
215        self._current_time += self._step_size
216
217        # Read outputs from the last step
218        self._last_outputs = self._decode_outputs()
219        if self._on_output is not None:
220            await self._on_output(self._last_outputs)
221
222        # Notify anyone waiting for the next step
223        await self._notify_next_step()
224
225        return self.outputs

Advance the simulation by a given step time, applying inputs.

async def wait_for_step(self) -> dict[str, typing.Any]:
227    async def wait_for_step(self) -> FMUVars:
228        """Block until the next step has been completed and return the outputs."""
229        await self._step_event.wait()
230        return self.outputs

Block until the next step has been completed and return the outputs.

def set_input_value(self, input_name: str, value: Any) -> None:
238    def set_input_value(self, input_name: str, value: Any) -> None:
239        """Set a single input value which will be applied in all future steps."""
240        if input_name in self._input_var_names:
241            self._input[input_name] = value
242        else:
243            logger.error(f"Attempted to set unknown input '{input_name}' with value '{value}'.")
244            raise ValueError(f"Input '{input_name}' is not a valid input variable for the FMU model.")

Set a single input value which will be applied in all future steps.

FMUVars = dict[str, typing.Any]