Skip to content

FMI-LS-REF

Validation of the results of an FMU from the reference material of FMI-LS-REF (see FMU Checker): the experiment files, the time series of their stimuli and references, and the replay of an experiment with the runtime of the FMU Container.

Experiment files of MA-HS-Experiments, referred to by FMI-LS-REF (draft of the Modelica Association).

An experiment file (<Experiments>) holds transient experiments: start and stop times, step size, tolerance, and the files of their parameters (SSV), stimuli and references (time series), given by URIs relative to the experiment file.

Experiment dataclass

A TransientExperiment of an experiment file. The times are None when they are not given.

Attributes:

Name Type Description
name str

Name of the experiment.

description str | None

Human-readable description.

start_time float | None

Start time, in seconds.

stop_time float | None

Stop time, in seconds.

step_size float | None

Step size, in seconds.

tolerance float | None

Tolerance.

parameters ExperimentSource | None

Parameters of the experiment.

stimuli ExperimentSource | None

Stimuli of the experiment.

references ExperimentSource | None

Reference results of the experiment.

Source code in fmu_manipulation_toolbox/experiments.py
@dataclass
class Experiment:
    """A `TransientExperiment` of an experiment file. The times are `None` when they are not given.

    Attributes:
        name (str): Name of the experiment.
        description (str | None): Human-readable description.
        start_time (float | None): Start time, in seconds.
        stop_time (float | None): Stop time, in seconds.
        step_size (float | None): Step size, in seconds.
        tolerance (float | None): Tolerance.
        parameters (ExperimentSource | None): Parameters of the experiment.
        stimuli (ExperimentSource | None): Stimuli of the experiment.
        references (ExperimentSource | None): Reference results of the experiment.
    """
    name: str
    description: str | None = None
    start_time: float | None = None
    stop_time: float | None = None
    step_size: float | None = None
    tolerance: float | None = None
    parameters: ExperimentSource | None = None
    stimuli: ExperimentSource | None = None
    references: ExperimentSource | None = None

ExperimentSource dataclass

The file of the parameters, of the stimuli or of the references of an experiment.

Attributes:

Name Type Description
source str

URI of the file, relative to the experiment file.

type str

MIME type of the file.

path Path | None

The file, when it was found in the FMU.

problem str | None

Why the file was not found (see resolve_uri).

Source code in fmu_manipulation_toolbox/experiments.py
@dataclass
class ExperimentSource:
    """The file of the parameters, of the stimuli or of the references of an experiment.

    Attributes:
        source (str): URI of the file, relative to the experiment file.
        type (str): MIME type of the file.
        path (Path | None): The file, when it was found in the FMU.
        problem (str | None): Why the file was not found (see
            [resolve_uri][fmu_manipulation_toolbox.ls.resolve_uri]).
    """
    source: str
    type: str
    path: Path | None = None
    problem: str | None = None

Experiments dataclass

An experiment file (Experiments element).

Attributes:

Name Type Description
name str

Name of the set of experiments.

description str | None

Human-readable description.

experiments list[Experiment]

Its experiments, in the order of the file.

Source code in fmu_manipulation_toolbox/experiments.py
@dataclass
class Experiments:
    """An experiment file (`Experiments` element).

    Attributes:
        name (str): Name of the set of experiments.
        description (str | None): Human-readable description.
        experiments (list[Experiment]): Its experiments, in the order of the file.
    """
    name: str
    description: str | None = None
    experiments: list[Experiment] = field(default_factory=list)

ExperimentsError

Bases: Exception

An experiment file that cannot be read.

Source code in fmu_manipulation_toolbox/experiments.py
class ExperimentsError(Exception):
    """An experiment file that cannot be read."""

Parameter dataclass

A parameter of an SSV parameter set.

Attributes:

Name Type Description
name str

Name of the variable.

type str

Value element of the parameter (Real, Float64, Integer, Boolean, String...).

value str

Its value, as written in the file.

Source code in fmu_manipulation_toolbox/experiments.py
@dataclass
class Parameter:
    """A parameter of an SSV parameter set.

    Attributes:
        name (str): Name of the variable.
        type (str): Value element of the parameter (`Real`, `Float64`, `Integer`, `Boolean`, `String`...).
        value (str): Its value, as written in the file.
    """
    name: str
    type: str
    value: str

read_experiments(filename, root)

Reads the experiment file filename of the extracted FMU root.

The elements are matched by their local name: the namespace and the XSD are checked by the checker of LS-REF. The sources are resolved against the directory of the file (see resolve_uri).

Raises:

Type Description
ExperimentsError

The file is not well-formed XML, its root is not Experiments, or a time is not a number.

Source code in fmu_manipulation_toolbox/experiments.py
def read_experiments(filename: Path | str, root: Path | str) -> Experiments:
    """Reads the experiment file `filename` of the extracted FMU `root`.

    The elements are matched by their local name: the namespace and the XSD are checked by the checker of LS-REF.
    The sources are resolved against the directory of the file (see
    [resolve_uri][fmu_manipulation_toolbox.ls.resolve_uri]).

    Raises:
        ExperimentsError: The file is not well-formed XML, its root is not `Experiments`, or a time is not a number.
    """
    filename = Path(filename)
    try:
        element = ET.parse(filename).getroot()
    except ET.ParseError as error:
        raise ExperimentsError(f"cannot parse '{filename.name}': {error}") from None
    if _local_name(element) != "Experiments":
        raise ExperimentsError(f"'{filename.name}': root element is '{_local_name(element)}', not 'Experiments'")

    experiments = Experiments(name=element.get("name", ""), description=element.get("description"))
    for child in element:
        if _local_name(child) != "TransientExperiment":
            continue
        experiment = Experiment(name=child.get("name", ""), description=child.get("description"),
                                start_time=_float(child, "startTime"), stop_time=_float(child, "stopTime"),
                                step_size=_float(child, "stepSize"), tolerance=_float(child, "tolerance"))
        for source_element in child:
            kind = _local_name(source_element)
            if kind not in ("Parameters", "Stimuli", "References"):
                continue
            source = ExperimentSource(source=source_element.get("source", ""),
                                      type=source_element.get("type",
                                                              PARAMETERS_TYPE if kind == "Parameters"
                                                              else TIME_SERIES_TYPE))
            source.path, source.problem = resolve_uri(source.source, filename.parent, root)
            setattr(experiment, kind.lower(), source)
        experiments.experiments.append(experiment)
    return experiments

read_parameter_set(filename)

Reads the parameters of an SSV file (ssv:ParameterSet). A parameter is given by its first value element (ssv:Real, ssv:Integer...); a parameter without value element is ignored.

Raises:

Type Description
ExperimentsError

The file is not well-formed XML or has no ssv:ParameterSet.

Source code in fmu_manipulation_toolbox/experiments.py
def read_parameter_set(filename: Path | str) -> list[Parameter]:
    """Reads the parameters of an SSV file (`ssv:ParameterSet`). A parameter is given by its first value element
    (`ssv:Real`, `ssv:Integer`...); a parameter without value element is ignored.

    Raises:
        ExperimentsError: The file is not well-formed XML or has no `ssv:ParameterSet`.
    """
    filename = Path(filename)
    ssv = f"{{{SSV_NAMESPACE}}}"
    try:
        root = ET.parse(filename).getroot()
    except ET.ParseError as error:
        raise ExperimentsError(f"cannot parse '{filename.name}': {error}") from None
    parameter_set = root if root.tag == f"{ssv}ParameterSet" else root.find(f".//{ssv}ParameterSet")
    if parameter_set is None:
        raise ExperimentsError(f"'{filename.name}' has no ssv:ParameterSet")
    parameters = []
    for parameter in parameter_set.iter(f"{ssv}Parameter"):
        for child in parameter:
            if child.tag.startswith(ssv):
                parameters.append(Parameter(parameter.get("name", ""), _local_name(child), child.get("value", "")))
                break
    return parameters

File designated by a relative URI of a layered standard, resolved against the directory base.

The URI may hold dot segments, as long as the resolved path stays inside the extracted FMU root.

Returns:

Type Description
tuple[Path | None, str | None]

tuple[Path | None, str | None]: The path of the file and None; or None and the reason why the URI does not designate a file of the FMU: "absolute URI" (scheme, authority or path starting with /), "outside of the FMU" or "missing file".

Source code in fmu_manipulation_toolbox/ls.py
def resolve_uri(uri: str, base: Path | str, root: Path | str) -> tuple[Path | None, str | None]:
    """File designated by a relative URI of a layered standard, resolved against the directory `base`.

    The URI may hold dot segments, as long as the resolved path stays inside the extracted FMU `root`.

    Returns:
        tuple[Path | None, str | None]: The path of the file and `None`; or `None` and the reason why the URI does
            not designate a file of the FMU: `"absolute URI"` (scheme, authority or path starting with `/`),
            `"outside of the FMU"` or `"missing file"`.
    """
    parsed = urllib.parse.urlsplit(uri)
    if parsed.scheme or parsed.netloc or parsed.path.startswith("/"):
        return None, "absolute URI"
    path = Path(os.path.normpath(Path(base) / urllib.parse.unquote(parsed.path)))
    try:
        path.relative_to(os.path.normpath(root))
    except ValueError:
        return None, "outside of the FMU"
    if not path.is_file():
        return None, "missing file"
    return path, None

Time series of FMI-LS-REF: stimuli and references of the experiments, simulated outputs.

The CSV files follow the convention of the FMI cross-check (Reference-FMUs, fmpy): comma separator, a header whose first column is time and whose other columns are the names of the FMI variables (quotes allowed), then one row per instant. Two rows may have the same time: an event, the second row gives the values after it.

Comparison dataclass

Result of the comparison of a simulated variable with its reference.

Attributes:

Name Type Description
name str

Name of the variable.

max_error float

Maximal absolute error over the instants of the reference (numbers only).

max_error_time float | None

Instant of the maximal error.

failure_time float | None

First instant where the criterion fails; None when the variable matches.

expected object

Value of the reference at failure_time.

simulated object

Simulated value at failure_time.

Source code in fmu_manipulation_toolbox/timeseries.py
@dataclass
class Comparison:
    """Result of the comparison of a simulated variable with its reference.

    Attributes:
        name (str): Name of the variable.
        max_error (float): Maximal absolute error over the instants of the reference (numbers only).
        max_error_time (float | None): Instant of the maximal error.
        failure_time (float | None): First instant where the criterion fails; `None` when the variable matches.
        expected: Value of the reference at `failure_time`.
        simulated: Simulated value at `failure_time`.
    """
    name: str
    max_error: float = 0.0
    max_error_time: float | None = None
    failure_time: float | None = None
    expected: object = None
    simulated: object = None

    @property
    def passed(self) -> bool:
        return self.failure_time is None

TimeSeries dataclass

Values of variables over time.

Attributes:

Name Type Description
times list[float]

Instants, non-decreasing (equal instants: an event).

columns dict[str, list]

Values of each variable, one per instant: text as read in a CSV file, or numbers.

Source code in fmu_manipulation_toolbox/timeseries.py
@dataclass
class TimeSeries:
    """Values of variables over time.

    Attributes:
        times (list[float]): Instants, non-decreasing (equal instants: an event).
        columns (dict[str, list]): Values of each variable, one per instant: text as read in a CSV file, or numbers.
    """
    times: list[float] = field(default_factory=list)
    columns: dict[str, list] = field(default_factory=dict)

    def index(self, time: float) -> int:
        """Index of the last instant that is not after `time` (the value after an event at `time`); -1 before the
        first instant. `time` matches an instant within a relative epsilon of 1e-9, so that a communication point
        computed by the simulation finds the row of its instant."""
        return bisect.bisect_right(self.times, time + 1e-9 * max(1.0, abs(time))) - 1

    def until(self, time: float) -> "TimeSeries":
        """Copy of the series up to `time` included (within the epsilon of `index`)."""
        end = self.index(time) + 1
        return TimeSeries(times=self.times[:end], columns={name: values[:end] for name, values in self.columns.items()})

    def value(self, name: str, time: float, interpolation: str = LINEAR):
        """Value of the variable `name` at `time`: before the first instant, the first value; after the last one, the
        last value; in between, the value interpolated as `interpolation` (`LINEAR` or `HOLD`).

        Raises:
            TimeSeriesError: The series has no instant, or a value to interpolate linearly is not a number.
        """
        if not self.times:
            raise TimeSeriesError("the time series has no instant")
        values = self.columns[name]
        i = self.index(time)
        if i < 0:
            return values[0]
        if interpolation == HOLD or i == len(self.times) - 1:
            return values[i]
        t0, t1 = self.times[i], self.times[i + 1]
        v0, v1 = to_number(values[i]), to_number(values[i + 1])
        fraction = min(max((time - t0) / (t1 - t0), 0.0), 1.0)   # time may precede t0 by the epsilon of index()
        return v0 + (v1 - v0) * fraction

index(time)

Index of the last instant that is not after time (the value after an event at time); -1 before the first instant. time matches an instant within a relative epsilon of 1e-9, so that a communication point computed by the simulation finds the row of its instant.

Source code in fmu_manipulation_toolbox/timeseries.py
def index(self, time: float) -> int:
    """Index of the last instant that is not after `time` (the value after an event at `time`); -1 before the
    first instant. `time` matches an instant within a relative epsilon of 1e-9, so that a communication point
    computed by the simulation finds the row of its instant."""
    return bisect.bisect_right(self.times, time + 1e-9 * max(1.0, abs(time))) - 1

until(time)

Copy of the series up to time included (within the epsilon of index).

Source code in fmu_manipulation_toolbox/timeseries.py
def until(self, time: float) -> "TimeSeries":
    """Copy of the series up to `time` included (within the epsilon of `index`)."""
    end = self.index(time) + 1
    return TimeSeries(times=self.times[:end], columns={name: values[:end] for name, values in self.columns.items()})

value(name, time, interpolation=LINEAR)

Value of the variable name at time: before the first instant, the first value; after the last one, the last value; in between, the value interpolated as interpolation (LINEAR or HOLD).

Raises:

Type Description
TimeSeriesError

The series has no instant, or a value to interpolate linearly is not a number.

Source code in fmu_manipulation_toolbox/timeseries.py
def value(self, name: str, time: float, interpolation: str = LINEAR):
    """Value of the variable `name` at `time`: before the first instant, the first value; after the last one, the
    last value; in between, the value interpolated as `interpolation` (`LINEAR` or `HOLD`).

    Raises:
        TimeSeriesError: The series has no instant, or a value to interpolate linearly is not a number.
    """
    if not self.times:
        raise TimeSeriesError("the time series has no instant")
    values = self.columns[name]
    i = self.index(time)
    if i < 0:
        return values[0]
    if interpolation == HOLD or i == len(self.times) - 1:
        return values[i]
    t0, t1 = self.times[i], self.times[i + 1]
    v0, v1 = to_number(values[i]), to_number(values[i + 1])
    fraction = min(max((time - t0) / (t1 - t0), 0.0), 1.0)   # time may precede t0 by the epsilon of index()
    return v0 + (v1 - v0) * fraction

TimeSeriesError

Bases: Exception

A time series that cannot be read or used.

Source code in fmu_manipulation_toolbox/timeseries.py
class TimeSeriesError(Exception):
    """A time series that cannot be read or used."""

compare(reference, simulated, name, rtol, atol, interpolation=LINEAR, exact=False)

Compares the variable name of simulated with reference at the instants of the reference.

The simulated value is interpolated as interpolation. Numbers (booleans as 0 / 1) match when abs(simulated - reference) <= atol + rtol * abs(reference); with exact (strings), when the texts are equal. At an event of the reference (rows with the same time), the value after it (its last row) is compared.

Raises:

Type Description
TimeSeriesError

A number is not a number, or a series has no instant.

Source code in fmu_manipulation_toolbox/timeseries.py
def compare(reference: TimeSeries, simulated: TimeSeries, name: str, rtol: float, atol: float,
            interpolation: str = LINEAR, exact: bool = False) -> Comparison:
    """Compares the variable `name` of `simulated` with `reference` at the instants of the reference.

    The simulated value is interpolated as `interpolation`. Numbers (booleans as 0 / 1) match when
    `abs(simulated - reference) <= atol + rtol * abs(reference)`; with `exact` (strings), when the texts are equal. At
    an event of the reference (rows with the same time), the value after it (its last row) is compared.

    Raises:
        TimeSeriesError: A number is not a number, or a series has no instant.
    """
    result = Comparison(name)
    times, values = reference.times, reference.columns[name]
    for i, (time, expected) in enumerate(zip(times, values, strict=False)):
        if i + 1 < len(times) and times[i + 1] == time:
            continue                                    # before an event: the value after it is compared
        actual = simulated.value(name, time, interpolation)
        if exact:
            passed = str(actual) == str(expected)
        else:
            error = abs(to_number(actual) - to_number(expected))
            if error > result.max_error or result.max_error_time is None:
                result.max_error, result.max_error_time = error, time
            passed = error <= atol + rtol * abs(to_number(expected))    # NaN fails
        if result.failure_time is None and not passed:
            result.failure_time, result.expected, result.simulated = time, expected, actual
    return result

read_csv(filename)

Reads a CSV file of the FMI cross-check convention.

Raises:

Type Description
TimeSeriesError

The file has no header, its first column is not time, a name is empty or repeated, a row has not the number of fields of the header, a time is not a number or the times decrease.

Source code in fmu_manipulation_toolbox/timeseries.py
def read_csv(filename: Path | str) -> TimeSeries:
    """Reads a CSV file of the FMI cross-check convention.

    Raises:
        TimeSeriesError: The file has no header, its first column is not `time`, a name is empty or repeated, a row
            has not the number of fields of the header, a time is not a number or the times decrease.
    """
    filename = Path(filename)
    with open(filename, newline="", encoding="utf-8") as file:
        rows = list(csv.reader(file))
    if not rows:
        raise TimeSeriesError(f"'{filename.name}': no header")
    header = [name.strip() for name in rows[0]]
    if header[0] != "time":
        raise TimeSeriesError(f"'{filename.name}': the first column is '{header[0]}', not 'time'")
    names = header[1:]
    for name in names:
        if not name:
            raise TimeSeriesError(f"'{filename.name}': a column has no name")
        if names.count(name) > 1:
            raise TimeSeriesError(f"'{filename.name}': the column '{name}' is repeated")

    series = TimeSeries(columns={name: [] for name in names})
    for line, row in enumerate(rows[1:], start=2):
        if not row:
            continue                                    # empty line, e.g. at the end of the file
        if len(row) != len(header):
            raise TimeSeriesError(f"'{filename.name}' line {line}: {len(row)} fields instead of {len(header)}")
        try:
            time = float(row[0])
        except ValueError:
            raise TimeSeriesError(f"'{filename.name}' line {line}: time '{row[0]}' is not a number") from None
        if not math.isfinite(time):
            raise TimeSeriesError(f"'{filename.name}' line {line}: time '{row[0]}' is not finite")
        if series.times and time < series.times[-1]:
            raise TimeSeriesError(f"'{filename.name}' line {line}: time {time} before the previous one")
        series.times.append(time)
        for name, value in zip(names, row[1:], strict=True):
            series.columns[name].append(value.strip())
    return series

to_number(value)

A value of a time series as a number: numbers as they are, text parsed (true / false accepted).

Raises:

Type Description
TimeSeriesError

The value is not a number.

Source code in fmu_manipulation_toolbox/timeseries.py
def to_number(value) -> float:
    """A value of a time series as a number: numbers as they are, text parsed (`true` / `false` accepted).

    Raises:
        TimeSeriesError: The value is not a number.
    """
    if isinstance(value, (int, float)):
        return float(value)
    text = str(value).strip()
    if text.lower() in ("true", "false"):
        return 1.0 if text.lower() == "true" else 0.0
    try:
        return float(text)
    except ValueError:
        raise TimeSeriesError(f"'{value}' is not a number") from None

Replay of an experiment of FMI-LS-REF with the container runtime.

The FMU is embedded in a temporary FMI-3 container (FMUContainer, whatever the FMI version of the FMU: the runtime embeds FMI-2 FMUs as well): one input per stimulus, one output per variable to record, the parameters as start values. The library of the container is then driven through its FMI-3 API (ctypes; the logger of FMI-2 is variadic, which ctypes cannot read on every platform): at each communication point t_k = start + k * step (computed, not accumulated), the stimuli interpolated at t_k are set, the outputs are read and recorded at t_k, then the container steps to t_k+1 (convention of fmpy and of the results of the Reference-FMUs: an output fed through follows its input at the same instant). When an embedded FMU asks to terminate the simulation, the container stops at the time reached: the simulation ends there, the outputs of this instant being the last ones recorded. An array output is recorded as one column per element, named as by the structured naming convention of FMI-3 (indices from 1, row-major order): y[1], y[2]... or m[1,1], m[1,2]...

The simulation runs in a dedicated process (multiprocessing, spawn): a crash of the FMU or of the runtime, or a simulation that never returns, fails the replay instead of the calling process, and the libraries loaded by the simulation are unloaded with its process.

SimulationError

Bases: Exception

An experiment that cannot be replayed.

Source code in fmu_manipulation_toolbox/simulation.py
class SimulationError(Exception):
    """An experiment that cannot be replayed."""

SimulationUnavailable

Bases: SimulationError

The container runtime, or the binary of the FMU, is not available for the host platform.

Source code in fmu_manipulation_toolbox/simulation.py
class SimulationUnavailable(SimulationError):
    """The container runtime, or the binary of the FMU, is not available for the host platform."""

SimulationUnsupported

Bases: SimulationError

An experiment that the temporary container cannot replay (a stimulus on a boolean input of an FMI-2 FMU).

Source code in fmu_manipulation_toolbox/simulation.py
class SimulationUnsupported(SimulationError):
    """An experiment that the temporary container cannot replay (a stimulus on a boolean input of an FMI-2 FMU)."""

experiment_times(experiment, model_description, references)

Start and stop times of an experiment: those of the experiment, else those of the DefaultExperiment of the FMU, else the first and the last instants of the references.

Raises:

Type Description
SimulationError

A time cannot be determined.

Source code in fmu_manipulation_toolbox/simulation.py
def experiment_times(experiment: Experiment, model_description: ModelDescription,
                     references: TimeSeries | None) -> tuple[float, float]:
    """Start and stop times of an experiment: those of the experiment, else those of the `DefaultExperiment` of the
    FMU, else the first and the last instants of the references.

    Raises:
        SimulationError: A time cannot be determined.
    """
    default = model_description.default_experiment
    times = []
    for name, value, index in (("startTime", experiment.start_time, 0), ("stopTime", experiment.stop_time, -1)):
        if value is None:
            value = _time(default, name)
        if value is None and references is not None and references.times:
            value = references.times[index]
            logger.info(f"Experiment '{experiment.name}': {name} {value} taken from the references.")
        if value is None:
            raise SimulationError(f"experiment '{experiment.name}': no {name}")
        times.append(value)
    return times[0], times[1]

replay(fmu_filename, experiment, outputs, stimuli=None, parameters=None, references=None, timeout=None, isolated=True)

Replays experiment on the FMU fmu_filename with the container runtime and records outputs.

Parameters:

Name Type Description Default
fmu_filename Path | str

The FMU.

required
experiment Experiment

Its start and stop times and its step size (None: see experiment_times; step size deduced by the container builder). Its tolerance is not used: the container runtime also takes the tolerance of the initialization as its tolerance on time.

required
outputs list[str]

Names of the output variables to record.

required
stimuli TimeSeries | None

Values of input variables (linear interpolation for the continuous reals, previous value otherwise).

None
parameters list[Parameter] | None

Start values of parameters.

None
references TimeSeries | None

The references, whose instants give the start and stop times when nothing else does.

None
timeout float | None

Time limit of the simulation, in seconds (None: no limit). Only with isolated.

None
isolated bool

Run the simulation in a dedicated process (False: in the calling process).

True

Returns:

Name Type Description
TimeSeries TimeSeries

The values of outputs at each communication point; an array output gives one column per element (y[1], y[2]..., m[1,1], m[1,2]...: indices from 1, row-major order).

Raises:

Type Description
SimulationUnavailable

The container or the FMU has no library for the host platform.

SimulationUnsupported

A stimulus is on a boolean input of an FMI-2 FMU, which the FMI-3 container cannot expose, or on an array input; an output is an array whose dimension is given by a structural parameter.

SimulationError

The container cannot be built, the simulation fails, crashes or exceeds timeout.

Source code in fmu_manipulation_toolbox/simulation.py
def replay(fmu_filename: Path | str, experiment: Experiment, outputs: list[str], stimuli: TimeSeries | None = None,
           parameters: list[Parameter] | None = None, references: TimeSeries | None = None,
           timeout: float | None = None, isolated: bool = True) -> TimeSeries:
    """Replays `experiment` on the FMU `fmu_filename` with the container runtime and records `outputs`.

    Args:
        fmu_filename: The FMU.
        experiment: Its start and stop times and its step size (`None`: see `experiment_times`; step size deduced by
            the container builder). Its `tolerance` is not used: the container runtime also takes the tolerance of
            the initialization as its tolerance on time.
        outputs: Names of the output variables to record.
        stimuli: Values of input variables (linear interpolation for the continuous reals, previous value otherwise).
        parameters: Start values of parameters.
        references: The references, whose instants give the start and stop times when nothing else does.
        timeout: Time limit of the simulation, in seconds (`None`: no limit). Only with `isolated`.
        isolated: Run the simulation in a dedicated process (`False`: in the calling process).

    Returns:
        TimeSeries: The values of `outputs` at each communication point; an array output gives one column per
            element (`y[1]`, `y[2]`..., `m[1,1]`, `m[1,2]`...: indices from 1, row-major order).

    Raises:
        SimulationUnavailable: The container or the FMU has no library for the host platform.
        SimulationUnsupported: A stimulus is on a boolean input of an FMI-2 FMU, which the FMI-3 container cannot
            expose, or on an array input; an output is an array whose dimension is given by a structural parameter.
        SimulationError: The container cannot be built, the simulation fails, crashes or exceeds `timeout`.
    """
    # Created and removed here: a library loaded by the simulation locks its files on Windows until its process ends.
    directory = Path(tempfile.mkdtemp(prefix="fmutool-lsref-"))
    try:
        arguments = (directory, Path(fmu_filename), experiment, outputs, stimuli, parameters or [], references)
        if isolated:
            return _simulate_in_process(arguments, timeout)
        return _simulate(*arguments)
    finally:
        shutil.rmtree(directory, ignore_errors=True)