Skip to content

Container

FMU Containers: FMUs embedding other FMUs.

FMUContainer is the entry point. The package is split by concern (types, arrays, embedded, rules, layout, txt, builder); every class stays importable from fmu_manipulation_toolbox.container, as when the package was a single module.

ArrayAggregate

Represents an FMI-2 array-element family (basename[i], basename[i,j], ...) aggregated as a virtual N-D array so it can be linked to an FMI-3 array port of matching shape.

Attributes:

Name Type Description
basename

Name of the virtual aggregate (without brackets).

dims

Shape as a tuple of positive integers, e.g. (3,) for a 1D vector of length 3, (2, 3) for a 2×3 matrix.

ordered_element_names

Original scalar port names sorted in row-major order (last index varies fastest), matching the FMI-3 array memory layout.

Source code in fmu_manipulation_toolbox/container/arrays.py
class ArrayAggregate:
    """Represents an FMI-2 array-element family (`basename[i]`, `basename[i,j]`,
    ...) aggregated as a virtual N-D array so it can be linked to an FMI-3
    array port of matching shape.

    Attributes:
        basename: Name of the virtual aggregate (without brackets).
        dims: Shape as a tuple of positive integers, e.g. `(3,)` for a 1D
            vector of length 3, `(2, 3)` for a 2×3 matrix.
        ordered_element_names: Original scalar port names sorted in
            **row-major** order (last index varies fastest), matching the
            FMI-3 array memory layout.
    """

    __slots__ = ("basename", "dims", "ordered_element_names")

    # Trailing bracket group: `[3]`, `[1,2]`, ... (Modelica-style, single
    # bracket with comma-separated indices) at the end of a name.
    _ARRAY_ELEM_RE = re.compile(r"^(.+)\[(\d+(?:,\d+)*)]$")

    def __init__(self, basename: str, dims: tuple[int, ...], ordered_element_names: list[str]):
        self.basename = basename
        self.dims = dims
        self.ordered_element_names = ordered_element_names

    @property
    def size(self) -> int:
        """Total number of scalar elements (product of `dims`)."""
        return len(self.ordered_element_names)

    @property
    def rank(self) -> int:
        """Number of axes (`len(dims)`)."""
        return len(self.dims)

    @property
    def shape_str(self) -> str:
        """Human-readable shape, e.g. `"2x3"` for a 2×3 matrix."""
        return "x".join(str(d) for d in self.dims)

    def __repr__(self):
        return f"ArrayAggregate({self.basename!r}, shape={self.shape_str}, size={self.size})"

    # -- Alternative constructors / parsers ------------------------------------

    @classmethod
    def parse_element_name(cls, name: str) -> tuple[str, tuple[int, ...]] | None:
        """Return `(basename, indices)` if `name` has the form `basename[i,j,...]`
        (Modelica-style comma notation, conforming to FMI-2 array-element
        naming). Returns `None` if `name` is not a recognized array element
        name.
        """
        m = cls._ARRAY_ELEM_RE.match(name)
        if not m:
            return None
        basename = m.group(1)
        indices = tuple(int(tok) for tok in m.group(2).split(","))
        return basename, indices

    @classmethod
    def detect_all(
            cls,
            port_names: Iterable[str],
            existing_names: set[str] | None = None,
            log_prefix: str = "",
    ) -> list["ArrayAggregate"]:
        """Detect FMI-2 array-element families among `port_names` and return the
        valid N-D aggregates as `ArrayAggregate` instances.

        Only aggregates whose indices form a complete, contiguous hyperrectangle
        starting at 0 or 1 on every axis are returned. Attribute homogeneity
        (type, causality, ...) is **not** checked here; callers must filter
        further if needed.

        `existing_names` avoids emitting an aggregate whose basename collides
        with an already-existing (scalar) port.
        """
        if existing_names is None:
            existing_names = set()

        groups: dict[str, list[tuple[tuple[int, ...], str]]] = defaultdict(list)
        for name in port_names:
            parsed = cls.parse_element_name(name)
            if parsed is None:
                continue
            basename, indices = parsed
            groups[basename].append((indices, name))

        aggregates: list[ArrayAggregate] = []
        for basename, elements in groups.items():
            if basename in existing_names:
                continue

            rank = len(elements[0][0])
            if not all(len(idx) == rank for idx, _ in elements):
                if log_prefix:
                    logger.debug(f"'{log_prefix}': mixed ranks for array '{basename}', "
                                 f"aggregate not created.")
                continue

            mins = [min(idx[a] for idx, _ in elements) for a in range(rank)]
            maxs = [max(idx[a] for idx, _ in elements) for a in range(rank)]
            if not all(s in (0, 1) for s in mins):
                continue
            dims = tuple(maxs[a] - mins[a] + 1 for a in range(rank))

            expected_count = 1
            for d in dims:
                expected_count *= d
            actual_set = {idx for idx, _ in elements}
            if len(actual_set) != len(elements) or expected_count != len(elements):
                if log_prefix:
                    logger.debug(f"'{log_prefix}': non-contiguous / duplicated array elements "
                                 f"for '{basename}', aggregate not created.")
                continue
            expected_set = set(itertools.product(
                *(range(mins[a], mins[a] + dims[a]) for a in range(rank))))
            if expected_set != actual_set:
                if log_prefix:
                    logger.debug(f"'{log_prefix}': non-contiguous array elements for '{basename}', "
                                 f"aggregate not created.")
                continue

            # Row-major sort: last index varies fastest.
            elements.sort(key=lambda e: e[0])
            ordered_names = [n for _, n in elements]
            aggregates.append(cls(basename, dims, ordered_names))

        return aggregates

rank property

Number of axes (len(dims)).

shape_str property

Human-readable shape, e.g. "2x3" for a 2×3 matrix.

size property

Total number of scalar elements (product of dims).

detect_all(port_names, existing_names=None, log_prefix='') classmethod

Detect FMI-2 array-element families among port_names and return the valid N-D aggregates as ArrayAggregate instances.

Only aggregates whose indices form a complete, contiguous hyperrectangle starting at 0 or 1 on every axis are returned. Attribute homogeneity (type, causality, ...) is not checked here; callers must filter further if needed.

existing_names avoids emitting an aggregate whose basename collides with an already-existing (scalar) port.

Source code in fmu_manipulation_toolbox/container/arrays.py
@classmethod
def detect_all(
        cls,
        port_names: Iterable[str],
        existing_names: set[str] | None = None,
        log_prefix: str = "",
) -> list["ArrayAggregate"]:
    """Detect FMI-2 array-element families among `port_names` and return the
    valid N-D aggregates as `ArrayAggregate` instances.

    Only aggregates whose indices form a complete, contiguous hyperrectangle
    starting at 0 or 1 on every axis are returned. Attribute homogeneity
    (type, causality, ...) is **not** checked here; callers must filter
    further if needed.

    `existing_names` avoids emitting an aggregate whose basename collides
    with an already-existing (scalar) port.
    """
    if existing_names is None:
        existing_names = set()

    groups: dict[str, list[tuple[tuple[int, ...], str]]] = defaultdict(list)
    for name in port_names:
        parsed = cls.parse_element_name(name)
        if parsed is None:
            continue
        basename, indices = parsed
        groups[basename].append((indices, name))

    aggregates: list[ArrayAggregate] = []
    for basename, elements in groups.items():
        if basename in existing_names:
            continue

        rank = len(elements[0][0])
        if not all(len(idx) == rank for idx, _ in elements):
            if log_prefix:
                logger.debug(f"'{log_prefix}': mixed ranks for array '{basename}', "
                             f"aggregate not created.")
            continue

        mins = [min(idx[a] for idx, _ in elements) for a in range(rank)]
        maxs = [max(idx[a] for idx, _ in elements) for a in range(rank)]
        if not all(s in (0, 1) for s in mins):
            continue
        dims = tuple(maxs[a] - mins[a] + 1 for a in range(rank))

        expected_count = 1
        for d in dims:
            expected_count *= d
        actual_set = {idx for idx, _ in elements}
        if len(actual_set) != len(elements) or expected_count != len(elements):
            if log_prefix:
                logger.debug(f"'{log_prefix}': non-contiguous / duplicated array elements "
                             f"for '{basename}', aggregate not created.")
            continue
        expected_set = set(itertools.product(
            *(range(mins[a], mins[a] + dims[a]) for a in range(rank))))
        if expected_set != actual_set:
            if log_prefix:
                logger.debug(f"'{log_prefix}': non-contiguous array elements for '{basename}', "
                             f"aggregate not created.")
            continue

        # Row-major sort: last index varies fastest.
        elements.sort(key=lambda e: e[0])
        ordered_names = [n for _, n in elements]
        aggregates.append(cls(basename, dims, ordered_names))

    return aggregates

parse_element_name(name) classmethod

Return (basename, indices) if name has the form basename[i,j,...] (Modelica-style comma notation, conforming to FMI-2 array-element naming). Returns None if name is not a recognized array element name.

Source code in fmu_manipulation_toolbox/container/arrays.py
@classmethod
def parse_element_name(cls, name: str) -> tuple[str, tuple[int, ...]] | None:
    """Return `(basename, indices)` if `name` has the form `basename[i,j,...]`
    (Modelica-style comma notation, conforming to FMI-2 array-element
    naming). Returns `None` if `name` is not a recognized array element
    name.
    """
    m = cls._ARRAY_ELEM_RE.match(name)
    if not m:
        return None
    basename = m.group(1)
    indices = tuple(int(tok) for tok in m.group(2).split(","))
    return basename, indices

AutoWired

Collects the rules automatically generated by implicit wiring.

Used to report back to the AssemblyNode which inputs, outputs, and links were created by auto-wiring, so they can be recorded in the assembly topology.

Attributes:

Name Type Description
rule_input list[list[str]]

Auto-generated input rules [exposed_name, fmu_name, port_name].

rule_output list[list[str]]

Auto-generated output rules [fmu_name, port_name, exposed_name].

rule_link list[list[str]]

Auto-generated link rules [from_fmu, from_port, to_fmu, to_port].

nb_param int

Number of auto-exposed parameters (subset of inputs).

Source code in fmu_manipulation_toolbox/container/rules.py
class AutoWired:
    """Collects the rules automatically generated by implicit wiring.

    Used to report back to the
    [AssemblyNode][fmu_manipulation_toolbox.assembly.AssemblyNode] which
    inputs, outputs, and links were created by auto-wiring, so they
    can be recorded in the assembly topology.

    Attributes:
        rule_input (list[list[str]]): Auto-generated input rules
            `[exposed_name, fmu_name, port_name]`.
        rule_output (list[list[str]]): Auto-generated output rules
            `[fmu_name, port_name, exposed_name]`.
        rule_link (list[list[str]]): Auto-generated link rules
            `[from_fmu, from_port, to_fmu, to_port]`.
        nb_param (int): Number of auto-exposed parameters (subset of inputs).
    """

    def __init__(self):
        self.rule_input = []
        self.rule_output = []
        self.rule_link = []
        self.nb_param = 0

    def __repr__(self):
        return (f"{self.nb_param} parameters, {len(self.rule_input) - self.nb_param} inputs,"
                f" {len(self.rule_output)} outputs, {len(self.rule_link)} links.")

    def add_input(self, from_port, to_fmu, to_port):
        self.rule_input.append([from_port, to_fmu, to_port])

    def add_parameter(self, from_port, to_fmu, to_port):
        self.rule_input.append([from_port, to_fmu, to_port])
        self.nb_param += 1

    def add_output(self, from_fmu, from_port, to_port):
        self.rule_output.append([from_fmu, from_port, to_port])

    def add_link(self, from_fmu, from_port, to_fmu, to_port):
        self.rule_link.append([from_fmu, from_port, to_fmu, to_port])

Clock dataclass

Clock of an embedded FMU scheduled by the importer: its value reference in the FMU, and the local variable of the container that feeds it, how it ticks and, when the FMU declares them, its interval and its shift (-1 if not declared).

Source code in fmu_manipulation_toolbox/container/txt.py
@dataclass
class Clock:
    """Clock of an embedded FMU scheduled by the importer: its value reference in the FMU, and the local variable of
    the container that feeds it, how it ticks and, when the FMU declares them, its interval and its shift (-1 if not
    declared)."""
    fmu_vr: int
    vr: int
    variability: str
    interval: str
    shift: str

ClockList

Tracks clocks that need to be scheduled by the FMI importer.

Used for LS-BUS support where the container runtime needs to trigger countdown clocks on embedded FMUs.

Attributes:

Name Type Description
clocks_per_fmu dict[int, list[Clock]]

Clock entries per FMU index.

fmu_index dict[str, int]

Mapping from FMU name to its index in the container.

Source code in fmu_manipulation_toolbox/container/txt.py
class ClockList:
    """Tracks clocks that need to be scheduled by the FMI importer.

    Used for LS-BUS support where the container runtime needs to trigger
    countdown clocks on embedded FMUs.

    Attributes:
        clocks_per_fmu (dict[int, list[Clock]]): Clock entries per FMU index.
        fmu_index (dict[str, int]): Mapping from FMU name to its index
            in the container.
    """

    def __init__(self, involved_fmu: InvolvedFMU):
        self.clocks_per_fmu: defaultdict[int, list[Clock]] = defaultdict(list)
        self.fmu_index: dict[str, int] = {}
        for i, fmu_name in enumerate(involved_fmu):
            self.fmu_index[fmu_name] = i

    def append(self, cport: ContainerPort, vr: int):
        """Register a clock for importer scheduling.

        Args:
            cport (ContainerPort): The clocked port on the embedded FMU.
            vr (int): The local value reference of the clock.
        """
        port = cport.port
        assert port.interval_variability is not None
        self.clocks_per_fmu[self.fmu_index[cport.fmu.name]].append(
            Clock(port.vr, vr, port.interval_variability, port.interval_decimal or "-1", port.shift_decimal or "-1"))

    def write_txt(self, txt_file: IO) -> None:
        """Write the clock scheduling table to the `container.txt` file.

        Args:
            txt_file (IO): Writable text file handle.
        """
        print("# importer CLOCKS: <FMU_INDEX> <NB> <FMU_VR> <VR> <VARIABILITY> <INTERVAL> <SHIFT> [...]", file=txt_file)
        nb_total_clocks = 0
        for clocks in self.clocks_per_fmu.values():
            nb_total_clocks += len(clocks)

        print(f"{len(self.clocks_per_fmu)} {nb_total_clocks}", file=txt_file)
        for index, clocks in self.clocks_per_fmu.items():
            clocks_str = " ".join([f"{clock.fmu_vr} {clock.vr} {clock.variability} {clock.interval} {clock.shift}"
                                   for clock in clocks])
            print(f"{index} {len(clocks)} {clocks_str}", file=txt_file)

append(cport, vr)

Register a clock for importer scheduling.

Parameters:

Name Type Description Default
cport ContainerPort

The clocked port on the embedded FMU.

required
vr int

The local value reference of the clock.

required
Source code in fmu_manipulation_toolbox/container/txt.py
def append(self, cport: ContainerPort, vr: int):
    """Register a clock for importer scheduling.

    Args:
        cport (ContainerPort): The clocked port on the embedded FMU.
        vr (int): The local value reference of the clock.
    """
    port = cport.port
    assert port.interval_variability is not None
    self.clocks_per_fmu[self.fmu_index[cport.fmu.name]].append(
        Clock(port.vr, vr, port.interval_variability, port.interval_decimal or "-1", port.shift_decimal or "-1"))

write_txt(txt_file)

Write the clock scheduling table to the container.txt file.

Parameters:

Name Type Description Default
txt_file IO

Writable text file handle.

required
Source code in fmu_manipulation_toolbox/container/txt.py
def write_txt(self, txt_file: IO) -> None:
    """Write the clock scheduling table to the `container.txt` file.

    Args:
        txt_file (IO): Writable text file handle.
    """
    print("# importer CLOCKS: <FMU_INDEX> <NB> <FMU_VR> <VR> <VARIABILITY> <INTERVAL> <SHIFT> [...]", file=txt_file)
    nb_total_clocks = 0
    for clocks in self.clocks_per_fmu.values():
        nb_total_clocks += len(clocks)

    print(f"{len(self.clocks_per_fmu)} {nb_total_clocks}", file=txt_file)
    for index, clocks in self.clocks_per_fmu.items():
        clocks_str = " ".join([f"{clock.fmu_vr} {clock.vr} {clock.variability} {clock.interval} {clock.shift}"
                               for clock in clocks])
        print(f"{index} {len(clocks)} {clocks_str}", file=txt_file)

ContainerInput

Represents an input port exposed by the container.

A single container input can fan out to multiple embedded FMU input ports, provided they share the same type and causality.

Attributes:

Name Type Description
name str

Exposed name of the container input.

type_name str

Container-internal type name (e.g. "real64").

causality str

Port causality ("input" or "parameter").

cport_list list[ContainerPort]

List of embedded FMU ports connected to this input.

Source code in fmu_manipulation_toolbox/container/rules.py
class ContainerInput:
    """Represents an input port exposed by the container.

    A single container input can fan out to multiple embedded FMU input ports,
    provided they share the same type and causality.

    Attributes:
        name (str): Exposed name of the container input.
        type_name (str): Container-internal type name (e.g. `"real64"`).
        causality (str): Port causality (`"input"` or `"parameter"`).
        cport_list (list[ContainerPort]): List of embedded FMU ports connected
            to this input.
    """

    def __init__(self, name: str, cport_to: ContainerPort):
        self.name = name
        self.type_name = cport_to.port.type_name
        self.causality = cport_to.port.causality
        self.cport_list = [cport_to]
        self.size = cport_to.port.size()

    def add_cport(self, cport_to: ContainerPort):
        """Connect an additional embedded FMU port to this container input.

        Args:
            cport_to (ContainerPort): The embedded FMU port to connect.

        Raises:
            FMUContainerError: If the port is already connected, or if types
                or causalities do not match.
        """
        if cport_to in self.cport_list: # Cannot be reached ! (Assembly prevent this to happen)
            raise FMUContainerError(f"{cport_to} is already connected to the input '{self.name}'.")

        if cport_to.port.type_name != self.type_name:
            raise FMUContainerError(f"Cannot connect '{self.name}' of type '{self.type_name}' to "
                                    f"port {cport_to.label} of type '{cport_to.port.type_name}'.")

        if cport_to.port.size() != self.size:
            raise FMUContainerError(f"Cannot connect '{self.name}' of dimension {self.size} to "
                                    f"port {cport_to.label} of dimension {cport_to.port.size()}.")

        if cport_to.port.causality != self.causality:
            raise FMUContainerError(f"Cannot connect the {self.causality} '{self.name}' to "
                                    f"the {cport_to.port.causality} {cport_to.label}.")

        self.cport_list.append(cport_to)

    @property
    def has_reset(self) -> bool:
        """Whether this input feeds a `container.reset` port: its value is then stored by the container."""
        return any(cport.port.is_reset for cport in self.cport_list)

has_reset property

Whether this input feeds a container.reset port: its value is then stored by the container.

add_cport(cport_to)

Connect an additional embedded FMU port to this container input.

Parameters:

Name Type Description Default
cport_to ContainerPort

The embedded FMU port to connect.

required

Raises:

Type Description
FMUContainerError

If the port is already connected, or if types or causalities do not match.

Source code in fmu_manipulation_toolbox/container/rules.py
def add_cport(self, cport_to: ContainerPort):
    """Connect an additional embedded FMU port to this container input.

    Args:
        cport_to (ContainerPort): The embedded FMU port to connect.

    Raises:
        FMUContainerError: If the port is already connected, or if types
            or causalities do not match.
    """
    if cport_to in self.cport_list: # Cannot be reached ! (Assembly prevent this to happen)
        raise FMUContainerError(f"{cport_to} is already connected to the input '{self.name}'.")

    if cport_to.port.type_name != self.type_name:
        raise FMUContainerError(f"Cannot connect '{self.name}' of type '{self.type_name}' to "
                                f"port {cport_to.label} of type '{cport_to.port.type_name}'.")

    if cport_to.port.size() != self.size:
        raise FMUContainerError(f"Cannot connect '{self.name}' of dimension {self.size} to "
                                f"port {cport_to.label} of dimension {cport_to.port.size()}.")

    if cport_to.port.causality != self.causality:
        raise FMUContainerError(f"Cannot connect the {self.causality} '{self.name}' to "
                                f"the {cport_to.port.causality} {cport_to.label}.")

    self.cport_list.append(cport_to)

ContainerLayout dataclass

Value references of a container, allocated from its rules before any file is written.

The modelDescription.xml, container.txt and datalog.txt writers only read the layout, so a container can be built several times. The allocation order fixes the value references: the reserved variables first (time, ts_multiplier, solver, profiling), then the local variables of the links and of the converted outputs, then the container inputs and outputs.

Attributes:

Name Type Description
table ValueReferenceTable

The allocator, with the local storage of each type.

time int

Value reference of the time.

ts_multiplier int

Value reference of the container.ts_multiplier input (allocated even if not exposed).

solver int

Value reference of the container.solver input (allocated even if not exposed).

profiling list[int]

Value references of the rt_ratio of each embedded FMU, empty without profiling.

links dict[Link, int]

Value reference of the local variable of each link.

converted dict[Link, dict[str, int]]

Value references of the converted copies of each link, by target type.

inputs dict[str, int]

Value reference of each container input, by exposed name.

outputs dict[str, int]

Value reference of each container output, by exposed name.

reset_inputs dict[str, int]

Local storage offset of each container input feeding container.reset ports, by exposed name: the runtime reads the trigger there.

output_conversions dict[str, OutputConversion]

The container outputs exposed through a converted local variable, by exposed name.

aggregate_outputs dict[str, int]

Value reference of the local variable of each container output that is an FMI-2 array aggregate (not converted), by exposed name: the variable is the output, its elements are exchanged one by one with the FMU.

aggregate_inputs dict[str, int]

Value reference of the local variable of each container input feeding FMI-2 array aggregates, by exposed name: the input writes it, its elements go one by one to the FMUs.

Source code in fmu_manipulation_toolbox/container/layout.py
@dataclass
class ContainerLayout:
    """Value references of a container, allocated from its rules before any file is written.

    The `modelDescription.xml`, `container.txt` and `datalog.txt` writers only read the layout, so a container can be
    built several times. The allocation order fixes the value references: the reserved variables first (time,
    `ts_multiplier`, solver, profiling), then the local variables of the links and of the converted outputs, then the
    container inputs and outputs.

    Attributes:
        table (ValueReferenceTable): The allocator, with the local storage of each type.
        time (int): Value reference of the time.
        ts_multiplier (int): Value reference of the `container.ts_multiplier` input (allocated even if not exposed).
        solver (int): Value reference of the `container.solver` input (allocated even if not exposed).
        profiling (list[int]): Value references of the `rt_ratio` of each embedded FMU, empty without profiling.
        links (dict[Link, int]): Value reference of the local variable of each link.
        converted (dict[Link, dict[str, int]]): Value references of the converted copies of each link, by target type.
        inputs (dict[str, int]): Value reference of each container input, by exposed name.
        outputs (dict[str, int]): Value reference of each container output, by exposed name.
        reset_inputs (dict[str, int]): Local storage offset of each container input feeding `container.reset`
            ports, by exposed name: the runtime reads the trigger there.
        output_conversions (dict[str, OutputConversion]): The container outputs exposed through a converted local
            variable, by exposed name.
        aggregate_outputs (dict[str, int]): Value reference of the local variable of each container output that is
            an FMI-2 array aggregate (not converted), by exposed name: the variable is the output, its elements are
            exchanged one by one with the FMU.
        aggregate_inputs (dict[str, int]): Value reference of the local variable of each container input feeding
            FMI-2 array aggregates, by exposed name: the input writes it, its elements go one by one to the FMUs.
    """
    table: ValueReferenceTable
    time: int
    ts_multiplier: int
    solver: int
    profiling: list[int]
    links: dict[Link, int]
    converted: dict[Link, dict[str, int]]
    inputs: dict[str, int]
    outputs: dict[str, int]
    reset_inputs: dict[str, int]
    output_conversions: dict[str, OutputConversion]
    aggregate_outputs: dict[str, int]
    aggregate_inputs: dict[str, int]

    @classmethod
    def allocate(cls, links: Iterable[Link], inputs: dict[str, ContainerInput], outputs: dict[str, ContainerPort],
                 nb_profiling: int = 0, fmi_version: int | None = None) -> "ContainerLayout":
        """Allocate the value references of a container.

        Args:
            links (Iterable[Link]): Links between the embedded FMUs, in order.
            inputs (dict[str, ContainerInput]): Container inputs, by exposed name.
            outputs (dict[str, ContainerPort]): Container outputs, by exposed name.
            nb_profiling (int): Number of profiling variables (one per embedded FMU), `0` without profiling.
            fmi_version (int | None): FMI version of the container: an output that is a boolean of the other FMI
                version is exposed through a converted local variable (`output_conversions`). `None`: no conversion.

        Returns:
            ContainerLayout: The value references.
        """
        table = ValueReferenceTable()
        time = table.add_vr("real64", local=True)
        ts_multiplier = table.add_vr("integer32", local=True)
        solver = table.add_vr("integer32", local=True)
        profiling = [table.add_vr("real64", local=True) for _ in range(nb_profiling)]

        # Local variables before the container ports, so that they get the lowest value references.
        link_vrs: dict[Link, int] = {}
        converted: dict[Link, dict[str, int]] = {}
        for link in links:
            link_vrs[link], converted[link] = table.add_link(link)
        output_conversions = cls._output_conversions(table, link_vrs, converted, outputs, fmi_version)
        # FMI-2 array aggregates: the runtime exchanges a port of an FMI-2 FMU as one scalar, their elements are
        # exchanged one by one through a local variable (once per port).
        aggregate_outputs: dict[str, int] = {}
        by_port: dict[ContainerPort, int] = {}
        for name, cport in outputs.items():
            if cport.port.is_fmi2_aggregate and name not in output_conversions:
                if cport not in by_port:
                    by_port[cport] = table.add_vr(cport, local=True)
                aggregate_outputs[name] = by_port[cport]
        aggregate_inputs = {name: table.add_vr(input_port.type_name, local=True, port_size=input_port.size)
                            for name, input_port in inputs.items()
                            if any(cport.port.is_fmi2_aggregate for cport in input_port.cport_list)}

        input_vrs = {name: table.add_vr(input_port.type_name) for name, input_port in inputs.items()}
        output_vrs = {name: output_conversions[name].vr if name in output_conversions else
                      aggregate_outputs[name] if name in aggregate_outputs else table.add_vr(output_port)
                      for name, output_port in outputs.items()}
        # Last: the other local variables are listed by value reference, their storage follows their order.
        reset_inputs = {name: table.add_storage(input_port.type_name) for name, input_port in inputs.items()
                        if input_port.has_reset}

        return cls(table, time, ts_multiplier, solver, profiling, link_vrs, converted, input_vrs, output_vrs,
                   reset_inputs, output_conversions, aggregate_outputs, aggregate_inputs)

    @staticmethod
    def _output_conversions(table: ValueReferenceTable, link_vrs: dict[Link, int],
                            converted: dict[Link, dict[str, int]], outputs: dict[str, ContainerPort],
                            fmi_version: int | None) -> dict[str, OutputConversion]:
        """The outputs that are booleans of the other FMI version, with their local variables: the one of the link
        of the port and its converted copy when they exist, allocated otherwise (once per port)."""
        if fmi_version is None:
            return {}
        exposable = CONTAINER_TO_FMI[fmi_version]
        link_of = {link.cport_from: link for link in link_vrs if link.cport_from is not None}
        conversions: dict[str, OutputConversion] = {}
        by_port: dict[ContainerPort, OutputConversion] = {}
        for name, cport in outputs.items():
            type_name = cport.port.type_name
            target = OTHER_BOOLEAN.get(type_name)
            if type_name in exposable or target not in exposable:
                continue
            if cport in by_port:            # the same port exposed under another name
                conversions[name] = by_port[cport]
                continue
            link = link_of.get(cport)
            if link is not None:
                local, own_local, vr = link_vrs[link], False, converted[link].get(target)
            else:
                local, own_local, vr = table.add_vr(cport, local=True), True, None
            own_copy = vr is None
            if own_copy:
                vr = table.add_vr(target, local=True, port_size=cport.port.size())
            assert vr is not None
            conversions[name] = by_port[cport] = OutputConversion(
                cport, local, target, CONVERSION_FUNCTION[f"{type_name}/{target}"], vr, own_local, own_copy)
        return conversions

    def local_offset(self, vr: int) -> int:
        """Index of a local variable in the storage of its type (`<FMU_VR>` of the local lines of `container.txt`)."""
        return self.table.vr_to_local[vr]

allocate(links, inputs, outputs, nb_profiling=0, fmi_version=None) classmethod

Allocate the value references of a container.

Parameters:

Name Type Description Default
links Iterable[Link]

Links between the embedded FMUs, in order.

required
inputs dict[str, ContainerInput]

Container inputs, by exposed name.

required
outputs dict[str, ContainerPort]

Container outputs, by exposed name.

required
nb_profiling int

Number of profiling variables (one per embedded FMU), 0 without profiling.

0
fmi_version int | None

FMI version of the container: an output that is a boolean of the other FMI version is exposed through a converted local variable (output_conversions). None: no conversion.

None

Returns:

Name Type Description
ContainerLayout ContainerLayout

The value references.

Source code in fmu_manipulation_toolbox/container/layout.py
@classmethod
def allocate(cls, links: Iterable[Link], inputs: dict[str, ContainerInput], outputs: dict[str, ContainerPort],
             nb_profiling: int = 0, fmi_version: int | None = None) -> "ContainerLayout":
    """Allocate the value references of a container.

    Args:
        links (Iterable[Link]): Links between the embedded FMUs, in order.
        inputs (dict[str, ContainerInput]): Container inputs, by exposed name.
        outputs (dict[str, ContainerPort]): Container outputs, by exposed name.
        nb_profiling (int): Number of profiling variables (one per embedded FMU), `0` without profiling.
        fmi_version (int | None): FMI version of the container: an output that is a boolean of the other FMI
            version is exposed through a converted local variable (`output_conversions`). `None`: no conversion.

    Returns:
        ContainerLayout: The value references.
    """
    table = ValueReferenceTable()
    time = table.add_vr("real64", local=True)
    ts_multiplier = table.add_vr("integer32", local=True)
    solver = table.add_vr("integer32", local=True)
    profiling = [table.add_vr("real64", local=True) for _ in range(nb_profiling)]

    # Local variables before the container ports, so that they get the lowest value references.
    link_vrs: dict[Link, int] = {}
    converted: dict[Link, dict[str, int]] = {}
    for link in links:
        link_vrs[link], converted[link] = table.add_link(link)
    output_conversions = cls._output_conversions(table, link_vrs, converted, outputs, fmi_version)
    # FMI-2 array aggregates: the runtime exchanges a port of an FMI-2 FMU as one scalar, their elements are
    # exchanged one by one through a local variable (once per port).
    aggregate_outputs: dict[str, int] = {}
    by_port: dict[ContainerPort, int] = {}
    for name, cport in outputs.items():
        if cport.port.is_fmi2_aggregate and name not in output_conversions:
            if cport not in by_port:
                by_port[cport] = table.add_vr(cport, local=True)
            aggregate_outputs[name] = by_port[cport]
    aggregate_inputs = {name: table.add_vr(input_port.type_name, local=True, port_size=input_port.size)
                        for name, input_port in inputs.items()
                        if any(cport.port.is_fmi2_aggregate for cport in input_port.cport_list)}

    input_vrs = {name: table.add_vr(input_port.type_name) for name, input_port in inputs.items()}
    output_vrs = {name: output_conversions[name].vr if name in output_conversions else
                  aggregate_outputs[name] if name in aggregate_outputs else table.add_vr(output_port)
                  for name, output_port in outputs.items()}
    # Last: the other local variables are listed by value reference, their storage follows their order.
    reset_inputs = {name: table.add_storage(input_port.type_name) for name, input_port in inputs.items()
                    if input_port.has_reset}

    return cls(table, time, ts_multiplier, solver, profiling, link_vrs, converted, input_vrs, output_vrs,
               reset_inputs, output_conversions, aggregate_outputs, aggregate_inputs)

local_offset(vr)

Index of a local variable in the storage of its type (<FMU_VR> of the local lines of container.txt).

Source code in fmu_manipulation_toolbox/container/layout.py
def local_offset(self, vr: int) -> int:
    """Index of a local variable in the storage of its type (`<FMU_VR>` of the local lines of `container.txt`)."""
    return self.table.vr_to_local[vr]

ContainerPort

References a specific port of an embedded FMU within a container.

Wraps an EmbeddedFMUPort together with its parent EmbeddedFMU. The value references of the container are not stored on the rules: they are allocated at each build, see ContainerLayout.

Attributes:

Name Type Description
fmu EmbeddedFMU

The embedded FMU owning this port.

port EmbeddedFMUPort

The port descriptor.

Raises:

Type Description
FMUContainerError

If the port name does not exist in the FMU.

Source code in fmu_manipulation_toolbox/container/rules.py
class ContainerPort:
    """References a specific port of an embedded FMU within a container.

    Wraps an [EmbeddedFMUPort][fmu_manipulation_toolbox.container.EmbeddedFMUPort]
    together with its parent
    [EmbeddedFMU][fmu_manipulation_toolbox.container.EmbeddedFMU]. The value
    references of the container are not stored on the rules: they are allocated
    at each build, see [ContainerLayout][fmu_manipulation_toolbox.container.ContainerLayout].

    Attributes:
        fmu (EmbeddedFMU): The embedded FMU owning this port.
        port (EmbeddedFMUPort): The port descriptor.

    Raises:
        FMUContainerError: If the port name does not exist in the FMU.
    """

    def __init__(self, fmu: EmbeddedFMU, port_name: str):
        self.fmu = fmu
        try:
            self.port = fmu.ports[port_name]
        except KeyError:
            raise FMUContainerError(f"Port '{fmu.name}/{port_name}' does not exist.") from None

    @property
    def label(self) -> str:
        """The name of the port, with its FMU, between single quotes: `'a.fmu/y'`."""
        return f"'{self.fmu.name}/{self.port.name}'"

    def __repr__(self):
        return f"Port {self.label}"

    def is_exposable(self, role: str) -> bool:
        """Whether the port can be exposed as `role` (INPUT, OUTPUT) of the container. Clocks and clocked variables
        cannot: the container has no clocked partition on its interface. Such a port is reported as an error and
        left out, the build goes on."""
        if self.port.is_clocked:
            logger.error(f"Cannot use {self} as {role} of the container: clocks and clocked variables cannot be "
                         f"exposed. It is not exposed.")
            return False
        return True

    def check_structural_parameter(self):
        """A structural parameter exposed on the container is set in Configuration Mode: it must be a scalar, and
        not give the dimension of an array (the container is built for the dimensions of the arrays).

        Raises:
            FMUContainerError: If the structural parameter is an array or gives the dimension of a port.
        """
        if self.port.dimensions:
            raise FMUContainerError(f"Cannot expose {self}: an array structural parameter is not supported.")
        for port in self.fmu.ports.values():
            if ("valueReference", self.port.vr) in port.dimensions:
                raise FMUContainerError(f"Cannot expose {self}: it gives the dimension of '{port.name}'.")

    def __hash__(self):
        return hash(str(self))

    def __eq__(self, other):
        return str(self) == str(other)

label property

The name of the port, with its FMU, between single quotes: 'a.fmu/y'.

check_structural_parameter()

A structural parameter exposed on the container is set in Configuration Mode: it must be a scalar, and not give the dimension of an array (the container is built for the dimensions of the arrays).

Raises:

Type Description
FMUContainerError

If the structural parameter is an array or gives the dimension of a port.

Source code in fmu_manipulation_toolbox/container/rules.py
def check_structural_parameter(self):
    """A structural parameter exposed on the container is set in Configuration Mode: it must be a scalar, and
    not give the dimension of an array (the container is built for the dimensions of the arrays).

    Raises:
        FMUContainerError: If the structural parameter is an array or gives the dimension of a port.
    """
    if self.port.dimensions:
        raise FMUContainerError(f"Cannot expose {self}: an array structural parameter is not supported.")
    for port in self.fmu.ports.values():
        if ("valueReference", self.port.vr) in port.dimensions:
            raise FMUContainerError(f"Cannot expose {self}: it gives the dimension of '{port.name}'.")

is_exposable(role)

Whether the port can be exposed as role (INPUT, OUTPUT) of the container. Clocks and clocked variables cannot: the container has no clocked partition on its interface. Such a port is reported as an error and left out, the build goes on.

Source code in fmu_manipulation_toolbox/container/rules.py
def is_exposable(self, role: str) -> bool:
    """Whether the port can be exposed as `role` (INPUT, OUTPUT) of the container. Clocks and clocked variables
    cannot: the container has no clocked partition on its interface. Such a port is reported as an error and
    left out, the build goes on."""
    if self.port.is_clocked:
        logger.error(f"Cannot use {self} as {role} of the container: clocks and clocked variables cannot be "
                     f"exposed. It is not exposed.")
        return False
    return True

EmbeddedFMU

Bases: OperationAbstract

Represents an FMU loaded and analyzed for embedding inside a container.

Parses the modelDescription.xml of an FMU to extract its ports, capabilities, step size, platform support, and co-simulation metadata. Implements OperationAbstract to process the FMU descriptor via the visitor pattern.

Attributes:

Name Type Description
capability_list tuple[str, ...]

FMI capability flags tracked by the container.

fmu FMU

The underlying FMU object, closed once analysed (only its fmu_filename remains usable).

name str

Name of the embedded FMU: its filename (e.g. "model.fmu"), or the name of an instance of an FMU embedded several times (e.g. "model-1.fmu").

id str

Lowercase stem of the name, used as an identifier (e.g. "model-1").

is_instance bool

Whether the name differs from the filename: an instance of an FMU embedded several times, or another file with an already used filename.

terminals Terminals

FMI Terminals defined by this FMU.

ls LayeredStandard

LS-BUS layered standard information.

step_size float | None

Step size in seconds: the fixedInternalStepSize of an FMI-3 FMU, else the stepSize of its <DefaultExperiment>, or None.

fixed_internal_step_size bool

Whether step_size is the fixedInternalStepSize of an FMI-3 FMU.

start_time float | None

Default experiment start time.

stop_time float | None

Default experiment stop time.

model_identifier str | None

Co-simulation model identifier.

guid str | None

GUID (FMI-2) or instantiation token (FMI-3).

fmi_version int | None

FMI version (2 or 3).

platforms set[str]

Supported operating systems (e.g. {"Windows", "Linux"}).

ports dict[str, EmbeddedFMUPort]

Ports of the FMU, keyed by name.

has_event_mode bool

Whether the FMU supports event mode (FMI-3).

capabilities dict[str, str]

FMI capability flags and their values.

is_me bool

Whether the FMU is embedded in Model-Exchange mode. Co-Simulation takes precedence when both modes are provided.

number_of_continuous_states int

Number of continuous states (nx).

number_of_event_indicators int

Number of event indicators (nz).

Raises:

Type Description
FMUContainerError

If the FMU does not implement Co-Simulation mode.

Source code in fmu_manipulation_toolbox/container/embedded.py
class EmbeddedFMU(OperationAbstract):
    """Represents an FMU loaded and analyzed for embedding inside a container.

    Parses the `modelDescription.xml` of an FMU to extract its ports,
    capabilities, step size, platform support, and co-simulation metadata.
    Implements
    [OperationAbstract][fmu_manipulation_toolbox.operations.OperationAbstract]
    to process the FMU descriptor via the visitor pattern.

    Attributes:
        capability_list (tuple[str, ...]): FMI capability flags tracked by the container.
        fmu (FMU): The underlying
            [FMU][fmu_manipulation_toolbox.operations.FMU] object, closed once
            analysed (only its `fmu_filename` remains usable).
        name (str): Name of the embedded FMU: its filename (e.g. `"model.fmu"`), or the name of an instance of an
            FMU embedded several times (e.g. `"model-1.fmu"`).
        id (str): Lowercase stem of the name, used as an identifier (e.g. `"model-1"`).
        is_instance (bool): Whether the name differs from the filename: an instance of an FMU embedded several
            times, or another file with an already used filename.
        terminals (Terminals): FMI Terminals defined by this FMU.
        ls (LayeredStandard): LS-BUS layered standard information.
        step_size (float | None): Step size in seconds: the `fixedInternalStepSize` of an FMI-3 FMU, else the
            `stepSize` of its `<DefaultExperiment>`, or `None`.
        fixed_internal_step_size (bool): Whether `step_size` is the `fixedInternalStepSize` of an FMI-3 FMU.
        start_time (float | None): Default experiment start time.
        stop_time (float | None): Default experiment stop time.
        model_identifier (str | None): Co-simulation model identifier.
        guid (str | None): GUID (FMI-2) or instantiation token (FMI-3).
        fmi_version (int | None): FMI version (`2` or `3`).
        platforms (set[str]): Supported operating systems (e.g. `{"Windows", "Linux"}`).
        ports (dict[str, EmbeddedFMUPort]): Ports of the FMU, keyed by name.
        has_event_mode (bool): Whether the FMU supports event mode (FMI-3).
        capabilities (dict[str, str]): FMI capability flags and their values.
        is_me (bool): Whether the FMU is embedded in Model-Exchange mode.
            Co-Simulation takes precedence when both modes are provided.
        number_of_continuous_states (int): Number of continuous states (`nx`).
        number_of_event_indicators (int): Number of event indicators (`nz`).

    Raises:
        FMUContainerError: If the FMU does not implement Co-Simulation mode.
    """

    # The descriptor is only read: the container embeds the original archive.
    read_only = True

    capability_list = ("needsExecutionTool",
                       "canBeInstantiatedOnlyOncePerProcess",
                       "canHandleVariableCommunicationStepSize")

    def __init__(self, filename, name: str | None = None):
        self.fmu: FMU = FMU(filename)
        self.name = Path(name or filename).name
        self.id = Path(self.name).stem.lower()
        self.is_instance = self.name != Path(filename).name

        logger.debug(f"Analysing '{self.name}'.")
        self.terminals = Terminals(self.fmu.tmp_directory)
        self.ls = LayeredStandard(self.fmu.tmp_directory)

        self.step_size: float | None = None
        self.fixed_internal_step_size = False
        self.start_time: float | None = None
        self.stop_time: float | None = None
        self.model_identifier: str | None = None
        self.guid: str | None = None
        self.fmi_version: int | None = None
        self.is_me = False
        self.number_of_continuous_states = 0
        self.number_of_event_indicators = 0
        self.platforms: set[str] = set()
        self.ports: dict[str, EmbeddedFMUPort] = {}

        self.has_event_mode = False
        self.capabilities: dict[str, str] = {}
        self.current_port = None  # used during apply_operation()

        try:
            self.fmu.apply_operation(self)
        finally:
            # Only `fmu.fmu_filename` is used once analysed: remove the temporary directory now.
            self.fmu.close()
        if self.model_identifier is None:
            raise FMUContainerError(f"FMU '{self.name}' does not implement Co-Simulation mode.")
        if self.guid is None:
            raise FMUContainerError(f"FMU '{self.name}' has no "
                                    f"{'guid' if self.fmi_version == 2 else 'instantiationToken'}.")

        if self.fmi_version == 2:
            self._detect_array_aggregates()


    def _detect_array_aggregates(self):
        """Detect FMI-2 array elements notated as `basename[k]` (1D) or
        `basename[i,j,...]` (N-D, Modelica-style comma notation) and expose
        them as a virtual aggregated port named `basename`.

        The aggregate port carries `dimensions=[("start", N0), ("start", N1), ...]`
        and stores the underlying scalar element VRs in `element_vrs`, flattened
        in **row-major** order (last index varies fastest), matching the FMI-3
        array memory layout. This allows the aggregate to be connected to an
        FMI-3 array port of matching shape.
        """
        candidates = ArrayAggregate.detect_all(
            [p.name for p in self.ports.values()],
            existing_names=set(self.ports.keys()),
            log_prefix=self.name,
        )

        for agg in candidates:
            elements = [self.ports[n] for n in agg.ordered_element_names]
            first = elements[0]

            # All elements must share the same type/causality/variability/clock.
            if not all(p.type_name == first.type_name
                       and p.causality == first.causality
                       and p.variability == first.variability
                       and p.clock == first.clock
                       for p in elements):
                logger.debug(f"'{self.name}': array elements for '{agg.basename}' have "
                             f"heterogeneous attributes, aggregate not created.")
                continue

            aggregate = EmbeddedFMUPort(first.type_name, {
                "name": agg.basename,
                "valueReference": first.vr,   # informational; not used for I/O
                "causality": first.causality,
                "variability": first.variability if first.variability else "continuous",
                "description": f"FMI-2 array aggregate of {agg.size} elements '{agg.basename}[]'",
            })
            aggregate.dimensions = [("start", d) for d in agg.dims]
            aggregate.is_fmi2_aggregate = True
            aggregate.element_names = [p.name for p in elements]
            aggregate.element_vrs = [p.vr for p in elements]
            aggregate.clock = first.clock
            self.ports[agg.basename] = aggregate
            logger.debug(f"'{self.name}': aggregated FMI-2 array '{agg.basename}' "
                         f"(shape={agg.shape_str}, {agg.size} elements).")

    def fmi_attrs(self, attrs):
        fmi_version = attrs['fmiVersion']
        if fmi_version == "2.0":
            self.guid = attrs.get('guid')
            self.fmi_version = 2
        if fmi_version.startswith("3."):
            self.guid = attrs.get('instantiationToken')
            self.fmi_version = 3


    def cosimulation_attrs(self, attrs: dict[str, str]):
        # Co-Simulation takes precedence over Model-Exchange for dual-mode FMUs.
        self.is_me = False
        self.model_identifier = attrs['modelIdentifier']
        if attrs.get("hasEventMode", "false") == "true":
            self.has_event_mode = True
        for capability in self.capability_list:
            self.capabilities[capability] = attrs.get(capability, "false")
        if self.fmi_version == 3 and "fixedInternalStepSize" in attrs:
            try:
                self.step_size = float(attrs["fixedInternalStepSize"])
                self.fixed_internal_step_size = True
            except ValueError:
                logger.warning(f"FMU '{self.name}' declares an invalid fixedInternalStepSize "
                               f"('{attrs['fixedInternalStepSize']}'): ignored.")
        logger.debug(f"FMU '{self.name}' is embedded in Co-Simulation mode.")

    @property
    def imposes_step_size(self) -> bool:
        """Whether the container step must be a multiple of `step_size`: the FMU has a fixed internal step
        (FMI-3), or cannot handle a variable communication step size."""
        return self.fixed_internal_step_size or self.capabilities["canHandleVariableCommunicationStepSize"] == "false"

    def modelexchange_attrs(self, attrs):
        self.is_me = True
        self.model_identifier = attrs['modelIdentifier']
        for capability in self.capability_list:
            self.capabilities[capability] = attrs.get(capability, "false")
        logger.debug(f"FMU '{self.name}' provides Model-Exchange mode.")

    def experiment_attrs(self, attrs: dict[str, str]):
        if self.fixed_internal_step_size:
            logger.debug(f"FMU '{self.name}': fixedInternalStepSize={self.step_size}s takes precedence over "
                         f"stepSize={attrs.get('stepSize')}.")
        else:
            try:
                self.step_size = float(attrs['stepSize'])
            except KeyError:
                logger.warning(f"FMU '{self.name}' does not specify a preferred step size.")
        self.start_time = float(attrs.get("startTime", 0.0))
        self.stop_time = float(attrs.get("stopTime", self.start_time + 1.0))

    def port_attrs(self, fmu_port: ModelVariable):
        # Container will manage Enumeration as Integer
        fmi_type = enumeration_as_integer(fmu_port.fmi_type, self.fmi_version)
        port = EmbeddedFMUPort(fmi_type, fmu_port, fmi_version=self.fmi_version)
        self.ports[port.name] = port

    def closure(self):
        self.number_of_continuous_states, self.number_of_event_indicators = \
            self.model_description.model_exchange_sizes(self.name)

        try:
            for directory in (Path(self.fmu.tmp_directory) / "binaries").iterdir():
                if directory.is_dir() and str(directory.stem) in PLATFORM_OS:
                    self.platforms.add(PLATFORM_OS[str(directory.stem)])
        except FileNotFoundError:
            pass  # no binaries

    def __repr__(self):
        properties = f"{len(self.ports)} variables, ts={self.step_size}s"
        if len(self.terminals) > 0:
            properties += f", {len(self.terminals)} terminals"
        if len(self.ls) > 0:
            properties += f", {self.ls}"
        return f"'{self.name}' ({properties})"

imposes_step_size property

Whether the container step must be a multiple of step_size: the FMU has a fixed internal step (FMI-3), or cannot handle a variable communication step size.

EmbeddedFMUPort

Represents a port of an FMU embedded inside a container.

Handles the mapping between FMI-standard type names (e.g. Real, Float64) and internal container type names (e.g. real64), and generates the corresponding XML fragments for modelDescription.xml.

Attributes:

Name Type Description
FMI_TO_CONTAINER dict[int, dict[str, str]]

Mapping from FMI type names to container type names, keyed by FMI version (alias of container.types.FMI_TO_CONTAINER).

CONTAINER_TO_FMI dict[int, dict[str, str]]

Reverse mapping from container type names to FMI type names, keyed by FMI version (alias).

ALL_TYPES tuple[str, ...]

All container type names (alias).

causality str

Port causality ("input", "output", "local", "parameter").

variability str | None

Port variability ("continuous", "discrete", etc.).

name str

Port name.

vr int

Value reference in the original FMU.

type_name str

Container-internal type name (e.g. "real64").

start_value str | None

Start value, if defined.

initial str | None

Initial value attribute.

clock str | None

Clock reference for clocked ports.

description str | None

Human-readable description of the port.

is_reset bool

Whether the port is the virtual container.reset input of the FMU.

Source code in fmu_manipulation_toolbox/container/embedded.py
class EmbeddedFMUPort:
    """Represents a port of an FMU embedded inside a container.

    Handles the mapping between FMI-standard type names (e.g. `Real`, `Float64`)
    and internal container type names (e.g. `real64`), and generates the
    corresponding XML fragments for `modelDescription.xml`.

    Attributes:
        FMI_TO_CONTAINER (dict[int, dict[str, str]]): Mapping from FMI type names
            to container type names, keyed by FMI version (alias of
            `container.types.FMI_TO_CONTAINER`).
        CONTAINER_TO_FMI (dict[int, dict[str, str]]): Reverse mapping from container
            type names to FMI type names, keyed by FMI version (alias).
        ALL_TYPES (tuple[str, ...]): All container type names (alias).
        causality (str): Port causality (`"input"`, `"output"`, `"local"`,
            `"parameter"`).
        variability (str | None): Port variability (`"continuous"`, `"discrete"`, etc.).
        name (str): Port name.
        vr (int): Value reference in the original FMU.
        type_name (str): Container-internal type name (e.g. `"real64"`).
        start_value (str | None): Start value, if defined.
        initial (str | None): Initial value attribute.
        clock (str | None): Clock reference for clocked ports.
        description (str | None): Human-readable description of the port.
        is_reset (bool): Whether the port is the virtual `container.reset` input of the FMU.
    """

    # Aliases of the tables of `container.types`, kept for compatibility.
    FMI_TO_CONTAINER = FMI_TO_CONTAINER

    CONTAINER_TO_FMI = CONTAINER_TO_FMI

    ALL_TYPES = ALL_TYPES

    def __init__(self, fmi_type, attrs: ModelVariable | dict[str, Any], fmi_version=0):
        self.causality = attrs.get("causality", "local")
        self.variability = attrs.get("variability", None)
        self.interval_variability = attrs.get("intervalVariability", None)
        self.mime_type = attrs.get("mimeType", None)
        self.interval_decimal = attrs.get("intervalDecimal", None)
        self.shift_decimal = attrs.get("shiftDecimal", None)
        self.name = attrs["name"]
        self.vr = int(attrs["valueReference"])
        self.description = attrs.get("description", None)
        if isinstance(attrs, ModelVariable):
            self.dimensions = attrs.dimensions
        else:
            self.dimensions = []

        # For FMI-2 aggregated arrays: flag marking this port as a virtual
        # array built from scalar element ports (vs a native FMI-3 array port).
        # Used by `xml()` to prevent incorrectly exposing such an aggregate as a
        # container port in an FMI-2 container.
        self.is_fmi2_aggregate: bool = False
        # Names of the underlying scalar element ports (e.g. `basename[1]`, ...),
        # used to mark each individual scalar port as LINK when the aggregate is
        # connected, so the checker does not report them as unconnected.
        self.element_names: list[str] = []
        # Value references of these elements, in the order of the array (row-major): they need not be consecutive.
        self.element_vrs: list[int] = []
        # Virtual `container.reset` input added by the container (option `reset_ports`): it drives the reset of the
        # FMU and has no value reference in the FMU.
        self.is_reset: bool = False

        if fmi_version > 0:
            self.type_name = FMI_TO_CONTAINER[fmi_version][fmi_type]
        else:
            self.type_name = fmi_type

        self.start_value = attrs.get("start", None)
        self.initial = attrs.get("initial", None)
        self.clock = attrs.get("clocks", None)

    @property
    def vrs(self) -> list[int]:
        """Value references of the elements of an FMI-2 aggregate, else the value reference of the port."""
        return self.element_vrs if self.is_fmi2_aggregate else [self.vr]

    @property
    def is_clocked(self) -> bool:
        """A clock, or a variable of a clocked partition (attribute `clocks`)."""
        return self.type_name == "clock" or bool(self.clock)

    def size(self) -> int:
        size = 1
        for dimension in self.dimensions:
            if dimension[0] == "start":
                size *= dimension[1]
            else:
                raise FMUError(f"Port '{self.name}' depends on structuralParameter '{dimension[1]}' "
                               f"which is not supported.")
        return size

    def xml(self, vr: int, name=None, causality=None, start=None, fmi_version=2,
            type_name: str | None = None) -> ET.Element | None:
        """Generate the XML element for this port in `modelDescription.xml`.

        Produces a `<ScalarVariable>` element (FMI-2) or a typed element
        like `<Float64>` (FMI-3). Attribute values are escaped when the
        document is written.

        Args:
            vr (int): Value reference to use in the generated XML.
            name (str | None): Override port name. Defaults to `self.name`.
            causality (str | None): Override causality. Defaults to `self.causality`.
            start (str | None): Override start value. Defaults to `self.start_value`.
            fmi_version (int): FMI version (`2` or `3`).
            type_name (str | None): Container type of the variable, when it is exposed with another type than the
                one of the port (a boolean of the other FMI version). Defaults to `self.type_name`.

        Returns:
            ET.Element | None: The variable element, or `None` if the type is
                not compatible with the requested FMI version.
        """
        if name is None:
            name = self.name
        if causality is None:
            causality = self.causality
        if start is None:
            start = self.start_value
            if start is None and self.type_name == "binary" and self.initial == "exact":
                start = ""
        variability = self.variability
        if variability is None:
            if self.causality == "parameter":
                variability = "fixed"
            else:
                variability = "continuous" if "real" in self.type_name else "discrete"

        try:
            fmi_type = CONTAINER_TO_FMI[fmi_version][type_name or self.type_name]
        except KeyError:
            logger.error(f"Cannot expose the {causality} '{name}': its type '{type_name or self.type_name}' is not "
                         f"compatible with FMI-{fmi_version}.")
            return None

        if fmi_version == 2 and self.is_fmi2_aggregate:
            logger.error(f"Cannot expose FMI-2 array aggregate '{name}' in an FMI-2 container "
                         f"(use the scalar elements '{name}[k]' individually).")
            return None

        attrs = {
            "name": name,
            "valueReference": vr,
            "causality": causality,
            "variability": variability,
            # FMI-2 §2.2.7: an input has no `initial` (FMI-3 §2.4.7.4 allows `exact` only, its default).
            "initial": None if fmi_version == 2 and causality == "input" else self.initial,
            "description": self.description,
        }

        if fmi_version == 2:
            variable = self._element("ScalarVariable", attrs)
            variable.append(self._element(fmi_type, {"start": start}))
            return variable

        elif fmi_version == 3:
            if self.dimensions or fmi_type in ('String', 'Binary'):
                variable = self._element(fmi_type, attrs)
                for dimension in self.dimensions:
                    variable.append(self._element("Dimension", {dimension[0]: dimension[1]}))
                if start is not None:
                    variable.append(self._element("Start", {"value": start}))
            else:
                variable = self._element(fmi_type, {**attrs, "start": start,
                                                    "intervalVariability": self.interval_variability})
            return variable

        else:
            logger.critical(f"Unknown FMI version {fmi_version}.")
            return None

    @staticmethod
    def _element(tag: str, attrs: dict[str, Any]) -> ET.Element:
        """Element with the attributes whose value is not `None`, converted to strings."""
        return ET.Element(tag, {key: str(value) for key, value in attrs.items() if value is not None})

is_clocked property

A clock, or a variable of a clocked partition (attribute clocks).

vrs property

Value references of the elements of an FMI-2 aggregate, else the value reference of the port.

xml(vr, name=None, causality=None, start=None, fmi_version=2, type_name=None)

Generate the XML element for this port in modelDescription.xml.

Produces a <ScalarVariable> element (FMI-2) or a typed element like <Float64> (FMI-3). Attribute values are escaped when the document is written.

Parameters:

Name Type Description Default
vr int

Value reference to use in the generated XML.

required
name str | None

Override port name. Defaults to self.name.

None
causality str | None

Override causality. Defaults to self.causality.

None
start str | None

Override start value. Defaults to self.start_value.

None
fmi_version int

FMI version (2 or 3).

2
type_name str | None

Container type of the variable, when it is exposed with another type than the one of the port (a boolean of the other FMI version). Defaults to self.type_name.

None

Returns:

Type Description
Element | None

ET.Element | None: The variable element, or None if the type is not compatible with the requested FMI version.

Source code in fmu_manipulation_toolbox/container/embedded.py
def xml(self, vr: int, name=None, causality=None, start=None, fmi_version=2,
        type_name: str | None = None) -> ET.Element | None:
    """Generate the XML element for this port in `modelDescription.xml`.

    Produces a `<ScalarVariable>` element (FMI-2) or a typed element
    like `<Float64>` (FMI-3). Attribute values are escaped when the
    document is written.

    Args:
        vr (int): Value reference to use in the generated XML.
        name (str | None): Override port name. Defaults to `self.name`.
        causality (str | None): Override causality. Defaults to `self.causality`.
        start (str | None): Override start value. Defaults to `self.start_value`.
        fmi_version (int): FMI version (`2` or `3`).
        type_name (str | None): Container type of the variable, when it is exposed with another type than the
            one of the port (a boolean of the other FMI version). Defaults to `self.type_name`.

    Returns:
        ET.Element | None: The variable element, or `None` if the type is
            not compatible with the requested FMI version.
    """
    if name is None:
        name = self.name
    if causality is None:
        causality = self.causality
    if start is None:
        start = self.start_value
        if start is None and self.type_name == "binary" and self.initial == "exact":
            start = ""
    variability = self.variability
    if variability is None:
        if self.causality == "parameter":
            variability = "fixed"
        else:
            variability = "continuous" if "real" in self.type_name else "discrete"

    try:
        fmi_type = CONTAINER_TO_FMI[fmi_version][type_name or self.type_name]
    except KeyError:
        logger.error(f"Cannot expose the {causality} '{name}': its type '{type_name or self.type_name}' is not "
                     f"compatible with FMI-{fmi_version}.")
        return None

    if fmi_version == 2 and self.is_fmi2_aggregate:
        logger.error(f"Cannot expose FMI-2 array aggregate '{name}' in an FMI-2 container "
                     f"(use the scalar elements '{name}[k]' individually).")
        return None

    attrs = {
        "name": name,
        "valueReference": vr,
        "causality": causality,
        "variability": variability,
        # FMI-2 §2.2.7: an input has no `initial` (FMI-3 §2.4.7.4 allows `exact` only, its default).
        "initial": None if fmi_version == 2 and causality == "input" else self.initial,
        "description": self.description,
    }

    if fmi_version == 2:
        variable = self._element("ScalarVariable", attrs)
        variable.append(self._element(fmi_type, {"start": start}))
        return variable

    elif fmi_version == 3:
        if self.dimensions or fmi_type in ('String', 'Binary'):
            variable = self._element(fmi_type, attrs)
            for dimension in self.dimensions:
                variable.append(self._element("Dimension", {dimension[0]: dimension[1]}))
            if start is not None:
                variable.append(self._element("Start", {"value": start}))
        else:
            variable = self._element(fmi_type, {**attrs, "start": start,
                                                "intervalVariability": self.interval_variability})
        return variable

    else:
        logger.critical(f"Unknown FMI version {fmi_version}.")
        return None

FMUContainer

Builds an FMU Container that embeds multiple FMUs into a single FMU.

An FMUContainer acts as both an FMI co-simulation FMU and an FMI importer. It loads embedded FMUs, wires their ports together, and generates the modelDescription.xml, the runtime configuration (container.txt), and the final .fmu archive.

Examples:

from pathlib import Path
from fmu_manipulation_toolbox.container import FMUContainer

container = FMUContainer("bouncing", Path("fmus"), fmi_version=2)
container.get_fmu("bb_position.fmu")
container.get_fmu("bb_velocity.fmu")
container.add_link("bb_position.fmu", "is_ground",
                   "bb_velocity.fmu", "reset")
container.add_implicit_rule(auto_input=True, auto_output=True)
container.make_fmu("bouncing.fmu", step_size=0.1)

Attributes:

Name Type Description
fmu_directory Path

Directory containing the source FMUs.

identifier str

Model identifier for the container.

fmi_version int

FMI version of the container interface (2 or 3).

involved_fmu OrderedDict[str, EmbeddedFMU]

Embedded FMUs, keyed by filename, in insertion order.

inputs dict[str, ContainerInput]

Container input ports, keyed by exposed name.

outputs dict[str, ContainerPort]

Container output ports, keyed by exposed name.

links dict[ContainerPort, Link]

Internal links between embedded FMUs.

start_values dict[ContainerPort, str]

Start values for embedded FMU ports.

start_time float | None

Start time of the default experiment; None to take the one of the first embedded FMU.

stop_time float | None

Stop time of the default experiment; None to take the one of the first embedded FMU.

Raises:

Type Description
FMUContainerError

If the FMU directory is invalid.

Source code in fmu_manipulation_toolbox/container/builder.py
  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
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 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
 267
 268
 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
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 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
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
class FMUContainer:
    """Builds an FMU Container that embeds multiple FMUs into a single FMU.

    An `FMUContainer` acts as both an FMI co-simulation FMU and an FMI importer.
    It loads embedded FMUs, wires their ports together, and generates the
    `modelDescription.xml`, the runtime configuration (`container.txt`), and the
    final `.fmu` archive.

    Examples:
        ```python
        from pathlib import Path
        from fmu_manipulation_toolbox.container import FMUContainer

        container = FMUContainer("bouncing", Path("fmus"), fmi_version=2)
        container.get_fmu("bb_position.fmu")
        container.get_fmu("bb_velocity.fmu")
        container.add_link("bb_position.fmu", "is_ground",
                           "bb_velocity.fmu", "reset")
        container.add_implicit_rule(auto_input=True, auto_output=True)
        container.make_fmu("bouncing.fmu", step_size=0.1)
        ```

    Attributes:
        fmu_directory (Path): Directory containing the source FMUs.
        identifier (str): Model identifier for the container.
        fmi_version (int): FMI version of the container interface (`2` or `3`).
        involved_fmu (OrderedDict[str, EmbeddedFMU]): Embedded FMUs, keyed
            by filename, in insertion order.
        inputs (dict[str, ContainerInput]): Container input ports, keyed by
            exposed name.
        outputs (dict[str, ContainerPort]): Container output ports, keyed by
            exposed name.
        links (dict[ContainerPort, Link]): Internal links between embedded FMUs.
        start_values (dict[ContainerPort, str]): Start values for embedded FMU ports.
        start_time (float | None): Start time of the default experiment; `None` to take
            the one of the first embedded FMU.
        stop_time (float | None): Stop time of the default experiment; `None` to take
            the one of the first embedded FMU.

    Raises:
        FMUContainerError: If the FMU directory is invalid.
    """

    #: Name of the virtual input added to each embedded FMU by the option `reset_ports`.
    RESET_PORT = "container.reset"

    def __init__(self, identifier: str, fmu_directory: str | Path, description_pathname=None, fmi_version=2,
                 reset_ports=False):
        self.fmu_directory = Path(fmu_directory)
        self.identifier = identifier
        if not self.fmu_directory.is_dir():
            raise FMUContainerError(f"'{self.fmu_directory}' is not a valid directory.")
        self.involved_fmu = InvolvedFMU()

        self.description_pathname = description_pathname
        self.fmi_version = fmi_version
        self.reset_ports = reset_ports

        self.start_time: float | None = None
        self.stop_time: float | None = None

        self.have_me = False

        # Rules
        self.inputs: dict[str, ContainerInput] = {}
        self.outputs: dict[str, ContainerPort] = {}
        self.links: dict[ContainerPort, Link] = {}

        self.rules: dict[ContainerPort, str] = {}
        self.start_values: dict[ContainerPort, str] = {}
        self.terminal_parameters: list[tuple[ContainerPort, ContainerPort]] = []
        # What feeds each input of the embedded FMUs: a container input or a link, never both, never two (B6).
        self.input_feeders: dict[ContainerPort, str] = {}

    def get_fmu(self, fmu_filename: str, name: str | None = None) -> EmbeddedFMU:
        """Load an embedded FMU from the FMU directory.

        An embedded FMU is designated by its name: its filename, or the name of an instance when the same FMU is
        embedded several times. Each instance is a distinct embedded FMU, extracted in its own directory of the
        container. If the FMU has already been loaded, returns the cached instance.

        Args:
            fmu_filename (str): Filename of the FMU (e.g. `"model.fmu"`).
            name (str | None): Name of the instance (e.g. `"model-1.fmu"`). Defaults to the filename. Once loaded,
                the instance is designated by this name in every rule.

        Returns:
            EmbeddedFMU: The loaded and analysed FMU.

        Raises:
            FMUContainerError: If the FMU cannot be loaded, or if `name` already designates another file.
        """
        fmu_name = Path(name or fmu_filename).name
        if fmu_name in self.involved_fmu:
            fmu = self.involved_fmu[fmu_name]
            if name is not None:  # a rule designates the FMU by name only: no file to compare with
                loaded_from = Path(fmu.fmu.fmu_filename).resolve()
                if loaded_from != (self.fmu_directory / fmu_filename).resolve():
                    raise FMUContainerError(f"'{fmu_name}' already designates '{fmu.fmu.fmu_filename}': "
                                            f"it cannot also designate '{fmu_filename}'.")
            return fmu

        try:
            fmu = EmbeddedFMU(self.fmu_directory / fmu_filename, name=fmu_name)
        except (FMUContainerError, FMUError) as e:
            raise FMUContainerError(f"Cannot load '{fmu_filename}': {e}") from e

        if not fmu.fmi_version == self.fmi_version:
            logger.warning(f"FMU '{fmu.name}' (FMI-{fmu.fmi_version}) is embedded in an FMI-{self.fmi_version} "
                           f"container.")
        if self.reset_ports:
            self.add_reset_port(fmu)
        self.involved_fmu[fmu.name] = fmu

        if fmu.is_me:
            fmu_type = "ME"
            self.have_me = True
        else:
            fmu_type = "CS"

        logger.info(f"Involved FMU #{len(self.involved_fmu)}: {fmu}, {fmu_type}.")

        return fmu

    def add_reset_port(self, fmu: EmbeddedFMU):
        """Add the virtual `container.reset` input to an embedded FMU (option `reset_ports`).

        When this input is `true` at the start of an internal step, the container resets the FMU and initializes it
        again at the current time; the input goes back to `false` at the end of the step. Its type is the Boolean
        of the container (`fmi2Boolean` or `fmi3Boolean`).

        Args:
            fmu (EmbeddedFMU): The embedded FMU.

        Raises:
            FMUContainerError: If the FMU already has a port named `container.reset`.
        """
        if self.RESET_PORT in fmu.ports:
            raise FMUContainerError(f"FMU '{fmu.name}' has a port named '{self.RESET_PORT}': it cannot be embedded "
                                    f"with the option reset_ports, which reserves this name.")
        port = EmbeddedFMUPort("boolean" if self.fmi_version == 2 else "boolean1", {
            "name": self.RESET_PORT,
            "valueReference": -1,   # no value reference in the FMU
            "causality": "input",
            "variability": "discrete",
            "start": "false",
            "description": f"Reset of the embedded FMU '{fmu.name}'",
        })
        port.is_reset = True
        fmu.ports[self.RESET_PORT] = port

    def reset_input_name(self, fmu: EmbeddedFMU) -> str:
        """Name under which the container exposes the `container.reset` input of `fmu`."""
        return f"container.{fmu.id}.reset"

    def _default_reset_input_name(self, fmu: EmbeddedFMU) -> str:
        """`reset_input_name`, for an exposure without explicit name (`auto_input`, or `add_input` with an empty
        name): an input or an output of the container may already have this name (e.g. an input of a sub-container
        exposed by `auto_input`), and the reset must not be merged into it.

        Raises:
            FMUContainerError: If the name is already used by the container.
        """
        name = self.reset_input_name(fmu)
        if name in self.inputs or name in self.outputs:
            raise FMUContainerError(f"Cannot expose the reset of FMU '{fmu.name}' as '{name}': the container already "
                                    f"has a variable of this name.")
        return name

    def mark_ruled(self, cport: ContainerPort, rule: str):
        if cport in self.rules:
            previous_rule = self.rules[cport]
            if rule not in ("OUTPUT", "LINK") and previous_rule not in ("OUTPUT", "LINK"):
                raise FMUContainerError(f"{cport} is already used as {previous_rule.lower()}: it cannot also be used "
                                        f"as {rule.lower()}.")

        self.rules[cport] = rule

    def check_not_fed(self, cport: ContainerPort, feeder: str):
        """Refuse a second feeder (container input or link) for an input of an embedded FMU.

        Clocks are excepted: LS-BUS connects input clocks together.

        Raises:
            FMUContainerError: If the input is already fed.
        """
        if cport.port.type_name != "clock" and cport in self.input_feeders:
            raise FMUContainerError(f"{cport} is already fed by {self.input_feeders[cport]}: "
                                    f"it cannot also be fed by {feeder}.")

    def get_all_cports(self):
        cport_list = []
        for fmu in self.involved_fmu.values():
            for port_name in fmu.ports:
                try:
                    cport = ContainerPort(fmu, port_name)
                    cport_list.append(cport)
                except FMUContainerError:
                    pass

        return cport_list

    def add_input(self, container_port_name: str, to_fmu_filename: str, to_port_name: str):
        """Expose a port of an embedded FMU as a container input.

        Multiple embedded FMU ports can be connected to the same container
        input (fan-out), provided they share the same type and causality.

        Args:
            container_port_name (str): Exposed name on the container. If empty,
                defaults to `to_port_name`, or `container.<id>.reset` for the
                `container.reset` port (refused when that name is already used).
            to_fmu_filename (str): Filename of the embedded FMU.
            to_port_name (str): Name of the input port on the embedded FMU.

        Raises:
            FMUContainerError: If the FMU or the port does not exist, if the port
                causality is not `"input"`, `"parameter"` or `"structuralParameter"` (a scalar that gives no
                dimension), or if types do not match an existing input with the same name.
        """
        try:
            cport_to = ContainerPort(self.get_fmu(to_fmu_filename), to_port_name)
        except FMUContainerError as e:
            raise FMUContainerError(f"Cannot add input '{container_port_name or to_port_name}': {e.reason}") from e

        if not container_port_name:
            container_port_name = self._default_reset_input_name(cport_to.fmu) if cport_to.port.is_reset \
                else to_port_name

        if cport_to.port.causality not in ("input", "parameter", "structuralParameter"):  # check causality
            raise FMUContainerError(f"Cannot use {cport_to} as an input of the container: its causality is "
                                    f"'{cport_to.port.causality}'.")
        if not cport_to.is_exposable("INPUT"):
            return
        if cport_to.port.causality == "structuralParameter":
            cport_to.check_structural_parameter()

        feeder = f"the container input '{container_port_name}'"
        self.check_not_fed(cport_to, feeder)
        try:
            input_port = self.inputs[container_port_name]
            input_port.add_cport(cport_to)
        except KeyError:
            self.inputs[container_port_name] = ContainerInput(container_port_name, cport_to)
        self.input_feeders[cport_to] = feeder

        logger.debug(f"{cport_to} is an input of the container.")
        self.mark_ruled(cport_to, 'INPUT')

    def add_output(self, from_fmu_filename: str, from_port_name: str, container_port_name: str):
        """Expose a port of an embedded FMU as a container output.

        Args:
            from_fmu_filename (str): Filename of the embedded FMU.
            from_port_name (str): Name of the output port on the embedded FMU.
            container_port_name (str): Exposed name on the container. If empty,
                defaults to `from_port_name`.

        Raises:
            FMUContainerError: If the FMU or the port does not exist, if the port
                causality is not `"output"` or `"local"`, or if the exposed name is
                already used.
        """
        if not container_port_name:  # empty is allowed
            container_port_name = from_port_name

        try:
            cport_from = ContainerPort(self.get_fmu(from_fmu_filename), from_port_name)
        except FMUContainerError as e:
            raise FMUContainerError(f"Cannot add output '{container_port_name}': {e.reason}") from e

        if cport_from.port.causality not in ("output", "local"):  # check causality
            raise FMUContainerError(f"Cannot use {cport_from} as an output of the container: its causality is "
                                    f"'{cport_from.port.causality}'.")
        if not cport_from.is_exposable("OUTPUT"):
            return

        if container_port_name in self.outputs:
            raise FMUContainerError(f"The output '{container_port_name}' of the container is already connected to "
                                    f"port {self.outputs[container_port_name].label}.")

        logger.debug(f"{cport_from} is an output of the container.")
        self.mark_ruled(cport_from, 'OUTPUT')
        self.outputs[container_port_name] = cport_from

    def drop_port(self, from_fmu_filename: str, from_port_name: str):
        """Explicitly ignore an output port of an embedded FMU.

        Prevents the port from being auto-exposed or flagged as unconnected.

        Args:
            from_fmu_filename (str): Filename of the embedded FMU.
            from_port_name (str): Name of the output port to drop.

        Raises:
            FMUContainerError: If the FMU or the port does not exist, or if the
                port causality is not `"output"`.
        """

        try:
            cport_from = ContainerPort(self.get_fmu(from_fmu_filename), from_port_name)
        except FMUContainerError as e:
            raise FMUContainerError(f"Cannot drop port: {e.reason}") from e

        if not cport_from.port.causality == "output":  # check causality
            raise FMUContainerError(f"Cannot drop {cport_from}: its causality is '{cport_from.port.causality}', not "
                                    f"'output'.")

        logger.debug(f"{cport_from} is dropped.")
        self.mark_ruled(cport_from, 'DROP')

    def add_link(self, from_fmu_filename: str, from_port_name: str, to_fmu_filename: str, to_port_name: str):
        """Connect an output of one embedded FMU to an input of another.

        If both port names match FMI Terminal definitions, a terminal-level
        connection is made (connecting all member ports). Otherwise, a regular
        port-to-port link is created.

        Args:
            from_fmu_filename (str): Filename of the source FMU.
            from_port_name (str): Output port name (or terminal name).
            to_fmu_filename (str): Filename of the destination FMU.
            to_port_name (str): Input port name (or terminal name).

        Raises:
            FMUContainerError: If an FMU or a port does not exist, if port
                causalities are invalid or types
                are incompatible.
        """
        fmu_from = self.get_fmu(from_fmu_filename)
        fmu_to = self.get_fmu(to_fmu_filename)

        if from_port_name in fmu_from.terminals and to_port_name in fmu_to.terminals:
            # TERMINAL Connection
            terminal1 = fmu_from.terminals[from_port_name]
            terminal2 = fmu_to.terminals[to_port_name]
            if terminal1 == terminal2:
                logger.debug(f"Plugging the terminals '{terminal1.path}' and '{terminal2.path}'.")
                try:
                    links = terminal1.connect(terminal2)
                except TerminalError as e:
                    raise FMUContainerError(f"Cannot plug the terminals of '{fmu_from.name}' and '{fmu_to.name}': "
                                            f"{e}") from e
                for terminal1_port_name, terminal2_port_name in links:
                    self.add_link_regular(fmu_from, terminal1_port_name, fmu_to, terminal2_port_name)
                for terminal1_port_name, terminal2_port_name in terminal1.connected_parameters(terminal2):
                    self.terminal_parameters.append((ContainerPort(fmu_from, terminal1_port_name),
                                                     ContainerPort(fmu_to, terminal2_port_name)))
            else:
                logger.error(f"Cannot plug the incompatible terminals '{terminal1.path}' and '{terminal2.path}'.")
        else:
            # REGULAR port connection
            try:
                self.add_link_regular(fmu_from, from_port_name, fmu_to, to_port_name)
            except FMUContainerError as e:
                paths = fmu_from.terminals.paths_of(from_port_name) + fmu_to.terminals.paths_of(to_port_name)
                if paths:
                    raise FMUContainerError(f"{e.reason} A nested terminal is designated by its full path: "
                                            f"{', '.join(paths)}.") from e
                raise

    def add_link_regular(self, fmu_from: EmbeddedFMU, from_port_name: str, fmu_to: EmbeddedFMU, to_port_name: str):

        try:
            cport_from = ContainerPort(fmu_from, from_port_name)
            cport_to = ContainerPort(fmu_to, to_port_name)
        except FMUContainerError as e:
            raise FMUContainerError(f"Cannot link '{from_port_name}' to '{to_port_name}': {e.reason}") from e

        if cport_to.port.causality == "output" and cport_from.port.causality == "input":
            logger.debug("Link orientation inverted.")
            tmp = cport_to
            cport_to = cport_from
            cport_from = tmp

        feeder = f"a link from port {cport_from.label}"
        self.check_not_fed(cport_to, feeder)
        try:
            local = self.links[cport_from]
        except KeyError:
            local = Link(cport_from)
            self.links[cport_from] = local

        local.add_target(cport_to)  # Causality is check in the add() function
        self.input_feeders[cport_to] = feeder

        logger.debug(f"Link: {cport_from.label} → {cport_to.label}.")
        self.mark_ruled(cport_from, 'LINK')
        self.mark_ruled(cport_to, 'LINK')

        # If either side is an FMI-2 array aggregate, also mark each
        # underlying scalar element port as LINK so it is not reported
        # as unconnected.
        for cport in (cport_from, cport_to):
            for elt_name in cport.port.element_names:
                try:
                    self.mark_ruled(ContainerPort(cport.fmu, elt_name), 'LINK')
                except FMUContainerError:
                    pass

    def add_start_value(self, fmu_filename: str, port_name: str, value: str):
        """Set a start value for a port of an embedded FMU.

        The value is automatically converted to the appropriate type
        (float, int, bool, or string).

        Args:
            fmu_filename (str): Filename of the embedded FMU.
            port_name (str): Name of the port.
            value (str): Start value as a string (a Python `bool`, e.g. a JSON `true`, is accepted for a
                Boolean port).

        Raises:
            FMUContainerError: If the FMU or the port does not exist, if the port
                type has no start value (binary, clock), or if the value cannot be
                converted to the port's type.
        """

        try:
            cport = ContainerPort(self.get_fmu(fmu_filename), port_name)
        except FMUContainerError as e:
            raise FMUContainerError(f"Cannot set start value: {e.reason}") from e

        if cport.port.is_reset:
            raise FMUContainerError(f"Start value cannot be set on {cport}: it drives the reset of the FMU.")

        self.start_values[cport] = self.start_value_text(cport, value)

    @staticmethod
    def start_value_text(cport: ContainerPort, value) -> str:
        """The start value `value` of `cport`, checked and formatted for `container.txt`.

        Raises:
            FMUContainerError: If the port type has no start value (binary, clock), or if the value cannot be
                converted to the port's type.
        """
        if isinstance(value, bool):     # JSON true/false: str() would give 'True'/'False'
            value = "true" if value else "false"

        # Check dimensions
        value_tokens = str(value).split(' ')
        if not len(value_tokens) == cport.port.size():
            raise FMUContainerError(f"The start value of {cport} does not match its dimension "
                                    f"{cport.port.size()}.")

        # Check type
        for token in value_tokens:
            try:
                if cport.port.type_name.startswith('real'):
                    float(token)
                elif cport.port.type_name.startswith('integer') or  cport.port.type_name.startswith('uinteger'):
                    int(token)
                elif cport.port.type_name.startswith('boolean'):
                    if token not in ("true", "false", "0", "1"):
                        raise ValueError(f"Invalid boolean value: '{token}'")
                elif cport.port.type_name == 'string':
                    pass
                else:
                    raise FMUContainerError(f"Start value cannot be set on {cport} of type '{cport.port.type_name}'.")
            except ValueError:
                raise FMUContainerError(f"Start value of {cport} is not conforming to the format of "
                                        f"'{cport.port.type_name}'.") from None

        # Format is different for string
        if cport.port.type_name == 'string':
            value = "\n" + "\n".join(value_tokens)

        return value

    def apply_terminal_parameters(self):
        """Give to the parameters of Configuration terminals the value of the connected Bus Simulation.

        These variables are parameters: they cannot be linked. The value is propagated when it is known at build
        time, unless the user has set a start value.
        """
        for cport1, cport2 in self.terminal_parameters:
            if cport1.port.causality == "parameter" and cport2.port.causality != "parameter":
                target, source = cport1, cport2
            elif cport2.port.causality == "parameter" and cport1.port.causality != "parameter":
                target, source = cport2, cport1
            else:
                logger.debug(f"No value to propagate between {cport1} and port {cport2.label}.")
                continue

            if target in self.start_values:
                logger.debug(f"The start value of {target} is kept: port {source.label} is not propagated.")
            elif source.port.start_value is None:
                logger.warning(f"The value of {source} is known at runtime only: it is not propagated to port "
                               f"{target.label}.")
            else:
                logger.info(f"The start value of {target} is taken from port {source.label}: "
                            f"{source.port.start_value}.")
                self.add_start_value(target.fmu.name, target.port.name, source.port.start_value)

    def find_inputs(self, port_to_connect: EmbeddedFMUPort) -> list[ContainerPort]:
        candidates = []
        for cport in self.get_all_cports():
            if (cport.port.causality == 'input' and cport not in self.rules and cport.port.name == port_to_connect.name
                    and cport.port.type_name == port_to_connect.type_name):
                candidates.append(cport)
        return candidates

    def add_implicit_rule(self, auto_input=True, auto_output=True, auto_link=True, auto_parameter=False,
                          auto_local=False) -> AutoWired:
        """Automatically wire unconnected ports of embedded FMUs.

        Processes all ports in the following order:

        1. **auto_link**: Connect outputs to inputs with matching names and types.
        2. **auto_output**: Expose remaining unconnected outputs.
        3. **auto_local**: Expose local variables.
        4. **auto_input**: Expose remaining unconnected inputs.
        5. **auto_parameter**: Expose parameters.
        6. Always: expose the variables that configure the XCP services of the embedded FMUs (FMI-LS-XCP), as
           `<fmu id>.<variable>`.

        Args:
            auto_input (bool): Expose unconnected input ports.
            auto_output (bool): Expose unconnected output ports.
            auto_link (bool): Link matching output/input ports automatically.
            auto_parameter (bool): Expose parameter ports.
            auto_local (bool): Expose local variables.

        Returns:
            AutoWired: Record of all automatically created rules.
        """
        auto_wired = AutoWired()
        all_cports = self.get_all_cports()
        # Candidates of the auto-links, by (name, type), in the order of `all_cports`: same result as `find_inputs`,
        # without going through every port for each output.
        inputs_by_signature: dict[tuple[str, str], list[ContainerPort]] = defaultdict(list)
        for cport in all_cports:
            if cport.port.causality == 'input':
                inputs_by_signature[(cport.port.name, cport.port.type_name)].append(cport)

        # Auto Link outputs. The instances of an FMU share its port names: they are never auto-linked, otherwise an
        # output would feed the inputs of every instance.
        for cport in all_cports:
            if cport.port.causality == 'output':
                candidates_cport_list = [candidate for candidate in
                                         inputs_by_signature[(cport.port.name, cport.port.type_name)]
                                         if candidate not in self.rules and not candidate.fmu.is_instance]
                if auto_link and candidates_cport_list and not cport.fmu.is_instance:
                    for candidate_cport in candidates_cport_list:
                        logger.info(f"Auto link: {cport.label} → {candidate_cport.label}.")
                        self.add_link(cport.fmu.name, cport.port.name,
                                      candidate_cport.fmu.name, candidate_cport.port.name)
                        auto_wired.add_link(cport.fmu.name, cport.port.name,
                                            candidate_cport.fmu.name, candidate_cport.port.name)
                elif auto_output and cport not in self.rules and cport.port.is_clocked:
                    logger.warning(f"Auto output: port {cport.label} is not exposed: clocks and clocked variables "
                                   f"cannot be "
                                   f"exposed.")
                elif auto_output and cport not in self.rules:
                    output_name = self._auto_name(cport)
                    logger.info(f"Auto output: port {cport.label} exposed as '{output_name}'.")
                    self.add_output(cport.fmu.name, cport.port.name, output_name)
                    auto_wired.add_output(cport.fmu.name, cport.port.name, output_name)
            elif cport.port.causality == 'local':
                local_portname = None
                if cport.port.name.startswith("container."):
                    local_portname = "container." + cport.fmu.id + "." + cport.port.name[10:]
                    logger.info(f"Profiling: port {cport.label} exposed.")
                elif auto_local and cport.port.is_clocked:
                    logger.debug(f"Auto local: port {cport.label} is not exposed: clocks and clocked variables cannot "
                                 f"be exposed.")
                elif auto_local:
                    local_portname = cport.fmu.id + "." + cport.port.name
                    logger.info(f"Auto local: port {cport.label} exposed as '{local_portname}'.")
                if local_portname:
                    self.add_output(cport.fmu.name, cport.port.name, local_portname)
                    auto_wired.add_output(cport.fmu.name, cport.port.name, local_portname)

        # Auto link inputs
        for cport in all_cports:
            if cport not in self.rules:
                if auto_parameter and cport.port.causality == 'parameter':
                    parameter_name = cport.fmu.id + "." + cport.port.name
                    logger.info(f"Auto parameter: port {cport.label} exposed as '{parameter_name}'.")
                    self.add_input(parameter_name, cport.fmu.name, cport.port.name)
                    auto_wired.add_parameter(parameter_name, cport.fmu.name, cport.port.name)
                elif auto_input and cport.port.causality == 'input' and cport.port.type_name == "clock" \
                        and cport.port.interval_variability in TIME_BASED_CLOCKS:
                    logger.info(f"Auto input: port {cport.label} is not exposed (a clock cannot be): the container "
                                f"schedules it.")
                elif auto_input and cport.port.causality == 'input' and cport.port.is_clocked:
                    logger.warning(f"Auto input: port {cport.label} is not exposed: clocks and clocked variables "
                                   f"cannot be "
                                   f"exposed.")
                elif auto_input and cport.port.causality == 'input' :
                    input_name = self._default_reset_input_name(cport.fmu) if cport.port.is_reset \
                        else self._auto_name(cport)
                    logger.info(f"Auto input: port {cport.label} exposed as '{input_name}'.")
                    self.add_input(input_name, cport.fmu.name, cport.port.name)
                    auto_wired.add_input(input_name, cport.fmu.name, cport.port.name)

        # FMI-LS-XCP: the variables that configure the XCP services of the embedded FMUs, whatever the options
        xcp.expose_variables(self, auto_wired)

        logger.info(f"Automatic wiring: {auto_wired}")

        return auto_wired

    def _auto_name(self, cport: ContainerPort) -> str:
        """Name under which `auto_input` / `auto_output` expose `cport`: its port name, or `<id>.<port>` when the
        port name is already exposed, as an input or as an output (the instances of an FMU share its port names,
        and the variables of the container need distinct names)."""
        if cport.port.name in self.inputs or cport.port.name in self.outputs:
            return f"{cport.fmu.id}.{cport.port.name}"
        return cport.port.name

    def default_step_size(self) -> float:
        """Compute the default step size from embedded FMUs.

        The step size is the least common multiple of the step sizes of the FMUs that
        impose their step (`fixedInternalStepSize` of FMI-3, or no variable step size),
        computed exactly (`0.1` and `0.25` give `0.5`). Otherwise, returns the largest step size.
        FMUs without step size are ignored; without any step size, the default is 0.1 s.

        Returns:
            float: Computed step size in seconds.
        """
        step_sizes = {fmu.name: fmu.step_size for fmu in self.involved_fmu.values() if fmu.step_size}
        for name, step_size in list(step_sizes.items()):
            if step_size < 0:
                logger.warning(f"FMU '{name}' declares a negative step size ({step_size}s): ignored.")
                del step_sizes[name]

        step_size = deduce_step_size([
            (step_sizes[fmu.name], not fmu.imposes_step_size)
            for fmu in self.involved_fmu.values() if fmu.name in step_sizes])
        if step_size is not None:
            return step_size

        logger.warning(f"Defaulting to the step size {DEFAULT_STEP_SIZE}s.")
        return DEFAULT_STEP_SIZE

    def scheduled_clock_links(self) -> list[Link]:
        """Links of the time-based input clocks that are neither linked nor exposed (a clock cannot be exposed).

        Each one gets a link without source, like input clocks linked together: the container schedules it from its
        interval and shift. Built again at each build, the rules are not modified.
        """
        links = []
        for fmu in self.involved_fmu.values():
            for port_name, fmu_port in fmu.ports.items():
                if fmu_port.type_name == "clock" and fmu_port.causality == "input" \
                        and fmu_port.interval_variability in TIME_BASED_CLOCKS:
                    cport = ContainerPort(fmu, port_name)
                    if cport not in self.rules:
                        links.append(Link(cport))
        return links

    def sanity_check(self, step_size: float):
        """Validate the container configuration before building.

        Warns about step size mismatches and unconnected ports.

        Args:
            step_size (float): The container's internal step size.
        """
        for fmu in self.involved_fmu.values():
            if fmu.step_size and fmu.imposes_step_size:
                ts_ratio = _exact(step_size) / _exact(fmu.step_size)   # exact: 0.3 / 0.1 is 3
                logger.debug(f"Container step size {step_size}s = {fmu.step_size}s x {float(ts_ratio)} for "
                             f"'{fmu.name}'.")
                if ts_ratio < 1:
                    logger.warning(f"The step size of the container ({step_size}s) is lower than the one of FMU "
                                   f"'{fmu.name}' ({fmu.step_size}s).")
                if ts_ratio.denominator != 1:
                    logger.warning(f"The step size of the container ({step_size}s) should be a multiple of the one of "
                                   f"FMU "
                                   f"'{fmu.name}' ({fmu.step_size}s).")
            for port_name, fmu_port in fmu.ports.items():
                if fmu_port.is_fmi2_aggregate:
                    continue
                cport = ContainerPort(fmu, port_name)
                if cport not in self.rules:
                    if cport.port.is_reset:
                        logger.warning(f"Reset of FMU '{fmu.name}' is neither linked nor exposed: "
                                       f"the FMU will never be reset.")
                    elif cport.port.causality == 'input' and cport.port.type_name == "clock" \
                            and cport.port.interval_variability in TIME_BASED_CLOCKS:
                        logger.info(f"Input clock {cport.label} is not linked: the container schedules it.")
                    elif cport.port.causality == 'input':
                        logger.error(f"Input {cport.label} is not connected.")
                    if cport.port.causality == 'output':
                        logger.warning(f"Output {cport.label} is not connected.")

    def make_fmu(self, fmu_filename: str | Path, step_size: float | None = None, debug=False, mt=False,
                 profiling=False, sequential=False, ts_multiplier=False, datalog=False,
                 mt_threshold: float = MT_THRESHOLD):
        """Build the FMU Container archive.

        Generates the `modelDescription.xml`, the `container.txt` runtime
        configuration, and packages everything into a `.fmu` zip archive.

        Args:
            fmu_filename (str | Path): Output filename for the container.
            step_size (float | None): Internal time step in seconds. If `None`,
                deduced from the embedded FMUs.
            debug (bool): Keep intermediate build artifacts.
            mt (bool): Enable multithreaded mode.
            profiling (bool): Enable profiling mode.
            sequential (bool): Use sequential scheduling.
            ts_multiplier (bool): Add a `TS_MULTIPLIER` input port.
            datalog (bool): Generate a datalog configuration.
            mt_threshold (float): Multithreaded mode: the embedded FMUs whose mean step takes at least this
                duration, in seconds, get a worker thread (see `MT_THRESHOLD`).
        """
        if mt_threshold < 0:
            raise FMUContainerError(f"The threshold of the multithreaded mode cannot be negative: {mt_threshold}.")
        if isinstance(fmu_filename, str):
            fmu_filename = Path(fmu_filename)

        self.apply_terminal_parameters()
        xcp.check_ports(self)

        if step_size is None:
            logger.info("The step size will be deduced from the embedded FMUs.")
            step_size = self.default_step_size()
        self.sanity_check(step_size)

        if mt and len(self.involved_fmu) < 2:
            logger.error("The multi-threaded mode needs several FMUs: the container runs in mono-threaded mode.")
            mt = False

        logger.info(f"Building '{fmu_filename}' with a step size of {step_size}s.")

        base_directory = self.fmu_directory / fmu_filename.with_suffix('')
        resources_directory = self.make_fmu_skeleton(base_directory)

        # Allocated again at each build: the rules are never modified by a build.
        links = [*self.links.values(), *self.scheduled_clock_links()]
        layout = ContainerLayout.allocate(links, self.inputs, self.outputs,
                                          nb_profiling=len(self.involved_fmu) if profiling else 0,
                                          fmi_version=self.fmi_version)

        self.make_fmu_xml(base_directory / "modelDescription.xml", step_size, profiling, ts_multiplier, layout)
        with open(resources_directory / "container.txt", "w", encoding=ENCODING) as txt_file:
            self.make_fmu_txt(txt_file, step_size, mt, profiling, sequential, layout, mt_threshold=mt_threshold)

        if datalog:
            with open(resources_directory / "datalog.txt", "w", encoding=ENCODING) as datalog_file:
                self.make_datalog(datalog_file, layout)

        xcp.write_manifest(self, base_directory, list(self.get_platforms(verbose=False)))

        self.make_fmu_package(base_directory, fmu_filename)
        if not debug:
            self.make_fmu_cleanup(base_directory)

    def make_fmu_xml(self, xml_filename: Path, step_size: float, profiling: bool, ts_multiplier: bool,
                     layout: ContainerLayout):
        """Build the container `modelDescription.xml` and write it (UTF-8, see `ModelDescription.save`).

        The document is built as an ElementTree, so that names and descriptions
        coming from the embedded FMUs are escaped. FMI-2 `<Unknown index>`
        entries are computed from the actual position of the output variables.
        The value references come from `layout`.
        """
        timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
        guid = str(uuid.uuid4())
        embedded_fmu = ", ".join([fmu_name for fmu_name in self.involved_fmu])
        try:
            author = getpass.getuser()
        except OSError:
            author = "Unspecified"

        capabilities = {}
        for capability in EmbeddedFMU.capability_list:
            capabilities[capability] = "false"
            for fmu in self.involved_fmu.values():
                if fmu.capabilities[capability] == "true":
                    capabilities[capability] = "true"

        first_fmu = next(iter(self.involved_fmu.values()))
        start_time = self.start_time
        if start_time is None:
            start_time = first_fmu.start_time
            logger.info(f"Start time: {start_time}s (deduced from '{first_fmu.name}').")
        else:
            logger.info(f"Start time: {start_time}s.")

        stop_time = self.stop_time
        if stop_time is None:
            stop_time = first_fmu.stop_time
            logger.info(f"Stop time: {stop_time}s (deduced from '{first_fmu.name}').")
        else:
            logger.info(f"Stop time: {stop_time}s.")

        root = ET.Element("fmiModelDescription", {
            "fmiVersion": f"{self.fmi_version}.0",
            "modelName": self.identifier,
            "generationTool": f"FMUContainer-{tool_version}",
            "generationDateAndTime": timestamp,
            "guid" if self.fmi_version == 2 else "instantiationToken": guid,
            "description": f"FMUContainer with {embedded_fmu}",
            "author": author,
            "license": "Proprietary",
            "copyright": "See Embedded FMU's copyrights.",
            "variableNamingConvention": "structured",
        })

        if self.fmi_version == 2:
            cosimulation = {
                "modelIdentifier": self.identifier,
                "canHandleVariableCommunicationStepSize": "true",
                "canBeInstantiatedOnlyOncePerProcess": capabilities['canBeInstantiatedOnlyOncePerProcess'],
                "canNotUseMemoryManagementFunctions": "true",
                "canGetAndSetFMUstate": "false",
                "canSerializeFMUstate": "false",
                "providesDirectionalDerivative": "false",
                "needsExecutionTool": capabilities['needsExecutionTool'],
            }
        else:
            cosimulation = {
                "modelIdentifier": self.identifier,
                "canHandleVariableCommunicationStepSize": "true",
                "fixedInternalStepSize": str(step_size),    # TS_MULTIPLIER keeps the steps on this grid
                "canBeInstantiatedOnlyOncePerProcess": capabilities['canBeInstantiatedOnlyOncePerProcess'],
                "canNotUseMemoryManagementFunctions": "true",
                "canGetAndSetFMUState": "false",
                "canSerializeFMUState": "false",
                "providesDirectionalDerivatives": "false",
                "providesAdjointDerivatives": "false",
                "providesPerElementDependencies": "false",
                "providesEvaluateDiscreteStates": "false",
                "hasEventMode": "false",
                "needsExecutionTool": capabilities['needsExecutionTool'],
            }
        ET.SubElement(root, "CoSimulation", cosimulation)

        log_categories = ET.SubElement(root, "LogCategories")
        ET.SubElement(log_categories, "Category", {"name": "Info", "description": "Info log messages."})
        ET.SubElement(log_categories, "Category", {"name": "Error", "description": "Error log messages."})

        default_experiment = {"stepSize": str(step_size)}
        if start_time is not None:
            default_experiment["startTime"] = str(start_time)
        if stop_time is not None:
            default_experiment["stopTime"] = str(stop_time)
        ET.SubElement(root, "DefaultExperiment", default_experiment)

        model_variables = ET.SubElement(root, "ModelVariables")
        if self.fmi_version == 2:
            time = ET.SubElement(model_variables, "ScalarVariable",
                                 {"valueReference": str(layout.time), "name": "time", "causality": "independent"})
            ET.SubElement(time, "Real")
        else:
            ET.SubElement(model_variables, "Float64",
                          {"valueReference": str(layout.time), "name": "time", "causality": "independent"})

        def add_variable(variable: ET.Element | None) -> ET.Element | None:
            if variable is not None:
                model_variables.append(variable)
            return variable

        logger.debug(f"Value reference of the time: {layout.time}.")

        vr_ts_multiplier = layout.ts_multiplier
        if ts_multiplier:
            logger.debug(f"Value reference of the TS multiplier: {vr_ts_multiplier}.")
            port = EmbeddedFMUPort("integer32", {"valueReference": vr_ts_multiplier,
                                                 "name": "container.ts_multiplier",
                                                 "causality": "input",
                                                 "description": "Timestep multiplier",
                                                 "variability": "discrete",
                                                 "start": 1,
                                                 "initial": "exact"})
            add_variable(port.xml(vr_ts_multiplier, fmi_version=self.fmi_version))

        vr_solver = layout.solver
        if self.have_me:
            logger.debug(f"Value reference of the solver configuration: {vr_solver}.")
            port = EmbeddedFMUPort("integer32", {"valueReference": vr_solver,
                                                 "name": "container.solver",
                                                 "causality": "input",
                                                 "description": "0:Euler, 1: RK4",
                                                 "variability": "discrete",
                                                 "start": 0,
                                                 "initial": "exact"})
            add_variable(port.xml(vr_solver, fmi_version=self.fmi_version))

        if profiling:
            for fmu, vr in zip(self.involved_fmu.values(), layout.profiling, strict=True):
                port = EmbeddedFMUPort("real64", {"valueReference": vr,
                                        "name": f"container.{fmu.id}.rt_ratio",
                                        "description": f"RT ratio for embedded FMU '{fmu.name}'"})
                add_variable(port.xml(vr, fmi_version=self.fmi_version))

        nb_clocks = 0
        for link in layout.links:
            if link.cport_from:
                add_variable(link.cport_from.port.xml(layout.links[link], name=link.name, causality='local',
                                                      fmi_version=self.fmi_version))
            else:
                # LS-BUS allow Clock generated by fmi-importer
                port = EmbeddedFMUPort("Clock",
                                       {"name": "", "valueReference": -1, "intervalVariability": "triggered"},
                                       fmi_version=3)
                add_variable(port.xml(layout.links[link], name=f"container.clock{nb_clocks}", causality='local',
                                      fmi_version=self.fmi_version))
                nb_clocks += 1

        for input_port_name, input_port in self.inputs.items():
            # Get Start and XML from first connected input
            start = self.start_values.get(input_port.cport_list[0], None)
            causality = None
            if self.fmi_version == 2 and input_port.cport_list[0].port.causality == "structuralParameter":
                causality = "parameter"     # set by the container in Configuration Mode
            add_variable(input_port.cport_list[0].port.xml(layout.inputs[input_port_name], name=input_port_name,
                                                           causality=causality, start=start,
                                                           fmi_version=self.fmi_version))

        outputs = []    # (value reference of a container output, its variable element), for <ModelStructure>
        for output_port_name, output_port in self.outputs.items():
            conversion = layout.output_conversions.get(output_port_name)
            variable = add_variable(output_port.port.xml(layout.outputs[output_port_name], name=output_port_name,
                                                         fmi_version=self.fmi_version,
                                                         type_name=conversion.type_name if conversion else None))
            if variable is not None:
                outputs.append((layout.outputs[output_port_name], variable))

        # FMI-2 §2.2.8, FMI-3 §2.4.8: the initial unknowns are the outputs with initial="calculated" or "approx". An
        # output that copies initial="exact" (and its start value) from its embedded FMU is not one.
        initial_unknowns = [(vr, variable) for vr, variable in outputs if self._initial_of(variable) != "exact"]
        model_structure = ET.SubElement(root, "ModelStructure")
        if self.fmi_version == 2:
            # FMI-2 §2.2.8: <Unknown index> is the 1-based position of the variable in <ModelVariables>.
            positions = {id(variable): index for index, variable in enumerate(model_variables, start=1)}
            for section, entries in (("Outputs", outputs), ("InitialUnknowns", initial_unknowns)):
                if entries:
                    unknowns = ET.SubElement(model_structure, section)
                    for _, variable in entries:
                        ET.SubElement(unknowns, "Unknown", {"index": str(positions[id(variable)])})
        else:
            for tag, entries in (("Output", outputs), ("InitialUnknown", initial_unknowns)):
                for output_vr, _ in entries:
                    ET.SubElement(model_structure, tag, {"valueReference": str(output_vr)})

        ModelDescription(root).save(xml_filename)

    @staticmethod
    def _initial_of(variable: ET.Element) -> str:
        """The `initial` of a generated output, given or by default (FMI-2 §2.2.7, FMI-3 §2.4.7.4: `exact` for a
        constant output, `calculated` otherwise)."""
        initial = variable.get("initial")
        if initial is None:
            initial = "exact" if variable.get("variability") == "constant" else "calculated"
        return initial

    @staticmethod
    def _link_graph(links, fmu_rank: dict[str, int]) -> dict[int, set[int]]:
        """Graph of the embedded FMUs of `fmu_rank`, with an edge from the FMU of an output to the FMU of an input it
        is linked to. The clocks, the clocked variables, the `container.reset` triggers, the links of an FMU on
        itself and the links with an FMU absent from `fmu_rank` make no edge.

        Args:
            links: The links of the container.
            fmu_rank (dict[str, int]): Index of each embedded FMU in `container.txt`, by FMU name.

        Returns:
            dict[int, set[int]]: The indexes of the FMUs fed by each FMU, by FMU index.
        """
        successors: dict[int, set[int]] = {rank: set() for rank in fmu_rank.values()}
        for link in links:
            cport_from = link.cport_from
            if cport_from is None or cport_from.port.clock or cport_from.port.type_name == "clock":
                continue
            for cport_to in link.cport_to_list:
                if cport_to.port.is_reset or cport_to.port.clock or cport_to.fmu.name == cport_from.fmu.name:
                    continue
                if cport_from.fmu.name in fmu_rank and cport_to.fmu.name in fmu_rank:
                    successors[fmu_rank[cport_from.fmu.name]].add(fmu_rank[cport_to.fmu.name])
        return successors

    def initialization_order(self, fmu_rank: dict[str, int]) -> list[int]:
        """Order in which the embedded FMUs propagate their links during the initialization.

        Topological sort of the graph of the embedded FMUs, with an edge from the FMU of an output to the FMU of an
        input it is linked to. The clocks, the clocked variables and the `container.reset` triggers make no edge
        (they are not propagated during the initialization). Between independent FMUs, the order of the
        configuration (`fmu_rank`) decides. A loop is cut before its first FMU in the configuration, which is then
        initialized without the values computed by the loop: a warning is logged.

        Args:
            fmu_rank (dict[str, int]): Index of each embedded FMU in `container.txt`, by FMU name.

        Returns:
            list[int]: The indexes of every embedded FMU, in initialization order.
        """
        successors = self._link_graph(self.links.values(), fmu_rank)

        nb_predecessors = {rank: 0 for rank in successors}
        for targets in successors.values():
            for target in targets:
                nb_predecessors[target] += 1

        name_of = {rank: name for name, rank in fmu_rank.items()}
        order: list[int] = []
        remaining = set(successors)
        while remaining:
            ready = [rank for rank in remaining if nb_predecessors[rank] == 0]
            if ready:
                rank = min(ready)
            else:                                                # a loop: cut before its first FMU
                rank = min(remaining)
                logger.warning(f"Loop of links through the embedded FMU '{name_of[rank]}': it is initialized "
                               f"without the values its inputs get from the loop.")
            order.append(rank)
            remaining.remove(rank)
            for target in successors[rank]:
                nb_predecessors[target] -= 1
        return order

    def check_sequential_order(self, fmu_rank: dict[str, int]) -> None:
        """Warn when the sequential scheduling steps the Co-Simulation FMUs against the order of their links.

        In sequential mode, the Co-Simulation FMUs step one after the other in the order of the configuration, each
        one with the outputs just computed by the previous ones: an FMU placed before an FMU it depends on gets the
        outputs of the previous step. The links inside a loop are left out (one of them goes backwards whatever the
        order), as are the Model-Exchange FMUs, which step together after the Co-Simulation FMUs.

        Args:
            fmu_rank (dict[str, int]): Index of each embedded FMU in `container.txt`, by FMU name.
        """
        cs_rank = {name: rank for name, rank in fmu_rank.items() if not self.involved_fmu[name].is_me}
        successors = self._link_graph(self.links.values(), cs_rank)

        def reachable(start: int) -> set[int]:
            seen: set[int] = set()
            stack = [start]
            while stack:
                for target in successors[stack.pop()]:
                    if target not in seen:
                        seen.add(target)
                        stack.append(target)
            return seen

        # Predecessors of each FMU outside of its loops: a source reachable from its target is in a loop with it.
        reachable_from = {rank: reachable(rank) for rank in successors}
        predecessors: dict[int, set[int]] = {rank: set() for rank in successors}
        for source, targets in successors.items():
            for target in targets:
                if source not in reachable_from[target]:
                    predecessors[target].add(source)

        if any(source > target for target, sources in predecessors.items() for source in sources):
            # The FMUs of a loop wait for the predecessors of the whole loop.
            waiting_for = {rank: set().union(*(predecessors[other] for other in successors
                                               if other == rank or rank in reachable_from[other] and
                                               other in reachable_from[rank]))
                           for rank in successors}
            order: list[int] = []
            while len(order) < len(waiting_for):
                order.append(min(rank for rank, sources in waiting_for.items()
                                 if rank not in order and sources.issubset(order)))
            name_of = {rank: name for name, rank in cs_rank.items()}
            logger.warning(f"Sequential mode: the order of the configuration does not match the topological order "
                           f"of the links. Topological order of the Co-Simulation FMUs: "
                           f"{', '.join(name_of[rank] for rank in order)}.")

    @staticmethod
    def check_clocks_of_link(link: Link, scheduled_clocks: list[ContainerPort]):
        """Warn about the input clocks of a link that will not tick together: they share their local variable."""
        if not scheduled_clocks:
            logger.warning(f"No clock drives {', '.join(str(cport) for cport in link.cport_to_list)}: "
                           f"they will never tick.")

        declared = {(cport.port.interval_decimal, cport.port.shift_decimal or "0") for cport in scheduled_clocks
                    if cport.port.interval_decimal is not None}
        if len(declared) > 1:
            logger.warning(f"The ticks of {', '.join(str(cport) for cport in scheduled_clocks)} must match, "
                           f"but their intervals and shifts differ.")

    def make_fmu_txt(self, txt_file, step_size: float, mt: bool, profiling: bool, sequential: bool,
                     layout: ContainerLayout, mt_threshold: float = MT_THRESHOLD):
        print(f"# Version {CONTAINER_TXT_VERSION}", file=txt_file)
        print("# Container flags <MT> <Profiling> <Sequential> <MT_THRESHOLD_US>", file=txt_file)
        flags = [str(int(bool(flag))) for flag in (mt, profiling, sequential)]
        print(" ".join(flags + [str(round(mt_threshold * 1e6))]), file=txt_file)

        print("# Internal time step in seconds", file=txt_file)
        print(f"{step_size}", file=txt_file)

        print("# NB of embedded FMU's", file=txt_file)
        # An exposed structural parameter has a start value of Configuration Mode (its start value by default): the
        # runtime sets it in Configuration Mode only. The FMUs with such values go through their Configuration Mode.
        start_values = dict(self.start_values)
        for input_port in self.inputs.values():
            for cport in input_port.cport_list:
                if cport.port.causality == "structuralParameter" and cport not in start_values and \
                        cport.port.start_value is not None:
                    start_values[cport] = self.start_value_text(cport, cport.port.start_value)
        configured = {cport.fmu.name for cport in start_values if cport.port.causality == "structuralParameter"}
        fmu_rank = self.involved_fmu.write_txt(txt_file, configured)

        print("# Initialization order of the embedded FMU's", file=txt_file)
        print(" ".join(str(rank) for rank in self.initialization_order(fmu_rank)), file=txt_file)
        if sequential:
            self.check_sequential_order(fmu_rank)


        # Prepare data structure
        inputs_per_type: dict[str, list[ContainerInput]] = defaultdict(list) # Container's INPUT
        outputs_per_type: dict[str, list[tuple[str, ContainerPort]]] = defaultdict(list) # Container's OUTPUT

        fmu_io_list = FMUIOList(layout.table)
        clock_list = ClockList(self.involved_fmu)

        local_per_type: dict[str, list[LocalVariable]] = defaultdict(list)
        links_per_fmu: dict[str, list[Link]] = defaultdict(list)
        # Local storage offset of the `container.reset` trigger of each FMU, by FMU name
        reset_triggers: dict[str, int] = {}

        # Fill data structure
        # Inputs
        for input_port_name, input_port in self.inputs.items():
            inputs_per_type[input_port.type_name].append(input_port)
            for cport in input_port.cport_list:
                if cport.port.is_reset:
                    reset_triggers[cport.fmu.name] = layout.reset_inputs[input_port_name]

        # Start values
        for cport, value in start_values.items():
            fmu_io_list.add_start_value(cport, value)

        # Outputs; those exposed through a local variable (converted, FMI-2 array aggregate) are listed with the local
        # variables
        for output_port_name, output_port in self.outputs.items():
            if output_port_name not in layout.output_conversions and output_port_name not in layout.aggregate_outputs:
                outputs_per_type[output_port.port.type_name].append((output_port_name, output_port))

        # Links
        for link in layout.links:
            scheduled_clocks = []

            # FMU Outputs
            if link.cport_from:
                local_per_type[link.cport_from.port.type_name].append(LocalVariable(layout.links[link], link.size))
                fmu_io_list.add_output(link.cport_from, layout.links[link])
                for cport_to in link.cport_to_list:
                    if cport_to.port.interval_variability in TIME_BASED_CLOCKS:
                        logger.warning(f"{cport_to} ticks with port {link.cport_from.label} only: their ticks must "
                                       f"match.")
            else:
                local_per_type["clock"].append(LocalVariable(layout.links[link], link.size))
                for cport_to in link.cport_to_list:
                    if cport_to.port.interval_variability in TIME_BASED_CLOCKS:
                        scheduled_clocks.append(cport_to)
                        logger.info(f"FMI-LS-BUS: the importer schedules the clock {cport_to.label} "
                                    f"(valueReference {cport_to.port.vr}, local {layout.links[link]}).")
                        clock_list.append(cport_to, layout.links[link])
                self.check_clocks_of_link(link, scheduled_clocks)

            # Converted copies: one local variable per target type, whatever the number of targets of that type.
            for type_name in link.conversions:
                local_per_type[type_name].append(LocalVariable(layout.converted[link][type_name], link.size))
            if link.conversions:
                assert link.cport_from is not None
                links_per_fmu[link.cport_from.fmu.name].append(link)

            # FMU Inputs
            for cport_to in link.cport_to_list:
                if cport_to not in scheduled_clocks:
                    # LS-BUS allows, importer to feed clock signal. In this case, cport_from is None
                    # A scheduled clock is activated directly by the schedule, no need to add input link!
                    if link.cport_from is None or cport_to.port.type_name == link.cport_from.port.type_name:
                        local_vr = layout.links[link]
                    else:
                        local_vr = layout.converted[link][cport_to.port.type_name]
                    if cport_to.port.is_reset:
                        # Read by the container, never set to the FMU.
                        reset_triggers[cport_to.fmu.name] = layout.local_offset(local_vr)
                    else:
                        fmu_io_list.add_input(cport_to, local_vr)

        # Outputs exposed through a converted local variable: the value of the FMU and its converted copy, unless the
        # link of the port already has them (allocated after the local variables of the links, in this order).
        output_conversions_per_fmu: dict[str, list[tuple[int, int, str]]] = defaultdict(list)
        for conversion in {id(conversion): conversion for conversion in layout.output_conversions.values()}.values():
            size = conversion.cport.port.size()
            if conversion.own_local:
                local_per_type[conversion.cport.port.type_name].append(LocalVariable(conversion.local, size))
                fmu_io_list.add_output(conversion.cport, conversion.local)
            if conversion.own_copy:
                local_per_type[conversion.type_name].append(LocalVariable(conversion.vr, size))
                output_conversions_per_fmu[conversion.cport.fmu.name].append(
                    (conversion.local, conversion.vr, conversion.conversion))

        # FMI-2 array aggregates exposed by the container: a local variable, whose elements are exchanged one by one
        # with the FMU (allocated after the converted outputs, the outputs first).
        aggregate_locals = {}
        for output_port_name, vr in layout.aggregate_outputs.items():
            output_port = self.outputs[output_port_name]
            if vr not in aggregate_locals:
                aggregate_locals[vr] = (output_port.port.type_name, output_port.port.size())
                fmu_io_list.add_output(output_port, vr)
        for input_port_name, vr in layout.aggregate_inputs.items():
            input_port = self.inputs[input_port_name]
            aggregate_locals[vr] = (input_port.type_name, input_port.size)
            for cport in input_port.cport_list:
                if cport.port.is_fmi2_aggregate:
                    fmu_io_list.add_input(cport, vr)
        for vr, (type_name, size) in sorted(aggregate_locals.items()):
            local_per_type[type_name].append(LocalVariable(vr, size))

        print("# NB local variables:", ", ".join(ALL_TYPES), file=txt_file)
        nb_storage = [f"{layout.table.nb_storage(type_name)}" for type_name in ALL_TYPES]
        print(" ".join(nb_storage), file=txt_file, end='')
        print("", file=txt_file)

        print("# CONTAINER I/O: <VR> <DIM> <NB> <FMU_INDEX> <FMU_VR> [<FMU_INDEX> <FMU_VR>]", file=txt_file)
        for type_name in ALL_TYPES:
            print(f"# {type_name}" , file=txt_file)
            nb_local = (len(inputs_per_type[type_name]) +
                        len(outputs_per_type[type_name]) +
                        layout.table.nb_local(type_name))
            input_links = {input_port.name: self._input_links(input_port, layout, fmu_rank)
                           for input_port in inputs_per_type[type_name]}
            nb_input_link = sum(len(links) - 1 for links in input_links.values())
            print(f"{nb_local} {nb_local + nb_input_link}", file=txt_file)
            # Reserved variables, stored locally: <FMU_INDEX> is -1 (-2 for profiling) and <FMU_VR> the local offset.
            if type_name == "real64":
                print(f"{layout.time} 1 1 -1 {layout.local_offset(layout.time)}", file=txt_file)
                for vr in layout.profiling:
                    print(f"{vr} 1 1 -2 {layout.local_offset(vr)}", file=txt_file)
            elif type_name == "integer32":
                for vr in (layout.ts_multiplier, layout.solver):
                    print(f"{vr} 1 1 -1 {layout.local_offset(vr)}", file=txt_file)

            for input_port in inputs_per_type[type_name]:
                links = input_links[input_port.name]
                print(f"{layout.inputs[input_port.name]} {input_port.size} {len(links)}", " ".join(links),
                      file=txt_file)
            for output_port_name, output_port in outputs_per_type[type_name]:
                print(f"{layout.outputs[output_port_name]} {output_port.port.size()} 1 "
                      f"{fmu_rank[output_port.fmu.name]} {output_port.port.vr}", file=txt_file)
            offset_storage = 0
            for local_variable in local_per_type[type_name]:
                print(f"{local_variable.vr} {local_variable.dimension} 1 -1 "
                      f"{(local_variable.vr & 0xFFFFFF) + offset_storage}", file=txt_file)
                offset_storage += local_variable.dimension - 1
        # LINKS
        for fmu in self.involved_fmu.values():
            fmu_io_list.write_txt(fmu.name, txt_file)

            print(f"# Conversion table of {fmu.name}: <VR_FROM> <VR_TO> <CONVERSION>", file=txt_file)
            print(sum(len(link.conversions) for link in links_per_fmu[fmu.name]) +
                  len(output_conversions_per_fmu[fmu.name]), file=txt_file)
            for link in links_per_fmu[fmu.name]:
                for type_name, conversion_function in link.conversions.items():
                    print(f"{layout.links[link]} {layout.converted[link][type_name]} {conversion_function}",
                          file=txt_file)
            for vr_from, vr_to, conversion_function in output_conversions_per_fmu[fmu.name]:
                print(f"{vr_from} {vr_to} {conversion_function}", file=txt_file)

            print(f"# Reset trigger of {fmu.name}: <LOCAL_OFFSET>", file=txt_file)
            print(reset_triggers.get(fmu.name, -1), file=txt_file)

        # CLOCKS
        clock_list.write_txt(txt_file)

    @staticmethod
    def _input_links(input_port: ContainerInput, layout: ContainerLayout, fmu_rank: dict[str, int]) -> list[str]:
        """`<FMU_INDEX> <FMU_VR>` pairs of a container input. The `container.reset` ports it feeds share one local
        variable (`-1 <LOCAL_OFFSET>`), and so do the FMI-2 array aggregates it feeds: listed first, the getter of the
        container reads the first pair."""
        links = []
        if input_port.has_reset:
            links.append(f"-1 {layout.reset_inputs[input_port.name]}")
        if input_port.name in layout.aggregate_inputs:     # FMI-2 array aggregates: through their local variable
            links.append(f"-1 {layout.local_offset(layout.aggregate_inputs[input_port.name])}")
        links.extend(f"{fmu_rank[cport.fmu.name]} {cport.port.vr}" for cport in input_port.cport_list
                     if not cport.port.is_reset and not cport.port.is_fmi2_aggregate)
        return links

    def make_datalog(self, datalog_file, layout: ContainerLayout):
        print("# Datalog filename", file=datalog_file)
        print(f"{self.identifier}-datalog.csv", file=datalog_file)

        ports = defaultdict(list)
        for input_port_name, input_port in self.inputs.items():
            ports[input_port.type_name].append(Port(layout.inputs[input_port_name], input_port_name))
        for output_port_name, output_port in self.outputs.items():
            conversion = layout.output_conversions.get(output_port_name)
            ports[conversion.type_name if conversion else output_port.port.type_name].append(
                Port(layout.outputs[output_port_name], output_port_name))
        for link in layout.links:
            if link.cport_from is None:
                # LS-BUS allows connected input clocks. The column is named after the clock that ticks by itself, the
                # one of the sender: `datalog2pcap` finds the clock of `<name>_Data` with this name.
                scheduled = [cport for cport in link.cport_to_list
                             if cport.port.interval_variability in TIME_BASED_CLOCKS]
                name = f"{scheduled[0].fmu.id}.{scheduled[0].port.name}" if scheduled else link.name
                ports[link.cport_to_list[0].port.type_name].append(Port(layout.links[link], name))
            else:
                ports[link.cport_from.port.type_name].append(Port(layout.links[link], link.name))

        for type_name in ALL_TYPES:
            print(f"# {type_name}: <VR> <NAME>" , file=datalog_file)
            print(f"{len(ports[type_name])}", file=datalog_file)
            for port in ports[type_name]:
                print(f"{port.vr} {port.name}", file=datalog_file)

    @staticmethod
    def long_path(path: _PathT) -> _PathT | str:
        # https://stackoverflow.com/questions/14075465/copy-a-file-with-a-too-long-path-to-another-directory-in-python
        if os.name == 'nt':
            return "\\\\?\\" + os.path.abspath(str(path))
        else:
            return path

    @staticmethod
    def copyfile(origin, destination):
        logger.debug(f"Copying '{origin}' to '{destination}'.")
        shutil.copy(origin, destination)

    def get_platforms(self, verbose=True) -> Generator[Platform, Any, None]:
        fmu_iter = iter(self.involved_fmu.values())
        try:
            fmu = next(fmu_iter)
        except StopIteration:
            raise FMUContainerError("No fmu declared in this container.") from None

        os_list = fmu.platforms
        logger.debug(f"FMU '{fmu.name}' OS support: {', '.join(fmu.platforms)}.")

        for fmu in fmu_iter:
            logger.debug(f"FMU '{fmu.name}' OS support: {', '.join(fmu.platforms)}.")
            os_list &= fmu.platforms

        suffixes = {
            "Windows": "dll",
            "Linux": "so",
            "Darwin": "dylib"
        }

        origin_bindirs = {
            "Windows": "win64",
            "Linux": "linux64",
            "Darwin": "darwin64"
        }

        if self.fmi_version == 3:
            target_bindirs = {
                "Windows": "x86_64-windows",
                "Linux": "x86_64-linux",
                "Darwin": "aarch64-darwin"
            }
        else:
            target_bindirs = origin_bindirs

        if not verbose:
            pass
        elif os_list:
            logger.info(f"Container will be built for {', '.join(os_list)}.")
        else:
            logger.error("No common OS found for the embedded FMUs: the container will not be runnable. Try again "
                         "with '-debug'.")

        for os_name in os_list:
            try:
                yield Platform(origin_bindirs[os_name], suffixes[os_name], target_bindirs[os_name])
            except KeyError:
                raise FMUContainerError(f"OS '{os_name}' is not supported.") from None

    def make_fmu_skeleton(self, base_directory: Path) -> Path:
        logger.debug(f"Initialize directory '{base_directory}'.")

        origin = Path(__file__).parent.parent / "resources"  # resources of the toolbox package
        resources_directory = base_directory / "resources"
        documentation_directory = base_directory / "documentation"
        binaries_directory = base_directory / "binaries"

        base_directory.mkdir(exist_ok=True)
        resources_directory.mkdir(exist_ok=True)
        binaries_directory.mkdir(exist_ok=True)
        documentation_directory.mkdir(exist_ok=True)

        if self.description_pathname:
            self.copyfile(self.description_pathname, documentation_directory)

        # Model icon location depends on the FMI version:
        #   - FMI-3: terminalsAndIcons/icon.png
        #   - FMI-2: model.png at the FMU root
        if self.fmi_version == 3:
            terminals_and_icons_directory = base_directory / "terminalsAndIcons"
            terminals_and_icons_directory.mkdir(exist_ok=True)
            self.copyfile(origin / "fmucontainer.png", terminals_and_icons_directory / "icon.png")
        else:
            self.copyfile(origin / "fmucontainer.png", base_directory / "model.png")

        for platform in self.get_platforms():
            library_filename = origin / platform.origin_bindir / f"container.{platform.suffixe}"
            if library_filename.is_file():
                binary_directory = binaries_directory / platform.target_bindir
                binary_directory.mkdir(exist_ok=True)
                self.copyfile(library_filename, binary_directory / f"{self.identifier}.{platform.suffixe}")
            else:
                logger.error(f"File '{library_filename}' not found.")

        for i, fmu in enumerate(self.involved_fmu.values()):
            with zipfile.ZipFile(fmu.fmu.fmu_filename) as zin:
                zin.extractall(self.long_path(resources_directory / f"{i:02x}"))
            # FMI-3 gives a NULL resourcePath to an FMU without resources folder (2.3.1), which some FMUs do not
            # expect (strdup(resourcePath)): every embedded FMU gets one, empty when it has none.
            os.makedirs(self.long_path(resources_directory / f"{i:02x}" / "resources"), exist_ok=True)

        return resources_directory

    def make_fmu_package(self, base_directory: Path, fmu_filename: Path):
        logger.debug(f"Zipping directory '{base_directory}' into '{fmu_filename}'.")
        zip_directory = self.long_path(str(base_directory.absolute()))
        offset = len(zip_directory) + 1
        with zipfile.ZipFile(self.fmu_directory / fmu_filename, "w", zipfile.ZIP_DEFLATED) as zip_file:
            def add_file(directory: Path):
                for entry in directory.iterdir():
                    if entry.is_dir():
                        if not any(entry.iterdir()):
                            zip_file.write(str(entry), str(entry)[offset:])     # an empty folder is kept
                        add_file(directory / entry)
                    elif entry.is_file():
                        zip_file.write(str(entry), str(entry)[offset:])

            add_file(Path(zip_directory))
        logger.info(f"'{fmu_filename}' is available.")

    def make_fmu_cleanup(self, base_directory: Path):
        logger.debug(f"Delete directory '{base_directory}'.")
        shutil.rmtree(self.long_path(base_directory))

add_implicit_rule(auto_input=True, auto_output=True, auto_link=True, auto_parameter=False, auto_local=False)

Automatically wire unconnected ports of embedded FMUs.

Processes all ports in the following order:

  1. auto_link: Connect outputs to inputs with matching names and types.
  2. auto_output: Expose remaining unconnected outputs.
  3. auto_local: Expose local variables.
  4. auto_input: Expose remaining unconnected inputs.
  5. auto_parameter: Expose parameters.
  6. Always: expose the variables that configure the XCP services of the embedded FMUs (FMI-LS-XCP), as <fmu id>.<variable>.

Parameters:

Name Type Description Default
auto_input bool

Expose unconnected input ports.

True
auto_output bool

Expose unconnected output ports.

True
auto_link bool

Link matching output/input ports automatically.

True
auto_parameter bool

Expose parameter ports.

False
auto_local bool

Expose local variables.

False

Returns:

Name Type Description
AutoWired AutoWired

Record of all automatically created rules.

Source code in fmu_manipulation_toolbox/container/builder.py
def add_implicit_rule(self, auto_input=True, auto_output=True, auto_link=True, auto_parameter=False,
                      auto_local=False) -> AutoWired:
    """Automatically wire unconnected ports of embedded FMUs.

    Processes all ports in the following order:

    1. **auto_link**: Connect outputs to inputs with matching names and types.
    2. **auto_output**: Expose remaining unconnected outputs.
    3. **auto_local**: Expose local variables.
    4. **auto_input**: Expose remaining unconnected inputs.
    5. **auto_parameter**: Expose parameters.
    6. Always: expose the variables that configure the XCP services of the embedded FMUs (FMI-LS-XCP), as
       `<fmu id>.<variable>`.

    Args:
        auto_input (bool): Expose unconnected input ports.
        auto_output (bool): Expose unconnected output ports.
        auto_link (bool): Link matching output/input ports automatically.
        auto_parameter (bool): Expose parameter ports.
        auto_local (bool): Expose local variables.

    Returns:
        AutoWired: Record of all automatically created rules.
    """
    auto_wired = AutoWired()
    all_cports = self.get_all_cports()
    # Candidates of the auto-links, by (name, type), in the order of `all_cports`: same result as `find_inputs`,
    # without going through every port for each output.
    inputs_by_signature: dict[tuple[str, str], list[ContainerPort]] = defaultdict(list)
    for cport in all_cports:
        if cport.port.causality == 'input':
            inputs_by_signature[(cport.port.name, cport.port.type_name)].append(cport)

    # Auto Link outputs. The instances of an FMU share its port names: they are never auto-linked, otherwise an
    # output would feed the inputs of every instance.
    for cport in all_cports:
        if cport.port.causality == 'output':
            candidates_cport_list = [candidate for candidate in
                                     inputs_by_signature[(cport.port.name, cport.port.type_name)]
                                     if candidate not in self.rules and not candidate.fmu.is_instance]
            if auto_link and candidates_cport_list and not cport.fmu.is_instance:
                for candidate_cport in candidates_cport_list:
                    logger.info(f"Auto link: {cport.label} → {candidate_cport.label}.")
                    self.add_link(cport.fmu.name, cport.port.name,
                                  candidate_cport.fmu.name, candidate_cport.port.name)
                    auto_wired.add_link(cport.fmu.name, cport.port.name,
                                        candidate_cport.fmu.name, candidate_cport.port.name)
            elif auto_output and cport not in self.rules and cport.port.is_clocked:
                logger.warning(f"Auto output: port {cport.label} is not exposed: clocks and clocked variables "
                               f"cannot be "
                               f"exposed.")
            elif auto_output and cport not in self.rules:
                output_name = self._auto_name(cport)
                logger.info(f"Auto output: port {cport.label} exposed as '{output_name}'.")
                self.add_output(cport.fmu.name, cport.port.name, output_name)
                auto_wired.add_output(cport.fmu.name, cport.port.name, output_name)
        elif cport.port.causality == 'local':
            local_portname = None
            if cport.port.name.startswith("container."):
                local_portname = "container." + cport.fmu.id + "." + cport.port.name[10:]
                logger.info(f"Profiling: port {cport.label} exposed.")
            elif auto_local and cport.port.is_clocked:
                logger.debug(f"Auto local: port {cport.label} is not exposed: clocks and clocked variables cannot "
                             f"be exposed.")
            elif auto_local:
                local_portname = cport.fmu.id + "." + cport.port.name
                logger.info(f"Auto local: port {cport.label} exposed as '{local_portname}'.")
            if local_portname:
                self.add_output(cport.fmu.name, cport.port.name, local_portname)
                auto_wired.add_output(cport.fmu.name, cport.port.name, local_portname)

    # Auto link inputs
    for cport in all_cports:
        if cport not in self.rules:
            if auto_parameter and cport.port.causality == 'parameter':
                parameter_name = cport.fmu.id + "." + cport.port.name
                logger.info(f"Auto parameter: port {cport.label} exposed as '{parameter_name}'.")
                self.add_input(parameter_name, cport.fmu.name, cport.port.name)
                auto_wired.add_parameter(parameter_name, cport.fmu.name, cport.port.name)
            elif auto_input and cport.port.causality == 'input' and cport.port.type_name == "clock" \
                    and cport.port.interval_variability in TIME_BASED_CLOCKS:
                logger.info(f"Auto input: port {cport.label} is not exposed (a clock cannot be): the container "
                            f"schedules it.")
            elif auto_input and cport.port.causality == 'input' and cport.port.is_clocked:
                logger.warning(f"Auto input: port {cport.label} is not exposed: clocks and clocked variables "
                               f"cannot be "
                               f"exposed.")
            elif auto_input and cport.port.causality == 'input' :
                input_name = self._default_reset_input_name(cport.fmu) if cport.port.is_reset \
                    else self._auto_name(cport)
                logger.info(f"Auto input: port {cport.label} exposed as '{input_name}'.")
                self.add_input(input_name, cport.fmu.name, cport.port.name)
                auto_wired.add_input(input_name, cport.fmu.name, cport.port.name)

    # FMI-LS-XCP: the variables that configure the XCP services of the embedded FMUs, whatever the options
    xcp.expose_variables(self, auto_wired)

    logger.info(f"Automatic wiring: {auto_wired}")

    return auto_wired

add_input(container_port_name, to_fmu_filename, to_port_name)

Expose a port of an embedded FMU as a container input.

Multiple embedded FMU ports can be connected to the same container input (fan-out), provided they share the same type and causality.

Parameters:

Name Type Description Default
container_port_name str

Exposed name on the container. If empty, defaults to to_port_name, or container.<id>.reset for the container.reset port (refused when that name is already used).

required
to_fmu_filename str

Filename of the embedded FMU.

required
to_port_name str

Name of the input port on the embedded FMU.

required

Raises:

Type Description
FMUContainerError

If the FMU or the port does not exist, if the port causality is not "input", "parameter" or "structuralParameter" (a scalar that gives no dimension), or if types do not match an existing input with the same name.

Source code in fmu_manipulation_toolbox/container/builder.py
def add_input(self, container_port_name: str, to_fmu_filename: str, to_port_name: str):
    """Expose a port of an embedded FMU as a container input.

    Multiple embedded FMU ports can be connected to the same container
    input (fan-out), provided they share the same type and causality.

    Args:
        container_port_name (str): Exposed name on the container. If empty,
            defaults to `to_port_name`, or `container.<id>.reset` for the
            `container.reset` port (refused when that name is already used).
        to_fmu_filename (str): Filename of the embedded FMU.
        to_port_name (str): Name of the input port on the embedded FMU.

    Raises:
        FMUContainerError: If the FMU or the port does not exist, if the port
            causality is not `"input"`, `"parameter"` or `"structuralParameter"` (a scalar that gives no
            dimension), or if types do not match an existing input with the same name.
    """
    try:
        cport_to = ContainerPort(self.get_fmu(to_fmu_filename), to_port_name)
    except FMUContainerError as e:
        raise FMUContainerError(f"Cannot add input '{container_port_name or to_port_name}': {e.reason}") from e

    if not container_port_name:
        container_port_name = self._default_reset_input_name(cport_to.fmu) if cport_to.port.is_reset \
            else to_port_name

    if cport_to.port.causality not in ("input", "parameter", "structuralParameter"):  # check causality
        raise FMUContainerError(f"Cannot use {cport_to} as an input of the container: its causality is "
                                f"'{cport_to.port.causality}'.")
    if not cport_to.is_exposable("INPUT"):
        return
    if cport_to.port.causality == "structuralParameter":
        cport_to.check_structural_parameter()

    feeder = f"the container input '{container_port_name}'"
    self.check_not_fed(cport_to, feeder)
    try:
        input_port = self.inputs[container_port_name]
        input_port.add_cport(cport_to)
    except KeyError:
        self.inputs[container_port_name] = ContainerInput(container_port_name, cport_to)
    self.input_feeders[cport_to] = feeder

    logger.debug(f"{cport_to} is an input of the container.")
    self.mark_ruled(cport_to, 'INPUT')

Connect an output of one embedded FMU to an input of another.

If both port names match FMI Terminal definitions, a terminal-level connection is made (connecting all member ports). Otherwise, a regular port-to-port link is created.

Parameters:

Name Type Description Default
from_fmu_filename str

Filename of the source FMU.

required
from_port_name str

Output port name (or terminal name).

required
to_fmu_filename str

Filename of the destination FMU.

required
to_port_name str

Input port name (or terminal name).

required

Raises:

Type Description
FMUContainerError

If an FMU or a port does not exist, if port causalities are invalid or types are incompatible.

Source code in fmu_manipulation_toolbox/container/builder.py
def add_link(self, from_fmu_filename: str, from_port_name: str, to_fmu_filename: str, to_port_name: str):
    """Connect an output of one embedded FMU to an input of another.

    If both port names match FMI Terminal definitions, a terminal-level
    connection is made (connecting all member ports). Otherwise, a regular
    port-to-port link is created.

    Args:
        from_fmu_filename (str): Filename of the source FMU.
        from_port_name (str): Output port name (or terminal name).
        to_fmu_filename (str): Filename of the destination FMU.
        to_port_name (str): Input port name (or terminal name).

    Raises:
        FMUContainerError: If an FMU or a port does not exist, if port
            causalities are invalid or types
            are incompatible.
    """
    fmu_from = self.get_fmu(from_fmu_filename)
    fmu_to = self.get_fmu(to_fmu_filename)

    if from_port_name in fmu_from.terminals and to_port_name in fmu_to.terminals:
        # TERMINAL Connection
        terminal1 = fmu_from.terminals[from_port_name]
        terminal2 = fmu_to.terminals[to_port_name]
        if terminal1 == terminal2:
            logger.debug(f"Plugging the terminals '{terminal1.path}' and '{terminal2.path}'.")
            try:
                links = terminal1.connect(terminal2)
            except TerminalError as e:
                raise FMUContainerError(f"Cannot plug the terminals of '{fmu_from.name}' and '{fmu_to.name}': "
                                        f"{e}") from e
            for terminal1_port_name, terminal2_port_name in links:
                self.add_link_regular(fmu_from, terminal1_port_name, fmu_to, terminal2_port_name)
            for terminal1_port_name, terminal2_port_name in terminal1.connected_parameters(terminal2):
                self.terminal_parameters.append((ContainerPort(fmu_from, terminal1_port_name),
                                                 ContainerPort(fmu_to, terminal2_port_name)))
        else:
            logger.error(f"Cannot plug the incompatible terminals '{terminal1.path}' and '{terminal2.path}'.")
    else:
        # REGULAR port connection
        try:
            self.add_link_regular(fmu_from, from_port_name, fmu_to, to_port_name)
        except FMUContainerError as e:
            paths = fmu_from.terminals.paths_of(from_port_name) + fmu_to.terminals.paths_of(to_port_name)
            if paths:
                raise FMUContainerError(f"{e.reason} A nested terminal is designated by its full path: "
                                        f"{', '.join(paths)}.") from e
            raise

add_output(from_fmu_filename, from_port_name, container_port_name)

Expose a port of an embedded FMU as a container output.

Parameters:

Name Type Description Default
from_fmu_filename str

Filename of the embedded FMU.

required
from_port_name str

Name of the output port on the embedded FMU.

required
container_port_name str

Exposed name on the container. If empty, defaults to from_port_name.

required

Raises:

Type Description
FMUContainerError

If the FMU or the port does not exist, if the port causality is not "output" or "local", or if the exposed name is already used.

Source code in fmu_manipulation_toolbox/container/builder.py
def add_output(self, from_fmu_filename: str, from_port_name: str, container_port_name: str):
    """Expose a port of an embedded FMU as a container output.

    Args:
        from_fmu_filename (str): Filename of the embedded FMU.
        from_port_name (str): Name of the output port on the embedded FMU.
        container_port_name (str): Exposed name on the container. If empty,
            defaults to `from_port_name`.

    Raises:
        FMUContainerError: If the FMU or the port does not exist, if the port
            causality is not `"output"` or `"local"`, or if the exposed name is
            already used.
    """
    if not container_port_name:  # empty is allowed
        container_port_name = from_port_name

    try:
        cport_from = ContainerPort(self.get_fmu(from_fmu_filename), from_port_name)
    except FMUContainerError as e:
        raise FMUContainerError(f"Cannot add output '{container_port_name}': {e.reason}") from e

    if cport_from.port.causality not in ("output", "local"):  # check causality
        raise FMUContainerError(f"Cannot use {cport_from} as an output of the container: its causality is "
                                f"'{cport_from.port.causality}'.")
    if not cport_from.is_exposable("OUTPUT"):
        return

    if container_port_name in self.outputs:
        raise FMUContainerError(f"The output '{container_port_name}' of the container is already connected to "
                                f"port {self.outputs[container_port_name].label}.")

    logger.debug(f"{cport_from} is an output of the container.")
    self.mark_ruled(cport_from, 'OUTPUT')
    self.outputs[container_port_name] = cport_from

add_reset_port(fmu)

Add the virtual container.reset input to an embedded FMU (option reset_ports).

When this input is true at the start of an internal step, the container resets the FMU and initializes it again at the current time; the input goes back to false at the end of the step. Its type is the Boolean of the container (fmi2Boolean or fmi3Boolean).

Parameters:

Name Type Description Default
fmu EmbeddedFMU

The embedded FMU.

required

Raises:

Type Description
FMUContainerError

If the FMU already has a port named container.reset.

Source code in fmu_manipulation_toolbox/container/builder.py
def add_reset_port(self, fmu: EmbeddedFMU):
    """Add the virtual `container.reset` input to an embedded FMU (option `reset_ports`).

    When this input is `true` at the start of an internal step, the container resets the FMU and initializes it
    again at the current time; the input goes back to `false` at the end of the step. Its type is the Boolean
    of the container (`fmi2Boolean` or `fmi3Boolean`).

    Args:
        fmu (EmbeddedFMU): The embedded FMU.

    Raises:
        FMUContainerError: If the FMU already has a port named `container.reset`.
    """
    if self.RESET_PORT in fmu.ports:
        raise FMUContainerError(f"FMU '{fmu.name}' has a port named '{self.RESET_PORT}': it cannot be embedded "
                                f"with the option reset_ports, which reserves this name.")
    port = EmbeddedFMUPort("boolean" if self.fmi_version == 2 else "boolean1", {
        "name": self.RESET_PORT,
        "valueReference": -1,   # no value reference in the FMU
        "causality": "input",
        "variability": "discrete",
        "start": "false",
        "description": f"Reset of the embedded FMU '{fmu.name}'",
    })
    port.is_reset = True
    fmu.ports[self.RESET_PORT] = port

add_start_value(fmu_filename, port_name, value)

Set a start value for a port of an embedded FMU.

The value is automatically converted to the appropriate type (float, int, bool, or string).

Parameters:

Name Type Description Default
fmu_filename str

Filename of the embedded FMU.

required
port_name str

Name of the port.

required
value str

Start value as a string (a Python bool, e.g. a JSON true, is accepted for a Boolean port).

required

Raises:

Type Description
FMUContainerError

If the FMU or the port does not exist, if the port type has no start value (binary, clock), or if the value cannot be converted to the port's type.

Source code in fmu_manipulation_toolbox/container/builder.py
def add_start_value(self, fmu_filename: str, port_name: str, value: str):
    """Set a start value for a port of an embedded FMU.

    The value is automatically converted to the appropriate type
    (float, int, bool, or string).

    Args:
        fmu_filename (str): Filename of the embedded FMU.
        port_name (str): Name of the port.
        value (str): Start value as a string (a Python `bool`, e.g. a JSON `true`, is accepted for a
            Boolean port).

    Raises:
        FMUContainerError: If the FMU or the port does not exist, if the port
            type has no start value (binary, clock), or if the value cannot be
            converted to the port's type.
    """

    try:
        cport = ContainerPort(self.get_fmu(fmu_filename), port_name)
    except FMUContainerError as e:
        raise FMUContainerError(f"Cannot set start value: {e.reason}") from e

    if cport.port.is_reset:
        raise FMUContainerError(f"Start value cannot be set on {cport}: it drives the reset of the FMU.")

    self.start_values[cport] = self.start_value_text(cport, value)

apply_terminal_parameters()

Give to the parameters of Configuration terminals the value of the connected Bus Simulation.

These variables are parameters: they cannot be linked. The value is propagated when it is known at build time, unless the user has set a start value.

Source code in fmu_manipulation_toolbox/container/builder.py
def apply_terminal_parameters(self):
    """Give to the parameters of Configuration terminals the value of the connected Bus Simulation.

    These variables are parameters: they cannot be linked. The value is propagated when it is known at build
    time, unless the user has set a start value.
    """
    for cport1, cport2 in self.terminal_parameters:
        if cport1.port.causality == "parameter" and cport2.port.causality != "parameter":
            target, source = cport1, cport2
        elif cport2.port.causality == "parameter" and cport1.port.causality != "parameter":
            target, source = cport2, cport1
        else:
            logger.debug(f"No value to propagate between {cport1} and port {cport2.label}.")
            continue

        if target in self.start_values:
            logger.debug(f"The start value of {target} is kept: port {source.label} is not propagated.")
        elif source.port.start_value is None:
            logger.warning(f"The value of {source} is known at runtime only: it is not propagated to port "
                           f"{target.label}.")
        else:
            logger.info(f"The start value of {target} is taken from port {source.label}: "
                        f"{source.port.start_value}.")
            self.add_start_value(target.fmu.name, target.port.name, source.port.start_value)

Warn about the input clocks of a link that will not tick together: they share their local variable.

Source code in fmu_manipulation_toolbox/container/builder.py
@staticmethod
def check_clocks_of_link(link: Link, scheduled_clocks: list[ContainerPort]):
    """Warn about the input clocks of a link that will not tick together: they share their local variable."""
    if not scheduled_clocks:
        logger.warning(f"No clock drives {', '.join(str(cport) for cport in link.cport_to_list)}: "
                       f"they will never tick.")

    declared = {(cport.port.interval_decimal, cport.port.shift_decimal or "0") for cport in scheduled_clocks
                if cport.port.interval_decimal is not None}
    if len(declared) > 1:
        logger.warning(f"The ticks of {', '.join(str(cport) for cport in scheduled_clocks)} must match, "
                       f"but their intervals and shifts differ.")

check_not_fed(cport, feeder)

Refuse a second feeder (container input or link) for an input of an embedded FMU.

Clocks are excepted: LS-BUS connects input clocks together.

Raises:

Type Description
FMUContainerError

If the input is already fed.

Source code in fmu_manipulation_toolbox/container/builder.py
def check_not_fed(self, cport: ContainerPort, feeder: str):
    """Refuse a second feeder (container input or link) for an input of an embedded FMU.

    Clocks are excepted: LS-BUS connects input clocks together.

    Raises:
        FMUContainerError: If the input is already fed.
    """
    if cport.port.type_name != "clock" and cport in self.input_feeders:
        raise FMUContainerError(f"{cport} is already fed by {self.input_feeders[cport]}: "
                                f"it cannot also be fed by {feeder}.")

check_sequential_order(fmu_rank)

Warn when the sequential scheduling steps the Co-Simulation FMUs against the order of their links.

In sequential mode, the Co-Simulation FMUs step one after the other in the order of the configuration, each one with the outputs just computed by the previous ones: an FMU placed before an FMU it depends on gets the outputs of the previous step. The links inside a loop are left out (one of them goes backwards whatever the order), as are the Model-Exchange FMUs, which step together after the Co-Simulation FMUs.

Parameters:

Name Type Description Default
fmu_rank dict[str, int]

Index of each embedded FMU in container.txt, by FMU name.

required
Source code in fmu_manipulation_toolbox/container/builder.py
def check_sequential_order(self, fmu_rank: dict[str, int]) -> None:
    """Warn when the sequential scheduling steps the Co-Simulation FMUs against the order of their links.

    In sequential mode, the Co-Simulation FMUs step one after the other in the order of the configuration, each
    one with the outputs just computed by the previous ones: an FMU placed before an FMU it depends on gets the
    outputs of the previous step. The links inside a loop are left out (one of them goes backwards whatever the
    order), as are the Model-Exchange FMUs, which step together after the Co-Simulation FMUs.

    Args:
        fmu_rank (dict[str, int]): Index of each embedded FMU in `container.txt`, by FMU name.
    """
    cs_rank = {name: rank for name, rank in fmu_rank.items() if not self.involved_fmu[name].is_me}
    successors = self._link_graph(self.links.values(), cs_rank)

    def reachable(start: int) -> set[int]:
        seen: set[int] = set()
        stack = [start]
        while stack:
            for target in successors[stack.pop()]:
                if target not in seen:
                    seen.add(target)
                    stack.append(target)
        return seen

    # Predecessors of each FMU outside of its loops: a source reachable from its target is in a loop with it.
    reachable_from = {rank: reachable(rank) for rank in successors}
    predecessors: dict[int, set[int]] = {rank: set() for rank in successors}
    for source, targets in successors.items():
        for target in targets:
            if source not in reachable_from[target]:
                predecessors[target].add(source)

    if any(source > target for target, sources in predecessors.items() for source in sources):
        # The FMUs of a loop wait for the predecessors of the whole loop.
        waiting_for = {rank: set().union(*(predecessors[other] for other in successors
                                           if other == rank or rank in reachable_from[other] and
                                           other in reachable_from[rank]))
                       for rank in successors}
        order: list[int] = []
        while len(order) < len(waiting_for):
            order.append(min(rank for rank, sources in waiting_for.items()
                             if rank not in order and sources.issubset(order)))
        name_of = {rank: name for name, rank in cs_rank.items()}
        logger.warning(f"Sequential mode: the order of the configuration does not match the topological order "
                       f"of the links. Topological order of the Co-Simulation FMUs: "
                       f"{', '.join(name_of[rank] for rank in order)}.")

default_step_size()

Compute the default step size from embedded FMUs.

The step size is the least common multiple of the step sizes of the FMUs that impose their step (fixedInternalStepSize of FMI-3, or no variable step size), computed exactly (0.1 and 0.25 give 0.5). Otherwise, returns the largest step size. FMUs without step size are ignored; without any step size, the default is 0.1 s.

Returns:

Name Type Description
float float

Computed step size in seconds.

Source code in fmu_manipulation_toolbox/container/builder.py
def default_step_size(self) -> float:
    """Compute the default step size from embedded FMUs.

    The step size is the least common multiple of the step sizes of the FMUs that
    impose their step (`fixedInternalStepSize` of FMI-3, or no variable step size),
    computed exactly (`0.1` and `0.25` give `0.5`). Otherwise, returns the largest step size.
    FMUs without step size are ignored; without any step size, the default is 0.1 s.

    Returns:
        float: Computed step size in seconds.
    """
    step_sizes = {fmu.name: fmu.step_size for fmu in self.involved_fmu.values() if fmu.step_size}
    for name, step_size in list(step_sizes.items()):
        if step_size < 0:
            logger.warning(f"FMU '{name}' declares a negative step size ({step_size}s): ignored.")
            del step_sizes[name]

    step_size = deduce_step_size([
        (step_sizes[fmu.name], not fmu.imposes_step_size)
        for fmu in self.involved_fmu.values() if fmu.name in step_sizes])
    if step_size is not None:
        return step_size

    logger.warning(f"Defaulting to the step size {DEFAULT_STEP_SIZE}s.")
    return DEFAULT_STEP_SIZE

drop_port(from_fmu_filename, from_port_name)

Explicitly ignore an output port of an embedded FMU.

Prevents the port from being auto-exposed or flagged as unconnected.

Parameters:

Name Type Description Default
from_fmu_filename str

Filename of the embedded FMU.

required
from_port_name str

Name of the output port to drop.

required

Raises:

Type Description
FMUContainerError

If the FMU or the port does not exist, or if the port causality is not "output".

Source code in fmu_manipulation_toolbox/container/builder.py
def drop_port(self, from_fmu_filename: str, from_port_name: str):
    """Explicitly ignore an output port of an embedded FMU.

    Prevents the port from being auto-exposed or flagged as unconnected.

    Args:
        from_fmu_filename (str): Filename of the embedded FMU.
        from_port_name (str): Name of the output port to drop.

    Raises:
        FMUContainerError: If the FMU or the port does not exist, or if the
            port causality is not `"output"`.
    """

    try:
        cport_from = ContainerPort(self.get_fmu(from_fmu_filename), from_port_name)
    except FMUContainerError as e:
        raise FMUContainerError(f"Cannot drop port: {e.reason}") from e

    if not cport_from.port.causality == "output":  # check causality
        raise FMUContainerError(f"Cannot drop {cport_from}: its causality is '{cport_from.port.causality}', not "
                                f"'output'.")

    logger.debug(f"{cport_from} is dropped.")
    self.mark_ruled(cport_from, 'DROP')

get_fmu(fmu_filename, name=None)

Load an embedded FMU from the FMU directory.

An embedded FMU is designated by its name: its filename, or the name of an instance when the same FMU is embedded several times. Each instance is a distinct embedded FMU, extracted in its own directory of the container. If the FMU has already been loaded, returns the cached instance.

Parameters:

Name Type Description Default
fmu_filename str

Filename of the FMU (e.g. "model.fmu").

required
name str | None

Name of the instance (e.g. "model-1.fmu"). Defaults to the filename. Once loaded, the instance is designated by this name in every rule.

None

Returns:

Name Type Description
EmbeddedFMU EmbeddedFMU

The loaded and analysed FMU.

Raises:

Type Description
FMUContainerError

If the FMU cannot be loaded, or if name already designates another file.

Source code in fmu_manipulation_toolbox/container/builder.py
def get_fmu(self, fmu_filename: str, name: str | None = None) -> EmbeddedFMU:
    """Load an embedded FMU from the FMU directory.

    An embedded FMU is designated by its name: its filename, or the name of an instance when the same FMU is
    embedded several times. Each instance is a distinct embedded FMU, extracted in its own directory of the
    container. If the FMU has already been loaded, returns the cached instance.

    Args:
        fmu_filename (str): Filename of the FMU (e.g. `"model.fmu"`).
        name (str | None): Name of the instance (e.g. `"model-1.fmu"`). Defaults to the filename. Once loaded,
            the instance is designated by this name in every rule.

    Returns:
        EmbeddedFMU: The loaded and analysed FMU.

    Raises:
        FMUContainerError: If the FMU cannot be loaded, or if `name` already designates another file.
    """
    fmu_name = Path(name or fmu_filename).name
    if fmu_name in self.involved_fmu:
        fmu = self.involved_fmu[fmu_name]
        if name is not None:  # a rule designates the FMU by name only: no file to compare with
            loaded_from = Path(fmu.fmu.fmu_filename).resolve()
            if loaded_from != (self.fmu_directory / fmu_filename).resolve():
                raise FMUContainerError(f"'{fmu_name}' already designates '{fmu.fmu.fmu_filename}': "
                                        f"it cannot also designate '{fmu_filename}'.")
        return fmu

    try:
        fmu = EmbeddedFMU(self.fmu_directory / fmu_filename, name=fmu_name)
    except (FMUContainerError, FMUError) as e:
        raise FMUContainerError(f"Cannot load '{fmu_filename}': {e}") from e

    if not fmu.fmi_version == self.fmi_version:
        logger.warning(f"FMU '{fmu.name}' (FMI-{fmu.fmi_version}) is embedded in an FMI-{self.fmi_version} "
                       f"container.")
    if self.reset_ports:
        self.add_reset_port(fmu)
    self.involved_fmu[fmu.name] = fmu

    if fmu.is_me:
        fmu_type = "ME"
        self.have_me = True
    else:
        fmu_type = "CS"

    logger.info(f"Involved FMU #{len(self.involved_fmu)}: {fmu}, {fmu_type}.")

    return fmu

initialization_order(fmu_rank)

Order in which the embedded FMUs propagate their links during the initialization.

Topological sort of the graph of the embedded FMUs, with an edge from the FMU of an output to the FMU of an input it is linked to. The clocks, the clocked variables and the container.reset triggers make no edge (they are not propagated during the initialization). Between independent FMUs, the order of the configuration (fmu_rank) decides. A loop is cut before its first FMU in the configuration, which is then initialized without the values computed by the loop: a warning is logged.

Parameters:

Name Type Description Default
fmu_rank dict[str, int]

Index of each embedded FMU in container.txt, by FMU name.

required

Returns:

Type Description
list[int]

list[int]: The indexes of every embedded FMU, in initialization order.

Source code in fmu_manipulation_toolbox/container/builder.py
def initialization_order(self, fmu_rank: dict[str, int]) -> list[int]:
    """Order in which the embedded FMUs propagate their links during the initialization.

    Topological sort of the graph of the embedded FMUs, with an edge from the FMU of an output to the FMU of an
    input it is linked to. The clocks, the clocked variables and the `container.reset` triggers make no edge
    (they are not propagated during the initialization). Between independent FMUs, the order of the
    configuration (`fmu_rank`) decides. A loop is cut before its first FMU in the configuration, which is then
    initialized without the values computed by the loop: a warning is logged.

    Args:
        fmu_rank (dict[str, int]): Index of each embedded FMU in `container.txt`, by FMU name.

    Returns:
        list[int]: The indexes of every embedded FMU, in initialization order.
    """
    successors = self._link_graph(self.links.values(), fmu_rank)

    nb_predecessors = {rank: 0 for rank in successors}
    for targets in successors.values():
        for target in targets:
            nb_predecessors[target] += 1

    name_of = {rank: name for name, rank in fmu_rank.items()}
    order: list[int] = []
    remaining = set(successors)
    while remaining:
        ready = [rank for rank in remaining if nb_predecessors[rank] == 0]
        if ready:
            rank = min(ready)
        else:                                                # a loop: cut before its first FMU
            rank = min(remaining)
            logger.warning(f"Loop of links through the embedded FMU '{name_of[rank]}': it is initialized "
                           f"without the values its inputs get from the loop.")
        order.append(rank)
        remaining.remove(rank)
        for target in successors[rank]:
            nb_predecessors[target] -= 1
    return order

make_fmu(fmu_filename, step_size=None, debug=False, mt=False, profiling=False, sequential=False, ts_multiplier=False, datalog=False, mt_threshold=MT_THRESHOLD)

Build the FMU Container archive.

Generates the modelDescription.xml, the container.txt runtime configuration, and packages everything into a .fmu zip archive.

Parameters:

Name Type Description Default
fmu_filename str | Path

Output filename for the container.

required
step_size float | None

Internal time step in seconds. If None, deduced from the embedded FMUs.

None
debug bool

Keep intermediate build artifacts.

False
mt bool

Enable multithreaded mode.

False
profiling bool

Enable profiling mode.

False
sequential bool

Use sequential scheduling.

False
ts_multiplier bool

Add a TS_MULTIPLIER input port.

False
datalog bool

Generate a datalog configuration.

False
mt_threshold float

Multithreaded mode: the embedded FMUs whose mean step takes at least this duration, in seconds, get a worker thread (see MT_THRESHOLD).

MT_THRESHOLD
Source code in fmu_manipulation_toolbox/container/builder.py
def make_fmu(self, fmu_filename: str | Path, step_size: float | None = None, debug=False, mt=False,
             profiling=False, sequential=False, ts_multiplier=False, datalog=False,
             mt_threshold: float = MT_THRESHOLD):
    """Build the FMU Container archive.

    Generates the `modelDescription.xml`, the `container.txt` runtime
    configuration, and packages everything into a `.fmu` zip archive.

    Args:
        fmu_filename (str | Path): Output filename for the container.
        step_size (float | None): Internal time step in seconds. If `None`,
            deduced from the embedded FMUs.
        debug (bool): Keep intermediate build artifacts.
        mt (bool): Enable multithreaded mode.
        profiling (bool): Enable profiling mode.
        sequential (bool): Use sequential scheduling.
        ts_multiplier (bool): Add a `TS_MULTIPLIER` input port.
        datalog (bool): Generate a datalog configuration.
        mt_threshold (float): Multithreaded mode: the embedded FMUs whose mean step takes at least this
            duration, in seconds, get a worker thread (see `MT_THRESHOLD`).
    """
    if mt_threshold < 0:
        raise FMUContainerError(f"The threshold of the multithreaded mode cannot be negative: {mt_threshold}.")
    if isinstance(fmu_filename, str):
        fmu_filename = Path(fmu_filename)

    self.apply_terminal_parameters()
    xcp.check_ports(self)

    if step_size is None:
        logger.info("The step size will be deduced from the embedded FMUs.")
        step_size = self.default_step_size()
    self.sanity_check(step_size)

    if mt and len(self.involved_fmu) < 2:
        logger.error("The multi-threaded mode needs several FMUs: the container runs in mono-threaded mode.")
        mt = False

    logger.info(f"Building '{fmu_filename}' with a step size of {step_size}s.")

    base_directory = self.fmu_directory / fmu_filename.with_suffix('')
    resources_directory = self.make_fmu_skeleton(base_directory)

    # Allocated again at each build: the rules are never modified by a build.
    links = [*self.links.values(), *self.scheduled_clock_links()]
    layout = ContainerLayout.allocate(links, self.inputs, self.outputs,
                                      nb_profiling=len(self.involved_fmu) if profiling else 0,
                                      fmi_version=self.fmi_version)

    self.make_fmu_xml(base_directory / "modelDescription.xml", step_size, profiling, ts_multiplier, layout)
    with open(resources_directory / "container.txt", "w", encoding=ENCODING) as txt_file:
        self.make_fmu_txt(txt_file, step_size, mt, profiling, sequential, layout, mt_threshold=mt_threshold)

    if datalog:
        with open(resources_directory / "datalog.txt", "w", encoding=ENCODING) as datalog_file:
            self.make_datalog(datalog_file, layout)

    xcp.write_manifest(self, base_directory, list(self.get_platforms(verbose=False)))

    self.make_fmu_package(base_directory, fmu_filename)
    if not debug:
        self.make_fmu_cleanup(base_directory)

make_fmu_xml(xml_filename, step_size, profiling, ts_multiplier, layout)

Build the container modelDescription.xml and write it (UTF-8, see ModelDescription.save).

The document is built as an ElementTree, so that names and descriptions coming from the embedded FMUs are escaped. FMI-2 <Unknown index> entries are computed from the actual position of the output variables. The value references come from layout.

Source code in fmu_manipulation_toolbox/container/builder.py
def make_fmu_xml(self, xml_filename: Path, step_size: float, profiling: bool, ts_multiplier: bool,
                 layout: ContainerLayout):
    """Build the container `modelDescription.xml` and write it (UTF-8, see `ModelDescription.save`).

    The document is built as an ElementTree, so that names and descriptions
    coming from the embedded FMUs are escaped. FMI-2 `<Unknown index>`
    entries are computed from the actual position of the output variables.
    The value references come from `layout`.
    """
    timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
    guid = str(uuid.uuid4())
    embedded_fmu = ", ".join([fmu_name for fmu_name in self.involved_fmu])
    try:
        author = getpass.getuser()
    except OSError:
        author = "Unspecified"

    capabilities = {}
    for capability in EmbeddedFMU.capability_list:
        capabilities[capability] = "false"
        for fmu in self.involved_fmu.values():
            if fmu.capabilities[capability] == "true":
                capabilities[capability] = "true"

    first_fmu = next(iter(self.involved_fmu.values()))
    start_time = self.start_time
    if start_time is None:
        start_time = first_fmu.start_time
        logger.info(f"Start time: {start_time}s (deduced from '{first_fmu.name}').")
    else:
        logger.info(f"Start time: {start_time}s.")

    stop_time = self.stop_time
    if stop_time is None:
        stop_time = first_fmu.stop_time
        logger.info(f"Stop time: {stop_time}s (deduced from '{first_fmu.name}').")
    else:
        logger.info(f"Stop time: {stop_time}s.")

    root = ET.Element("fmiModelDescription", {
        "fmiVersion": f"{self.fmi_version}.0",
        "modelName": self.identifier,
        "generationTool": f"FMUContainer-{tool_version}",
        "generationDateAndTime": timestamp,
        "guid" if self.fmi_version == 2 else "instantiationToken": guid,
        "description": f"FMUContainer with {embedded_fmu}",
        "author": author,
        "license": "Proprietary",
        "copyright": "See Embedded FMU's copyrights.",
        "variableNamingConvention": "structured",
    })

    if self.fmi_version == 2:
        cosimulation = {
            "modelIdentifier": self.identifier,
            "canHandleVariableCommunicationStepSize": "true",
            "canBeInstantiatedOnlyOncePerProcess": capabilities['canBeInstantiatedOnlyOncePerProcess'],
            "canNotUseMemoryManagementFunctions": "true",
            "canGetAndSetFMUstate": "false",
            "canSerializeFMUstate": "false",
            "providesDirectionalDerivative": "false",
            "needsExecutionTool": capabilities['needsExecutionTool'],
        }
    else:
        cosimulation = {
            "modelIdentifier": self.identifier,
            "canHandleVariableCommunicationStepSize": "true",
            "fixedInternalStepSize": str(step_size),    # TS_MULTIPLIER keeps the steps on this grid
            "canBeInstantiatedOnlyOncePerProcess": capabilities['canBeInstantiatedOnlyOncePerProcess'],
            "canNotUseMemoryManagementFunctions": "true",
            "canGetAndSetFMUState": "false",
            "canSerializeFMUState": "false",
            "providesDirectionalDerivatives": "false",
            "providesAdjointDerivatives": "false",
            "providesPerElementDependencies": "false",
            "providesEvaluateDiscreteStates": "false",
            "hasEventMode": "false",
            "needsExecutionTool": capabilities['needsExecutionTool'],
        }
    ET.SubElement(root, "CoSimulation", cosimulation)

    log_categories = ET.SubElement(root, "LogCategories")
    ET.SubElement(log_categories, "Category", {"name": "Info", "description": "Info log messages."})
    ET.SubElement(log_categories, "Category", {"name": "Error", "description": "Error log messages."})

    default_experiment = {"stepSize": str(step_size)}
    if start_time is not None:
        default_experiment["startTime"] = str(start_time)
    if stop_time is not None:
        default_experiment["stopTime"] = str(stop_time)
    ET.SubElement(root, "DefaultExperiment", default_experiment)

    model_variables = ET.SubElement(root, "ModelVariables")
    if self.fmi_version == 2:
        time = ET.SubElement(model_variables, "ScalarVariable",
                             {"valueReference": str(layout.time), "name": "time", "causality": "independent"})
        ET.SubElement(time, "Real")
    else:
        ET.SubElement(model_variables, "Float64",
                      {"valueReference": str(layout.time), "name": "time", "causality": "independent"})

    def add_variable(variable: ET.Element | None) -> ET.Element | None:
        if variable is not None:
            model_variables.append(variable)
        return variable

    logger.debug(f"Value reference of the time: {layout.time}.")

    vr_ts_multiplier = layout.ts_multiplier
    if ts_multiplier:
        logger.debug(f"Value reference of the TS multiplier: {vr_ts_multiplier}.")
        port = EmbeddedFMUPort("integer32", {"valueReference": vr_ts_multiplier,
                                             "name": "container.ts_multiplier",
                                             "causality": "input",
                                             "description": "Timestep multiplier",
                                             "variability": "discrete",
                                             "start": 1,
                                             "initial": "exact"})
        add_variable(port.xml(vr_ts_multiplier, fmi_version=self.fmi_version))

    vr_solver = layout.solver
    if self.have_me:
        logger.debug(f"Value reference of the solver configuration: {vr_solver}.")
        port = EmbeddedFMUPort("integer32", {"valueReference": vr_solver,
                                             "name": "container.solver",
                                             "causality": "input",
                                             "description": "0:Euler, 1: RK4",
                                             "variability": "discrete",
                                             "start": 0,
                                             "initial": "exact"})
        add_variable(port.xml(vr_solver, fmi_version=self.fmi_version))

    if profiling:
        for fmu, vr in zip(self.involved_fmu.values(), layout.profiling, strict=True):
            port = EmbeddedFMUPort("real64", {"valueReference": vr,
                                    "name": f"container.{fmu.id}.rt_ratio",
                                    "description": f"RT ratio for embedded FMU '{fmu.name}'"})
            add_variable(port.xml(vr, fmi_version=self.fmi_version))

    nb_clocks = 0
    for link in layout.links:
        if link.cport_from:
            add_variable(link.cport_from.port.xml(layout.links[link], name=link.name, causality='local',
                                                  fmi_version=self.fmi_version))
        else:
            # LS-BUS allow Clock generated by fmi-importer
            port = EmbeddedFMUPort("Clock",
                                   {"name": "", "valueReference": -1, "intervalVariability": "triggered"},
                                   fmi_version=3)
            add_variable(port.xml(layout.links[link], name=f"container.clock{nb_clocks}", causality='local',
                                  fmi_version=self.fmi_version))
            nb_clocks += 1

    for input_port_name, input_port in self.inputs.items():
        # Get Start and XML from first connected input
        start = self.start_values.get(input_port.cport_list[0], None)
        causality = None
        if self.fmi_version == 2 and input_port.cport_list[0].port.causality == "structuralParameter":
            causality = "parameter"     # set by the container in Configuration Mode
        add_variable(input_port.cport_list[0].port.xml(layout.inputs[input_port_name], name=input_port_name,
                                                       causality=causality, start=start,
                                                       fmi_version=self.fmi_version))

    outputs = []    # (value reference of a container output, its variable element), for <ModelStructure>
    for output_port_name, output_port in self.outputs.items():
        conversion = layout.output_conversions.get(output_port_name)
        variable = add_variable(output_port.port.xml(layout.outputs[output_port_name], name=output_port_name,
                                                     fmi_version=self.fmi_version,
                                                     type_name=conversion.type_name if conversion else None))
        if variable is not None:
            outputs.append((layout.outputs[output_port_name], variable))

    # FMI-2 §2.2.8, FMI-3 §2.4.8: the initial unknowns are the outputs with initial="calculated" or "approx". An
    # output that copies initial="exact" (and its start value) from its embedded FMU is not one.
    initial_unknowns = [(vr, variable) for vr, variable in outputs if self._initial_of(variable) != "exact"]
    model_structure = ET.SubElement(root, "ModelStructure")
    if self.fmi_version == 2:
        # FMI-2 §2.2.8: <Unknown index> is the 1-based position of the variable in <ModelVariables>.
        positions = {id(variable): index for index, variable in enumerate(model_variables, start=1)}
        for section, entries in (("Outputs", outputs), ("InitialUnknowns", initial_unknowns)):
            if entries:
                unknowns = ET.SubElement(model_structure, section)
                for _, variable in entries:
                    ET.SubElement(unknowns, "Unknown", {"index": str(positions[id(variable)])})
    else:
        for tag, entries in (("Output", outputs), ("InitialUnknown", initial_unknowns)):
            for output_vr, _ in entries:
                ET.SubElement(model_structure, tag, {"valueReference": str(output_vr)})

    ModelDescription(root).save(xml_filename)

reset_input_name(fmu)

Name under which the container exposes the container.reset input of fmu.

Source code in fmu_manipulation_toolbox/container/builder.py
def reset_input_name(self, fmu: EmbeddedFMU) -> str:
    """Name under which the container exposes the `container.reset` input of `fmu`."""
    return f"container.{fmu.id}.reset"

sanity_check(step_size)

Validate the container configuration before building.

Warns about step size mismatches and unconnected ports.

Parameters:

Name Type Description Default
step_size float

The container's internal step size.

required
Source code in fmu_manipulation_toolbox/container/builder.py
def sanity_check(self, step_size: float):
    """Validate the container configuration before building.

    Warns about step size mismatches and unconnected ports.

    Args:
        step_size (float): The container's internal step size.
    """
    for fmu in self.involved_fmu.values():
        if fmu.step_size and fmu.imposes_step_size:
            ts_ratio = _exact(step_size) / _exact(fmu.step_size)   # exact: 0.3 / 0.1 is 3
            logger.debug(f"Container step size {step_size}s = {fmu.step_size}s x {float(ts_ratio)} for "
                         f"'{fmu.name}'.")
            if ts_ratio < 1:
                logger.warning(f"The step size of the container ({step_size}s) is lower than the one of FMU "
                               f"'{fmu.name}' ({fmu.step_size}s).")
            if ts_ratio.denominator != 1:
                logger.warning(f"The step size of the container ({step_size}s) should be a multiple of the one of "
                               f"FMU "
                               f"'{fmu.name}' ({fmu.step_size}s).")
        for port_name, fmu_port in fmu.ports.items():
            if fmu_port.is_fmi2_aggregate:
                continue
            cport = ContainerPort(fmu, port_name)
            if cport not in self.rules:
                if cport.port.is_reset:
                    logger.warning(f"Reset of FMU '{fmu.name}' is neither linked nor exposed: "
                                   f"the FMU will never be reset.")
                elif cport.port.causality == 'input' and cport.port.type_name == "clock" \
                        and cport.port.interval_variability in TIME_BASED_CLOCKS:
                    logger.info(f"Input clock {cport.label} is not linked: the container schedules it.")
                elif cport.port.causality == 'input':
                    logger.error(f"Input {cport.label} is not connected.")
                if cport.port.causality == 'output':
                    logger.warning(f"Output {cport.label} is not connected.")

Links of the time-based input clocks that are neither linked nor exposed (a clock cannot be exposed).

Each one gets a link without source, like input clocks linked together: the container schedules it from its interval and shift. Built again at each build, the rules are not modified.

Source code in fmu_manipulation_toolbox/container/builder.py
def scheduled_clock_links(self) -> list[Link]:
    """Links of the time-based input clocks that are neither linked nor exposed (a clock cannot be exposed).

    Each one gets a link without source, like input clocks linked together: the container schedules it from its
    interval and shift. Built again at each build, the rules are not modified.
    """
    links = []
    for fmu in self.involved_fmu.values():
        for port_name, fmu_port in fmu.ports.items():
            if fmu_port.type_name == "clock" and fmu_port.causality == "input" \
                    and fmu_port.interval_variability in TIME_BASED_CLOCKS:
                cport = ContainerPort(fmu, port_name)
                if cport not in self.rules:
                    links.append(Link(cport))
    return links

start_value_text(cport, value) staticmethod

The start value value of cport, checked and formatted for container.txt.

Raises:

Type Description
FMUContainerError

If the port type has no start value (binary, clock), or if the value cannot be converted to the port's type.

Source code in fmu_manipulation_toolbox/container/builder.py
@staticmethod
def start_value_text(cport: ContainerPort, value) -> str:
    """The start value `value` of `cport`, checked and formatted for `container.txt`.

    Raises:
        FMUContainerError: If the port type has no start value (binary, clock), or if the value cannot be
            converted to the port's type.
    """
    if isinstance(value, bool):     # JSON true/false: str() would give 'True'/'False'
        value = "true" if value else "false"

    # Check dimensions
    value_tokens = str(value).split(' ')
    if not len(value_tokens) == cport.port.size():
        raise FMUContainerError(f"The start value of {cport} does not match its dimension "
                                f"{cport.port.size()}.")

    # Check type
    for token in value_tokens:
        try:
            if cport.port.type_name.startswith('real'):
                float(token)
            elif cport.port.type_name.startswith('integer') or  cport.port.type_name.startswith('uinteger'):
                int(token)
            elif cport.port.type_name.startswith('boolean'):
                if token not in ("true", "false", "0", "1"):
                    raise ValueError(f"Invalid boolean value: '{token}'")
            elif cport.port.type_name == 'string':
                pass
            else:
                raise FMUContainerError(f"Start value cannot be set on {cport} of type '{cport.port.type_name}'.")
        except ValueError:
            raise FMUContainerError(f"Start value of {cport} is not conforming to the format of "
                                    f"'{cport.port.type_name}'.") from None

    # Format is different for string
    if cport.port.type_name == 'string':
        value = "\n" + "\n".join(value_tokens)

    return value

FMUContainerError

Bases: Exception

Exception raised for errors during FMU Container operations.

Attributes:

Name Type Description
reason str

Human-readable description of the error.

Source code in fmu_manipulation_toolbox/container/errors.py
class FMUContainerError(Exception):
    """Exception raised for errors during FMU Container operations.

    Attributes:
        reason (str): Human-readable description of the error.
    """

    def __init__(self, reason: str):
        self.reason = reason

    def __repr__(self):
        return f"{self.reason}"

FMUIOList

Tracks the I/O mapping between the container and its embedded FMUs.

Organizes inputs, outputs, and start values by type and FMU, supporting both regular and clocked variables. Used to generate the container.txt runtime configuration file.

Attributes:

Name Type Description
vr_table ValueReferenceTable

Reference table for VR lookups.

inputs IOReferences

Nested mapping [type][fmu_name][clock_vr] → list of IOReference (clock_vr is None for the variables without clock).

outputs IOReferences

Same as inputs, for the outputs of the embedded FMUs.

start_values defaultdict[str, defaultdict[str, list[tuple[int, int, int, str]]]]

Mapping [type][fmu_name] → list of (fmu_vr, dim, reset, value) tuples.

Source code in fmu_manipulation_toolbox/container/txt.py
class FMUIOList:
    """Tracks the I/O mapping between the container and its embedded FMUs.

    Organizes inputs, outputs, and start values by type and FMU, supporting
    both regular and clocked variables. Used to generate the `container.txt`
    runtime configuration file.

    Attributes:
        vr_table (ValueReferenceTable): Reference table for VR lookups.
        inputs: Nested mapping `[type][fmu_name][clock_vr]` → list of
            [IOReference][fmu_manipulation_toolbox.container.IOReference]
            (`clock_vr` is `None` for the variables without clock).
        outputs: Same as `inputs`, for the outputs of the embedded FMUs.
        start_values: Mapping `[type][fmu_name]` → list of
            `(fmu_vr, dim, reset, value)` tuples.
    """

    def __init__(self, vr_table: ValueReferenceTable):
        self.vr_table = vr_table
        # [type][fmu][clock_vr] -> [IOReference]
        self.inputs: IOReferences = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
        self.nb_clocked_inputs: defaultdict[str, defaultdict[str, int]] = defaultdict(lambda: defaultdict(lambda: 0))
        # [type][fmu][clock_vr] -> [IOReference]
        self.outputs: IOReferences = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
        self.nb_clocked_outputs: defaultdict[str, defaultdict[str, int]] = defaultdict(lambda: defaultdict(lambda: 0))
        # [type][fmu] -> [(fmu_vr, dim, reset, value)]
        self.start_values: defaultdict[str, defaultdict[str, list[tuple[int, int, int, str]]]] = \
            defaultdict(lambda: defaultdict(list))

    def add_input(self, cport: ContainerPort, local_vr: int):
        """Register an input mapping for an embedded FMU port.

        Args:
            cport (ContainerPort): The embedded FMU input port.
            local_vr (int): The local value reference in the container.
        """
        self._add("input", self.inputs, self.nb_clocked_inputs, cport, local_vr)

    def add_output(self, cport: ContainerPort, local_vr: int):
        """Register an output mapping for an embedded FMU port.

        Args:
            cport (ContainerPort): The embedded FMU output port.
            local_vr (int): The local value reference in the container.
        """
        self._add("output", self.outputs, self.nb_clocked_outputs, cport, local_vr)

    def _add(self, direction: str, references, nb_clocked, cport: ContainerPort, local_vr: int):
        if cport.port.clock is None:
            clock = None
        else:
            try:
                clock = self.vr_table.get_local_clock(cport)
            except KeyError:
                logger.error(f"Cannot expose the clocked {direction} {cport.label}.")
                return
            nb_clocked[cport.port.type_name][cport.fmu.name] += 1

        local_offset = self.vr_table.vr_to_local[local_vr]
        references_of_fmu = references[cport.port.type_name][cport.fmu.name][clock]
        if cport.port.is_fmi2_aggregate:
            # FMI-2 array aggregate: one exchange per scalar element, with the value reference of each element.
            references_of_fmu.extend(IOReference(local_offset + k, 1, vr) for k, vr in enumerate(cport.port.vrs))
        else:
            references_of_fmu.append(IOReference(local_offset, cport.port.size(), cport.port.vr))

    def add_start_value(self, cport: ContainerPort, value: str):
        """Register a start value for an embedded FMU port.

        Args:
            cport (ContainerPort): The embedded FMU port.
            value (str): The start value.
        """
        # <RESET>: 2 = structural parameter, set in Configuration Mode; 1 = input, set again in Initialization Mode
        if cport.port.causality == "structuralParameter":
            reset = 2
        else:
            reset = 1 if cport.port.causality == "input" else 0
        if cport.port.type_name.startswith("boolean"):
            if value == "true" or value == "1":
                value = "1"
            else:
                value = "0"

        if cport.port.is_fmi2_aggregate:
            tokens = str(value).split(' ')
            if len(tokens) == 1:
                tokens = tokens * len(cport.port.vrs)
            for vr, token in zip(cport.port.vrs, tokens, strict=False):
                self.start_values[cport.port.type_name][cport.fmu.name].append((vr, 1, reset, token))
        else:
            self.start_values[cport.port.type_name][cport.fmu.name].append(
                (cport.port.vr, cport.port.size(), reset, value))

    def write_txt(self, fmu_name: str, txt_file: IO) -> None:
        """Write the I/O mapping for one FMU to the `container.txt` file.

        Args:
            fmu_name (str): Name of the embedded FMU.
            txt_file (IO): Writable text file handle.
        """
        self._write_io("Inputs", self.inputs, self.nb_clocked_inputs, fmu_name, txt_file)

        for type_name in START_VALUE_TYPES:
            print(f"# Start values of {fmu_name} - {type_name}: <FMU_VR> <DIM> <RESET> <VALUE>", file=txt_file)
            start_values = self.start_values[type_name][fmu_name]
            print(f"{len(start_values)} {sum(dim for _, dim, _, _ in start_values)}", file=txt_file)
            for vr, dim, reset, value in start_values:
                print(f"{vr} {dim} {reset} {value}", file=txt_file)

        self._write_io("Outputs", self.outputs, self.nb_clocked_outputs, fmu_name, txt_file)

    @staticmethod
    def _write_io(label: str, references, nb_clocked, fmu_name: str, txt_file: IO) -> None:
        for type_name in ALL_TYPES:
            references_of_fmu = references[type_name][fmu_name]
            print(f"# {label} of {fmu_name} - {type_name}: <LOCAL_OFFSET> <DIM> <FMU_VR>", file=txt_file)
            print(len(references_of_fmu[None]), file=txt_file)
            for io_ref in references_of_fmu[None]:
                print(io_ref, file=txt_file)
            if not type_name == "clock":
                print(f"# Clocked {label} of {fmu_name} - {type_name}: "
                      f"<FMU_VR_CLOCK> <n> <LOCAL_OFFSET> <DIM> <FMU_VR>", file=txt_file)
                print(f"{len(references_of_fmu)-1} {nb_clocked[type_name][fmu_name]}", file=txt_file)
                for clock, translation in references_of_fmu.items():
                    if clock is not None:
                        print(f"{clock} {len(translation)} {' '.join(str(io_ref) for io_ref in translation)}",
                              file=txt_file)

add_input(cport, local_vr)

Register an input mapping for an embedded FMU port.

Parameters:

Name Type Description Default
cport ContainerPort

The embedded FMU input port.

required
local_vr int

The local value reference in the container.

required
Source code in fmu_manipulation_toolbox/container/txt.py
def add_input(self, cport: ContainerPort, local_vr: int):
    """Register an input mapping for an embedded FMU port.

    Args:
        cport (ContainerPort): The embedded FMU input port.
        local_vr (int): The local value reference in the container.
    """
    self._add("input", self.inputs, self.nb_clocked_inputs, cport, local_vr)

add_output(cport, local_vr)

Register an output mapping for an embedded FMU port.

Parameters:

Name Type Description Default
cport ContainerPort

The embedded FMU output port.

required
local_vr int

The local value reference in the container.

required
Source code in fmu_manipulation_toolbox/container/txt.py
def add_output(self, cport: ContainerPort, local_vr: int):
    """Register an output mapping for an embedded FMU port.

    Args:
        cport (ContainerPort): The embedded FMU output port.
        local_vr (int): The local value reference in the container.
    """
    self._add("output", self.outputs, self.nb_clocked_outputs, cport, local_vr)

add_start_value(cport, value)

Register a start value for an embedded FMU port.

Parameters:

Name Type Description Default
cport ContainerPort

The embedded FMU port.

required
value str

The start value.

required
Source code in fmu_manipulation_toolbox/container/txt.py
def add_start_value(self, cport: ContainerPort, value: str):
    """Register a start value for an embedded FMU port.

    Args:
        cport (ContainerPort): The embedded FMU port.
        value (str): The start value.
    """
    # <RESET>: 2 = structural parameter, set in Configuration Mode; 1 = input, set again in Initialization Mode
    if cport.port.causality == "structuralParameter":
        reset = 2
    else:
        reset = 1 if cport.port.causality == "input" else 0
    if cport.port.type_name.startswith("boolean"):
        if value == "true" or value == "1":
            value = "1"
        else:
            value = "0"

    if cport.port.is_fmi2_aggregate:
        tokens = str(value).split(' ')
        if len(tokens) == 1:
            tokens = tokens * len(cport.port.vrs)
        for vr, token in zip(cport.port.vrs, tokens, strict=False):
            self.start_values[cport.port.type_name][cport.fmu.name].append((vr, 1, reset, token))
    else:
        self.start_values[cport.port.type_name][cport.fmu.name].append(
            (cport.port.vr, cport.port.size(), reset, value))

write_txt(fmu_name, txt_file)

Write the I/O mapping for one FMU to the container.txt file.

Parameters:

Name Type Description Default
fmu_name str

Name of the embedded FMU.

required
txt_file IO

Writable text file handle.

required
Source code in fmu_manipulation_toolbox/container/txt.py
def write_txt(self, fmu_name: str, txt_file: IO) -> None:
    """Write the I/O mapping for one FMU to the `container.txt` file.

    Args:
        fmu_name (str): Name of the embedded FMU.
        txt_file (IO): Writable text file handle.
    """
    self._write_io("Inputs", self.inputs, self.nb_clocked_inputs, fmu_name, txt_file)

    for type_name in START_VALUE_TYPES:
        print(f"# Start values of {fmu_name} - {type_name}: <FMU_VR> <DIM> <RESET> <VALUE>", file=txt_file)
        start_values = self.start_values[type_name][fmu_name]
        print(f"{len(start_values)} {sum(dim for _, dim, _, _ in start_values)}", file=txt_file)
        for vr, dim, reset, value in start_values:
            print(f"{vr} {dim} {reset} {value}", file=txt_file)

    self._write_io("Outputs", self.outputs, self.nb_clocked_outputs, fmu_name, txt_file)

IOReference dataclass

Exchange between a local variable of the container and a variable of an embedded FMU.

Source code in fmu_manipulation_toolbox/container/txt.py
@dataclass
class IOReference:
    """Exchange between a local variable of the container and a variable of an embedded FMU."""
    local_offset: int
    dim: int
    fmu_vr: int

    def __str__(self) -> str:
        return f"{self.local_offset} {self.dim} {self.fmu_vr}"

InvolvedFMU

Ordered collection of embedded FMUs behaving like a single mapping.

Internally the FMUs are split between Co-Simulation (fmu_cs) and Model-Exchange (fmu_me) FMUs, but the object exposes a dict-like interface (in, [], iteration, len(), values(), ...) that transparently combines both stores (CS first, then ME).

Source code in fmu_manipulation_toolbox/container/txt.py
class InvolvedFMU:
    """Ordered collection of embedded FMUs behaving like a single mapping.

    Internally the FMUs are split between Co-Simulation (`fmu_cs`) and
    Model-Exchange (`fmu_me`) FMUs, but the object exposes a dict-like
    interface (`in`, `[]`, iteration, `len()`, `values()`, ...) that
    transparently combines both stores (CS first, then ME).
    """

    def __init__(self):
        self.fmu_cs: OrderedDict[str, EmbeddedFMU] = OrderedDict()
        self.fmu_me: OrderedDict[str, EmbeddedFMU] = OrderedDict()

    def __contains__(self, fmu_name: str) -> bool:
        return fmu_name in self.fmu_cs or fmu_name in self.fmu_me

    def __getitem__(self, fmu_name: str) -> EmbeddedFMU:
        if fmu_name in self.fmu_cs:
            return self.fmu_cs[fmu_name]
        return self.fmu_me[fmu_name]

    def __setitem__(self, fmu_name: str, fmu: EmbeddedFMU) -> None:
        if fmu.is_me:
            self.fmu_me[fmu_name] = fmu
        else:
            self.fmu_cs[fmu_name] = fmu

    def __delitem__(self, fmu_name: str) -> None:
        if fmu_name in self.fmu_cs:
            del self.fmu_cs[fmu_name]
        else:
            del self.fmu_me[fmu_name]

    def __iter__(self):
        yield from self.fmu_cs
        yield from self.fmu_me

    def __len__(self) -> int:
        return len(self.fmu_cs) + len(self.fmu_me)

    def keys(self):
        yield from self.fmu_cs.keys()
        yield from self.fmu_me.keys()

    def values(self):
        yield from self.fmu_cs.values()
        yield from self.fmu_me.values()

    def items(self):
        yield from self.fmu_cs.items()
        yield from self.fmu_me.items()

    def get(self, fmu_name: str, default=None):
        if fmu_name in self:
            return self[fmu_name]
        return default

    def write_txt(self, txt_file: IO, configured: set[str] | frozenset[str] = frozenset()) -> dict[str, int]:
        """Write the declarations of the embedded FMUs. `configured`: names of the FMUs whose structural parameters
        are set by the container, in Configuration Mode (`<has_configuration_mode>`)."""
        print(f"{len(self.fmu_cs)} {len(self.fmu_me)}", file=txt_file)
        fmu_rank: dict[str, int] = {}
        for i, fmu in enumerate(self.values()):
            has_configuration_mode = int(fmu.name in configured)
            if fmu.is_me:
                # ME entries: <filename> <fmi_version> <nx> <nz> <has_configuration_mode> / <identifier> / <guid>
                print(f"{fmu.name} {fmu.fmi_version} {fmu.number_of_continuous_states} "
                      f"{fmu.number_of_event_indicators} {has_configuration_mode}", file=txt_file)
            else:
                # CS entries: <filename> <fmi_version> <has_event_mode> <has_configuration_mode> / <identifier> / <guid>
                print(f"{fmu.name} {fmu.fmi_version} {int(fmu.has_event_mode)} {has_configuration_mode}",
                      file=txt_file)

            print(f"{fmu.model_identifier}", file=txt_file)
            print(f"{fmu.guid}", file=txt_file)
            fmu_rank[fmu.name] = i

        return fmu_rank

write_txt(txt_file, configured=frozenset())

Write the declarations of the embedded FMUs. configured: names of the FMUs whose structural parameters are set by the container, in Configuration Mode (<has_configuration_mode>).

Source code in fmu_manipulation_toolbox/container/txt.py
def write_txt(self, txt_file: IO, configured: set[str] | frozenset[str] = frozenset()) -> dict[str, int]:
    """Write the declarations of the embedded FMUs. `configured`: names of the FMUs whose structural parameters
    are set by the container, in Configuration Mode (`<has_configuration_mode>`)."""
    print(f"{len(self.fmu_cs)} {len(self.fmu_me)}", file=txt_file)
    fmu_rank: dict[str, int] = {}
    for i, fmu in enumerate(self.values()):
        has_configuration_mode = int(fmu.name in configured)
        if fmu.is_me:
            # ME entries: <filename> <fmi_version> <nx> <nz> <has_configuration_mode> / <identifier> / <guid>
            print(f"{fmu.name} {fmu.fmi_version} {fmu.number_of_continuous_states} "
                  f"{fmu.number_of_event_indicators} {has_configuration_mode}", file=txt_file)
        else:
            # CS entries: <filename> <fmi_version> <has_event_mode> <has_configuration_mode> / <identifier> / <guid>
            print(f"{fmu.name} {fmu.fmi_version} {int(fmu.has_event_mode)} {has_configuration_mode}",
                  file=txt_file)

        print(f"{fmu.model_identifier}", file=txt_file)
        print(f"{fmu.guid}", file=txt_file)
        fmu_rank[fmu.name] = i

    return fmu_rank

Represents an internal connection between embedded FMUs inside a container.

A link routes one output port to one or more input ports. When the source and target types differ, automatic type conversion is applied if a conversion function exists.

Attributes:

Name Type Description
CONVERSION_FUNCTION dict[str, str]

Mapping from type pair strings (e.g. "real32/real64") to conversion function identifiers (alias of container.types.CONVERSION_FUNCTION).

name str

Human-readable name derived from the source FMU and port.

cport_from ContainerPort | None

Source output port, or None for importer-generated clocks.

cport_to_list list[ContainerPort]

Destination input ports.

conversions dict[str, str]

Conversion function, keyed by the type of the targets that need a converted copy of the value.

Source code in fmu_manipulation_toolbox/container/rules.py
class Link:
    """Represents an internal connection between embedded FMUs inside a container.

    A link routes one output port to one or more input ports. When the source
    and target types differ, automatic type conversion is applied if a
    conversion function exists.

    Attributes:
        CONVERSION_FUNCTION (dict[str, str]): Mapping from type pair strings
            (e.g. `"real32/real64"`) to conversion function identifiers (alias of
            `container.types.CONVERSION_FUNCTION`).
        name (str): Human-readable name derived from the source FMU and port.
        cport_from (ContainerPort | None): Source output port, or `None` for
            importer-generated clocks.
        cport_to_list (list[ContainerPort]): Destination input ports.
        conversions (dict[str, str]): Conversion function, keyed by the type of
            the targets that need a converted copy of the value.
    """

    CONVERSION_FUNCTION = CONVERSION_FUNCTION

    def __init__(self, cport_from: ContainerPort):
        self.name = cport_from.fmu.id + "." + cport_from.port.name  # strip .fmu suffix
        self.cport_from: ContainerPort | None = cport_from
        self.cport_to_list: list[ContainerPort] = []
        self.size = cport_from.port.size()
        self.conversions: dict[str, str] = {}

        if not cport_from.port.causality == "output":
            if cport_from.port.type_name == "clock":
                # LS-BUS allows connected input clocks.
                self.cport_from = None
                self.add_target(cport_from)
            else:
                raise FMUContainerError(f"{cport_from} has the causality '{cport_from.port.causality}', not 'output'.")

    def add_target(self, cport_to: ContainerPort):
        """Add a destination input port to this link.

        Args:
            cport_to (ContainerPort): The input port to connect.

        Raises:
            FMUContainerError: If the port is not an input, or if types are
                incompatible and no conversion exists.
        """
        if not cport_to.port.causality == "input":
            raise FMUContainerError(f"{cport_to} has the causality '{cport_to.port.causality}', not 'input'.")

        if cport_to.port.type_name == "clock" and self.cport_from is None:
            self.cport_to_list.append(cport_to)
        elif cport_to.port.type_name == self.cport_from.port.type_name:
            if cport_to.port.dimensions == self.cport_from.port.dimensions:
                check_ls_bus_mime_types(self.cport_from, cport_to)
                self.cport_to_list.append(cport_to)
            else:
                raise FMUContainerError(f"Cannot connect {self.cport_from} to port {cport_to.label}: their dimensions "
                                        f"differ.")
        else:
            conversion = self.get_conversion(cport_to)
            if conversion:
                if is_lossy(conversion) and self.cport_from is not None:
                    logger.warning(f"Lossy conversion '{conversion.lstrip('_')}': "
                                   f"{self.cport_from.label} → {cport_to.label}.")
                self.cport_to_list.append(cport_to)
                self.conversions[cport_to.port.type_name] = conversion
            else:
                raise FMUContainerError(f"Cannot connect {self.cport_from} to port {cport_to.label}: their types "
                                        f"differ.")

    def get_conversion(self, cport_to: ContainerPort) -> str | None:
        """Look up the conversion function for connecting to a different type.

        Args:
            cport_to (ContainerPort): The target port with a potentially
                different type.

        Returns:
            str | None: Conversion function identifier, or `None` if no
                conversion is available.
        """
        try:
            assert self.cport_from is not None
            conversion = f"{self.cport_from.port.type_name}/{cport_to.port.type_name}"
            return CONVERSION_FUNCTION[conversion]
        except KeyError:
            return None

    def nb_local(self) -> int:
        """Return the number of local variables needed for this link.

        Returns:
            int: `1` for the main value plus one per type-converted copy.
        """
        return 1+len(self.conversions)

add_target(cport_to)

Add a destination input port to this link.

Parameters:

Name Type Description Default
cport_to ContainerPort

The input port to connect.

required

Raises:

Type Description
FMUContainerError

If the port is not an input, or if types are incompatible and no conversion exists.

Source code in fmu_manipulation_toolbox/container/rules.py
def add_target(self, cport_to: ContainerPort):
    """Add a destination input port to this link.

    Args:
        cport_to (ContainerPort): The input port to connect.

    Raises:
        FMUContainerError: If the port is not an input, or if types are
            incompatible and no conversion exists.
    """
    if not cport_to.port.causality == "input":
        raise FMUContainerError(f"{cport_to} has the causality '{cport_to.port.causality}', not 'input'.")

    if cport_to.port.type_name == "clock" and self.cport_from is None:
        self.cport_to_list.append(cport_to)
    elif cport_to.port.type_name == self.cport_from.port.type_name:
        if cport_to.port.dimensions == self.cport_from.port.dimensions:
            check_ls_bus_mime_types(self.cport_from, cport_to)
            self.cport_to_list.append(cport_to)
        else:
            raise FMUContainerError(f"Cannot connect {self.cport_from} to port {cport_to.label}: their dimensions "
                                    f"differ.")
    else:
        conversion = self.get_conversion(cport_to)
        if conversion:
            if is_lossy(conversion) and self.cport_from is not None:
                logger.warning(f"Lossy conversion '{conversion.lstrip('_')}': "
                               f"{self.cport_from.label} → {cport_to.label}.")
            self.cport_to_list.append(cport_to)
            self.conversions[cport_to.port.type_name] = conversion
        else:
            raise FMUContainerError(f"Cannot connect {self.cport_from} to port {cport_to.label}: their types "
                                    f"differ.")

get_conversion(cport_to)

Look up the conversion function for connecting to a different type.

Parameters:

Name Type Description Default
cport_to ContainerPort

The target port with a potentially different type.

required

Returns:

Type Description
str | None

str | None: Conversion function identifier, or None if no conversion is available.

Source code in fmu_manipulation_toolbox/container/rules.py
def get_conversion(self, cport_to: ContainerPort) -> str | None:
    """Look up the conversion function for connecting to a different type.

    Args:
        cport_to (ContainerPort): The target port with a potentially
            different type.

    Returns:
        str | None: Conversion function identifier, or `None` if no
            conversion is available.
    """
    try:
        assert self.cport_from is not None
        conversion = f"{self.cport_from.port.type_name}/{cport_to.port.type_name}"
        return CONVERSION_FUNCTION[conversion]
    except KeyError:
        return None

nb_local()

Return the number of local variables needed for this link.

Returns:

Name Type Description
int int

1 for the main value plus one per type-converted copy.

Source code in fmu_manipulation_toolbox/container/rules.py
def nb_local(self) -> int:
    """Return the number of local variables needed for this link.

    Returns:
        int: `1` for the main value plus one per type-converted copy.
    """
    return 1+len(self.conversions)

LocalVariable dataclass

Local variable of the container: its value reference and its dimension.

Source code in fmu_manipulation_toolbox/container/txt.py
@dataclass
class LocalVariable:
    """Local variable of the container: its value reference and its dimension."""
    vr: int
    dimension: int

Platform dataclass

Binary of the container runtime for one OS: directory in the toolbox resources, library suffix, directory in the container.

Source code in fmu_manipulation_toolbox/container/builder.py
@dataclass
class Platform:
    """Binary of the container runtime for one OS: directory in the toolbox resources, library suffix, directory in
    the container."""
    origin_bindir: str
    suffixe: str
    target_bindir: str

Port dataclass

Variable logged by the datalog: its value reference and its name.

Source code in fmu_manipulation_toolbox/container/txt.py
@dataclass
class Port:
    """Variable logged by the datalog: its value reference and its name."""
    vr: int
    name: str

ValueReferenceTable

Allocates and tracks value references for the container's local variables.

Value references are encoded with a type mask in the upper bits, allowing the container runtime to identify the type from the VR alone.

Attributes:

Name Type Description
vr_table dict[str, int]

Next available VR index per type.

masks dict[str, int]

Bit mask per type, shifted to the upper byte.

nb_local_variable dict[str, int]

Count of local variables per type.

local_clock dict

Mapping from (EmbeddedFMU, fmu_vr) to local clock VR.

Source code in fmu_manipulation_toolbox/container/layout.py
class ValueReferenceTable:
    """Allocates and tracks value references for the container's local variables.

    Value references are encoded with a type mask in the upper bits,
    allowing the container runtime to identify the type from the VR alone.

    Attributes:
        vr_table (dict[str, int]): Next available VR index per type.
        masks (dict[str, int]): Bit mask per type, shifted to the upper byte.
        nb_local_variable (dict[str, int]): Count of local variables per type.
        local_clock (dict): Mapping from `(EmbeddedFMU, fmu_vr)` to local
            clock VR.
    """

    def __init__(self):
        self.vr_table:dict[str, int] = {}
        self.masks: dict[str, int] = {}
        self.nb_local_variable:dict[str, int] = {}
        self.nb_local_storage: dict[str, int] = {}
        self.vr_to_local:dict[int, int] = {}

        self.local_clock = {}
        for i, type_name in enumerate(ALL_TYPES):
            self.vr_table[type_name] = 0
            self.masks[type_name] = i << 24
            self.nb_local_variable[type_name] = 0
            self.nb_local_storage[type_name] = 0

    def add_vr(self, port_or_type_name: ContainerPort | str, local: bool = False, port_size=1) -> int:
        """Allocate a new value reference.

        Args:
            port_or_type_name (ContainerPort | str): A port (type is inferred)
                or a type name string.
            local (bool): Whether this VR is for a local variable.
            port_size (int): Dimension of the local variable, when given by a type name.

        Returns:
            int: The allocated value reference with type mask applied.
        """
        if isinstance(port_or_type_name, ContainerPort):
            type_name, size = port_or_type_name.port.type_name, port_or_type_name.port.size()
        else:
            type_name, size = port_or_type_name, port_size

        vr = self.vr_table[type_name] | self.masks[type_name]
        self.vr_table[type_name] += 1

        if local:
            self.vr_to_local[vr] = self.nb_local_storage[type_name]
            self.nb_local_variable[type_name] += 1
            self.nb_local_storage[type_name] += size

        return vr

    def add_storage(self, type_name: str) -> int:
        """Allocate one slot of local storage without value reference.

        Args:
            type_name (str): Container type name.

        Returns:
            int: Offset of the slot in the local storage of its type.
        """
        offset = self.nb_local_storage[type_name]
        self.nb_local_storage[type_name] += 1
        return offset

    def add_link(self, link: Link) -> tuple[int, dict[str, int]]:
        """Allocate the local variables of a link: its value and its type-converted copies.

        Args:
            link (Link): The link.

        Returns:
            tuple[int, dict[str, int]]: The value reference of the link value, and the
                value references of the converted copies keyed by target type.
        """
        if link.cport_from is None:
            vr = self.add_vr("clock", local=True)
        else:
            vr = self.add_vr(link.cport_from, local=True)
            if link.cport_from.port.type_name == "clock":
                self.local_clock[(link.cport_from.fmu, link.cport_from.port.vr)] = vr

        for cport_to in link.cport_to_list:
            if cport_to.port.type_name == "clock":
                self.local_clock[(cport_to.fmu, cport_to.port.vr)] = vr

        converted = {type_name: self.add_vr(type_name, local=True, port_size=link.size)
                     for type_name in link.conversions}
        return vr, converted

    def get_local_clock(self, cport: ContainerPort) -> int:
        """Get the local VR for a clock associated with a clocked port.

        Args:
            cport (ContainerPort): The clocked port.

        Returns:
            int: The local value reference of the clock.
        """
        assert cport.port.clock is not None
        return self.local_clock[(cport.fmu, int(cport.port.clock))]


    def nb_local(self, type_name: str) -> int:
        """Return the number of local variables for a given type.

        Args:
            type_name (str): Container type name (e.g. `"real64"`).

        Returns:
            int: Number of local variables of this type.
        """
        return self.nb_local_variable[type_name]

    def nb_storage(self, type_name: str) -> int:
        return self.nb_local_storage[type_name]

Allocate the local variables of a link: its value and its type-converted copies.

Parameters:

Name Type Description Default
link Link

The link.

required

Returns:

Type Description
tuple[int, dict[str, int]]

tuple[int, dict[str, int]]: The value reference of the link value, and the value references of the converted copies keyed by target type.

Source code in fmu_manipulation_toolbox/container/layout.py
def add_link(self, link: Link) -> tuple[int, dict[str, int]]:
    """Allocate the local variables of a link: its value and its type-converted copies.

    Args:
        link (Link): The link.

    Returns:
        tuple[int, dict[str, int]]: The value reference of the link value, and the
            value references of the converted copies keyed by target type.
    """
    if link.cport_from is None:
        vr = self.add_vr("clock", local=True)
    else:
        vr = self.add_vr(link.cport_from, local=True)
        if link.cport_from.port.type_name == "clock":
            self.local_clock[(link.cport_from.fmu, link.cport_from.port.vr)] = vr

    for cport_to in link.cport_to_list:
        if cport_to.port.type_name == "clock":
            self.local_clock[(cport_to.fmu, cport_to.port.vr)] = vr

    converted = {type_name: self.add_vr(type_name, local=True, port_size=link.size)
                 for type_name in link.conversions}
    return vr, converted

add_storage(type_name)

Allocate one slot of local storage without value reference.

Parameters:

Name Type Description Default
type_name str

Container type name.

required

Returns:

Name Type Description
int int

Offset of the slot in the local storage of its type.

Source code in fmu_manipulation_toolbox/container/layout.py
def add_storage(self, type_name: str) -> int:
    """Allocate one slot of local storage without value reference.

    Args:
        type_name (str): Container type name.

    Returns:
        int: Offset of the slot in the local storage of its type.
    """
    offset = self.nb_local_storage[type_name]
    self.nb_local_storage[type_name] += 1
    return offset

add_vr(port_or_type_name, local=False, port_size=1)

Allocate a new value reference.

Parameters:

Name Type Description Default
port_or_type_name ContainerPort | str

A port (type is inferred) or a type name string.

required
local bool

Whether this VR is for a local variable.

False
port_size int

Dimension of the local variable, when given by a type name.

1

Returns:

Name Type Description
int int

The allocated value reference with type mask applied.

Source code in fmu_manipulation_toolbox/container/layout.py
def add_vr(self, port_or_type_name: ContainerPort | str, local: bool = False, port_size=1) -> int:
    """Allocate a new value reference.

    Args:
        port_or_type_name (ContainerPort | str): A port (type is inferred)
            or a type name string.
        local (bool): Whether this VR is for a local variable.
        port_size (int): Dimension of the local variable, when given by a type name.

    Returns:
        int: The allocated value reference with type mask applied.
    """
    if isinstance(port_or_type_name, ContainerPort):
        type_name, size = port_or_type_name.port.type_name, port_or_type_name.port.size()
    else:
        type_name, size = port_or_type_name, port_size

    vr = self.vr_table[type_name] | self.masks[type_name]
    self.vr_table[type_name] += 1

    if local:
        self.vr_to_local[vr] = self.nb_local_storage[type_name]
        self.nb_local_variable[type_name] += 1
        self.nb_local_storage[type_name] += size

    return vr

get_local_clock(cport)

Get the local VR for a clock associated with a clocked port.

Parameters:

Name Type Description Default
cport ContainerPort

The clocked port.

required

Returns:

Name Type Description
int int

The local value reference of the clock.

Source code in fmu_manipulation_toolbox/container/layout.py
def get_local_clock(self, cport: ContainerPort) -> int:
    """Get the local VR for a clock associated with a clocked port.

    Args:
        cport (ContainerPort): The clocked port.

    Returns:
        int: The local value reference of the clock.
    """
    assert cport.port.clock is not None
    return self.local_clock[(cport.fmu, int(cport.port.clock))]

nb_local(type_name)

Return the number of local variables for a given type.

Parameters:

Name Type Description Default
type_name str

Container type name (e.g. "real64").

required

Returns:

Name Type Description
int int

Number of local variables of this type.

Source code in fmu_manipulation_toolbox/container/layout.py
def nb_local(self, type_name: str) -> int:
    """Return the number of local variables for a given type.

    Args:
        type_name (str): Container type name (e.g. `"real64"`).

    Returns:
        int: Number of local variables of this type.
    """
    return self.nb_local_variable[type_name]

Types of the container and conversions between them.

Shared by the container builder, which writes container.txt, and by split.py, which reads it back. The C runtime (container/) uses the same type order and conversion names: container.txt lists its sections in the order of ALL_TYPES, and every value of CONVERSION_FUNCTION is a CASE(...) of container/convert.c.

enumeration_as_integer(fmi_type, fmi_version)

FMI type handled by the container: an Enumeration is handled as the integer type used to access it.

Source code in fmu_manipulation_toolbox/container/types.py
def enumeration_as_integer(fmi_type: str, fmi_version: int) -> str:
    """FMI type handled by the container: an `Enumeration` is handled as the integer type used to access it."""
    if fmi_type == "Enumeration":
        return ENUMERATION_TYPE.get(fmi_version, fmi_type)
    return fmi_type

is_lossy(conversion)

Whether a conversion of CONVERSION_FUNCTION may lose information (narrowing, sign change, to boolean).

Source code in fmu_manipulation_toolbox/container/types.py
def is_lossy(conversion: str) -> bool:
    """Whether a conversion of `CONVERSION_FUNCTION` may lose information (narrowing, sign change, to boolean)."""
    return conversion.startswith("_")