Skip to content

Assembly

High-level interface for loading, manipulating, and building FMU Container assemblies.

Assembly reads a description file (CSV, JSON, or SSP), constructs the corresponding AssemblyNode tree, and provides methods to build the container FMU or export the assembly to a different format.

This is the main entry point for both the fmucontainer CLI and the Python API.

Examples:

from pathlib import Path
from fmu_manipulation_toolbox.assembly import Assembly

assembly = Assembly("bouncing.csv",
                    fmu_directory=Path("containers/bouncing_ball"),
                    mt=True)
assembly.make_fmu()

Attributes:

Name Type Description
filename Path

Path to the description file.

fmu_directory Path

Directory containing the source FMUs.

debug bool

Whether debug mode is enabled.

root AssemblyNode | None

Root node of the assembly tree.

Source code in fmu_manipulation_toolbox/assembly.py
 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
class Assembly:
    """High-level interface for loading, manipulating, and building FMU Container assemblies.

    `Assembly` reads a description file (CSV, JSON, or SSP), constructs the corresponding
    [AssemblyNode][fmu_manipulation_toolbox.assembly.AssemblyNode] tree, and provides methods
    to build the container FMU or export the assembly to a different format.

    This is the main entry point for both the `fmucontainer` CLI and the Python API.

    Examples:
        ```python
        from pathlib import Path
        from fmu_manipulation_toolbox.assembly import Assembly

        assembly = Assembly("bouncing.csv",
                            fmu_directory=Path("containers/bouncing_ball"),
                            mt=True)
        assembly.make_fmu()
        ```

    Attributes:
        filename (Path): Path to the description file.
        fmu_directory (Path): Directory containing the source FMUs.
        debug (bool): Whether debug mode is enabled.
        root (AssemblyNode | None): Root node of the assembly tree.
    """

    def __init__(self, filename: str | Path | None = None, default_step_size=None, default_auto_link=True,
                 default_auto_input=True, debug=False, default_sequential=False, default_auto_output=True,
                 default_mt=False, default_profiling=False, fmu_directory: Path = Path("."),
                 default_auto_parameter=False, default_auto_local=False, default_ts_multiplier=False,
                 default_reset_ports=False, default_mt_threshold: float = MT_THRESHOLD):
        self.filename = Path(filename) if filename else None
        self.default_auto_input = default_auto_input
        self.debug = debug
        self.default_auto_output = default_auto_output
        self.default_step_size = default_step_size
        self.default_auto_link = default_auto_link
        self.default_auto_parameter = default_auto_parameter
        self.default_auto_local = default_auto_local
        self.default_mt = default_mt
        self.default_mt_threshold = default_mt_threshold
        self.default_sequential = default_sequential
        self.default_profiling = default_profiling
        self.default_ts_multiplier = default_ts_multiplier
        self.default_reset_ports = default_reset_ports
        self.fmu_directory = fmu_directory

        if not fmu_directory.is_dir():
            raise AssemblyError(f"FMU directory '{fmu_directory}' is not valid.")

        self.root: AssemblyNode | None = None

        if self.filename:
            self.input_pathname = fmu_directory / self.filename
            self.description_pathname: Path | None = self.input_pathname  # For inclusion in FMU
            self.read()
        else:
            self.description_pathname = None

    def read(self):
        """Read and parse the description file.

        The format is determined by the file extension: `.json`, `.ssp`, or `.csv`.

        Raises:
            AssemblyError: If the file format is not supported.
        """
        if self.filename:
            logger.info(f"Reading '{self.filename}'.")
            if self.filename.suffix == ".json":
                self.read_json()
            elif self.filename.suffix == ".ssp":
                self.read_ssp()
            elif self.filename.suffix == ".csv":
                self.read_csv()
            else:
                raise AssemblyError(f"File format of '{self.filename}' is not supported.")
        else:
            raise AssemblyError("Filename should be specified for reading.")

    def write(self, filename: str):
        """Export the assembly to a file.

        Args:
            filename (str): Output filename. The format is determined by the
                extension (`.csv` or `.json`).

        Raises:
            AssemblyError: If the format is not supported.
        """
        if filename.endswith(".csv"):
            self.write_csv(filename)
        elif filename.endswith(".json"):
            self.write_json(filename)
        else:
            raise AssemblyError(f"Unable to write to '{filename}': format unsupported.")

    def read_csv(self):
        """Parse a CSV description file and populate the assembly tree."""
        name = str(self.filename.with_suffix(".fmu"))
        self.root = AssemblyNode(name, step_size=self.default_step_size, auto_link=self.default_auto_link,
                                 mt=self.default_mt, profiling=self.default_profiling,
                                 sequential=self.default_sequential, auto_input=self.default_auto_input,
                                 auto_output=self.default_auto_output, auto_parameter=self.default_auto_parameter,
                                 auto_local=self.default_auto_local, ts_multiplier=self.default_ts_multiplier,
                                 reset_ports=self.default_reset_ports, mt_threshold=self.default_mt_threshold)

        with open_text(self.input_pathname) as file:
            reader = csv.reader(file, delimiter=';')
            self._check_csv_headers(reader)
            for i, row in enumerate(reader):
                if not row or row[0][0] == '#':  # skip blank line of comment
                    continue

                try:
                    rule, from_fmu_filename, from_port_name, to_fmu_filename, to_port_name = row
                except ValueError:
                    logger.error(f"Line #{i+2}: expecting 5 columns. Line skipped.")
                    continue

                try:
                    self._read_csv_rule(self.root, rule.upper(),
                                        from_fmu_filename, from_port_name, to_fmu_filename, to_port_name)
                except AssemblyError as e:
                    logger.error(f"Line #{i+2}: {e} Line skipped.")
                    continue

    @staticmethod
    def _check_csv_headers(reader):
        headers = next(reader)
        headers_lowered = [h.lower() for h in headers]
        if not headers_lowered == ["rule", "from_fmu", "from_port", "to_fmu", "to_port"]:
            raise AssemblyError("Header (1st line of the file) is not well formatted.")

    @staticmethod
    def _read_csv_rule(node: AssemblyNode, rule: str, from_fmu_filename: str, from_port_name: str,
                       to_fmu_filename: str, to_port_name: str):
        if rule == "FMU":
            if not from_fmu_filename:
                raise AssemblyError("Missing FMU information.")
            node.add_fmu(from_fmu_filename)

        elif rule == "INPUT":
            if not to_fmu_filename or not to_port_name:
                raise AssemblyError("Missing ports of an input rule.")
            if not from_port_name:
                from_port_name = to_port_name
            node.add_input(from_port_name, to_fmu_filename, to_port_name)

        elif rule == "OUTPUT":
            if not from_fmu_filename or not from_port_name:
                raise AssemblyError("Missing ports of an output rule.")
            if not to_port_name:
                to_port_name = from_port_name
            node.add_output(from_fmu_filename, from_port_name, to_port_name)

        elif rule == "DROP":
            if not from_fmu_filename or not from_port_name:
                raise AssemblyError("Missing ports of a drop rule.")
            node.add_drop_port(from_fmu_filename, from_port_name)

        elif rule == "LINK":
            node.add_link(from_fmu_filename, from_port_name, to_fmu_filename, to_port_name)

        elif rule == "START":
            if not from_fmu_filename or not from_port_name or not to_fmu_filename:
                raise AssemblyError("Missing ports of a start rule.")

            node.add_start_value(from_fmu_filename, from_port_name, to_fmu_filename)
        else:
            raise AssemblyError(f"Unexpected rule '{rule}'.")

    def write_csv(self, filename: str | Path):
        """Export the assembly as a CSV file.

        Args:
            filename (str | Path): Output filename, relative to `fmu_directory`.

        Raises:
            AssemblyError: If the assembly contains nested containers
                (not representable in CSV).
        """
        if self.root.children:
            raise AssemblyError("This assembly is not flat. Cannot export to CSV file.")
        if self.root.fmu_paths:
            raise AssemblyError("This assembly embeds an FMU several times. Cannot export to CSV file: "
                                "use the JSON format.")

        with open(self.fmu_directory / filename, "w", encoding=ENCODING) as outfile:
            outfile.write("rule;from_fmu;from_port;to_fmu;to_port\n")
            for fmu in self.root.fmu_names_list:
                outfile.write(f"FMU;{fmu};;;\n")
            for port, source in self.root.input_ports.items():
                outfile.write(f"INPUT;;{source};{port.fmu_name};{port.port_name}\n")
            for port, target in self.root.output_ports.items():
                outfile.write(f"OUTPUT;{port.fmu_name};{port.port_name};;{target}\n")
            for link in self.root.links:
                outfile.write(f"LINK;{link.from_port.fmu_name};{link.from_port.port_name};"
                              f"{link.to_port.fmu_name};{link.to_port.port_name}\n")
            for port, value in self.root.start_values.items():
                outfile.write(f"START;{port.fmu_name};{port.port_name};{value};\n")
            for port in self.root.drop_ports:
                outfile.write(f"DROP;{port.fmu_name};{port.port_name};;\n")

    def read_json(self):
        """Parse a JSON description file and populate the assembly tree.

        Raises:
            AssemblyError: If the JSON is malformed or contains invalid keywords.
        """
        with open_text(self.input_pathname) as file:
            try:
                data = json.load(file)
            except json.decoder.JSONDecodeError as e:
                raise AssemblyError(f"Cannot read the JSON file: {e}.") from e
        self.root = self._json_decode_node(data)
        if not self.root.name:
            self.root.name = str(self.filename.with_suffix(".fmu").name)

    def _json_decode_node(self, data: dict) -> AssemblyNode:
        name = data.get("name", None)                                                       # 1
        mt = data.get("mt", self.default_mt)                                                # 2
        profiling = data.get("profiling", self.default_profiling)                           # 3
        sequential = data.get("sequential", self.default_sequential)                        # 3b
        auto_link = data.get("auto_link", self.default_auto_link)                           # 4
        auto_input = data.get("auto_input", self.default_auto_input)                        # 5
        auto_output = data.get("auto_output", self.default_auto_output)                     # 6
        auto_parameter = data.get("auto_parameter", self.default_auto_parameter)            # 6b
        auto_local = data.get("auto_local", self.default_auto_local)                        # 6c
        step_size = data.get("step_size", self.default_step_size)                           # 7
        ts_multiplier = data.get("ts_multiplier", self.default_ts_multiplier)               # 7b
        reset_ports = data.get("reset_ports", self.default_reset_ports)                     # 7c
        mt_threshold = data.get("mt_threshold", self.default_mt_threshold)                  # 7d

        node = AssemblyNode(name, step_size=step_size, auto_link=auto_link, mt=mt, profiling=profiling,
                            sequential=sequential,
                            auto_input=auto_input, auto_output=auto_output, auto_parameter=auto_parameter,
                            auto_local=auto_local, ts_multiplier=ts_multiplier, reset_ports=reset_ports,
                            mt_threshold=mt_threshold)

        paths = {}
        for key, value in data.items():
            if key in ('name', 'step_size', 'auto_link', 'auto_input', 'auto_output', 'mt', 'profiling', 'sequential',
                       'auto_parameter', 'auto_local', 'ts_multiplier', 'reset_ports', 'mt_threshold'):
                continue  # Already read

            elif key == "container":  # 8
                if not isinstance(value, list):
                    raise AssemblyError("JSON: 'container' keyword should define a list.")
                for sub_data in value:
                    node.add_sub_node(self._json_decode_node(sub_data))

            elif key == "fmu":  # 9
                if not isinstance(value, list):
                    raise AssemblyError("JSON: 'fmu' keyword should define a list.")
                for fmu in value:
                    node.add_fmu(fmu)

            elif key == "path":  # 9b
                if not isinstance(value, dict) or not all(isinstance(path, str) for path in value.values()):
                    raise AssemblyError("JSON: 'path' keyword should define a dictionary of FMU files.")
                paths = value

            elif key == "input":  # 10
                self._json_decode_keyword('input', value, node.add_input)

            elif key == "output":  # 11
                self._json_decode_keyword('output', value, node.add_output)

            elif key == "link":  # 12
                self._json_decode_keyword('link', value, node.add_link)

            elif key == "start":  # 13
                self._json_decode_keyword('start', value, node.add_start_value)

            elif key == "drop":  # 14
                self._json_decode_keyword('drop', value, node.add_drop_port)

            else:
                logger.error(f"JSON: unexpected keyword '{key}', skipped.")

        for fmu_name, fmu_path in paths.items():  # once every FMU of the "fmu" block is known
            if fmu_name not in node.fmu_names_list:
                raise AssemblyError(f"JSON: 'path' gives the file of '{fmu_name}', which is not in the 'fmu' list.")
            if fmu_path != fmu_name:
                node.fmu_paths[fmu_name] = fmu_path

        return node

    @staticmethod
    def _json_decode_keyword(keyword: str, value, function):
        if not isinstance(value, list):
            raise AssemblyError(f"JSON: '{keyword}' keyword should define a list.")
        for line in value:
            if not isinstance(line, list):
                raise AssemblyError(f"JSON: unexpected '{keyword}' value: {line}.")
            try:
                function(*line)
            except TypeError:
                raise AssemblyError(f"JSON: '{keyword}' value does not contain the right number of fields: "
                                    f"{line}.") from None

    def write_ssp(self, filename: str | Path, ssp_version: str = "2.0") -> Path:
        """Write the assembly as an SSP archive: `SystemStructure.ssd` and the embedded FMUs.

        The routing is written resolved (the links and ports of the `auto_*` rules become connections) and the
        options of each container go in an annotation, so that the file read back gives the same container (see
        [SSPWriter][fmu_manipulation_toolbox.ssp.SSPWriter]).

        Args:
            filename (str | Path): The `.ssp` file to write, relative to `fmu_directory` (as `write_json`).
            ssp_version (str): `"2.0"` (default) or `"1.0"`.

        Returns:
            Path: The file written.

        Raises:
            AssemblyError: If the assembly is empty or the version unknown.
        """
        from .ssp import SSPWriter

        return SSPWriter(self, ssp_version).write(self.fmu_directory / filename)

    def write_json(self, filename: str | Path, basenames_only: bool = False):
        """Export the assembly as a JSON file.

        FMU paths referenced in the `fmu`, `link`, `input`, `output`, `start`
        and `drop` blocks are made relative to the directory of the produced
        JSON file, so that the assembly stays portable (e.g. if the FMUs are
        stored alongside the JSON file, or in a sibling directory).

        Args:
            filename (str | Path): Output filename, relative to `fmu_directory`.
            basenames_only (bool): If `True`, reference embedded FMUs only by
                their filename (no directory), instead of computing a path
                relative to the JSON's own directory. Useful when the JSON is
                written to a location that has no lasting meaning (e.g. a
                temporary directory used to embed a documentation copy inside
                a built FMU).
        """
        output_pathname = self.fmu_directory / filename
        with open(output_pathname, "w", encoding=ENCODING) as file:
            data = self.json_encode()
            if basenames_only:
                data = _basename_json(data)
            else:
                data = _relativize_json(data, output_pathname.resolve().parent)
            json.dump(data, file, indent=2)

    def json_encode(self) -> dict[str, Any]:
        """Export the assembly as a JSON file."""
        if self.root:
            return self._json_encode_node(self.root)
        else:
            return {}

    def _json_encode_node(self, node: AssemblyNode) -> dict[str, Any]:
        json_node: dict[str, Any] = dict()
        json_node["name"] = node.name                      # 1
        json_node["mt"] = node.mt                          # 2
        json_node["profiling"] = node.profiling            # 3
        json_node["sequential"] = node.sequential          # 3b
        json_node["auto_link"] = node.auto_link            # 4
        json_node["auto_input"] = node.auto_input          # 5
        json_node["auto_output"] = node.auto_output        # 6
        json_node["auto_parameter"] = node.auto_parameter  # 6b
        json_node["auto_local"] = node.auto_local          # 6c

        if node.step_size:
            json_node["step_size"] = node.step_size        # 7

        if node.ts_multiplier:
            json_node["ts_multiplier"] = node.ts_multiplier # 7b

        if node.reset_ports:
            json_node["reset_ports"] = node.reset_ports     # 7c

        if node.mt_threshold != MT_THRESHOLD:
            json_node["mt_threshold"] = node.mt_threshold   # 7d

        if node.children:
            json_node["container"] = [self._json_encode_node(child) for child in node.children.values()]  # 8

        if node.fmu_names_list:
            json_node["fmu"] = [f"{fmu_name}" for fmu_name in sorted(node.fmu_names_list)]          # 9

        if node.fmu_paths:
            json_node["path"] = {fmu_name: node.fmu_paths[fmu_name] for fmu_name in sorted(node.fmu_paths)}  # 9b

        if node.input_ports:
            json_node["input"] = [[f"{source}", f"{port.fmu_name}", f"{port.port_name}"]            # 10
                                  for port, source in node.input_ports.items()]

        if node.output_ports:
            json_node["output"] = [[f"{port.fmu_name}", f"{port.port_name}", f"{target}"]           # 11
                                   for port, target in node.output_ports.items()]

        if node.links:
            json_node["link"] = [[f"{link.from_port.fmu_name}", f"{link.from_port.port_name}",      # 12
                                  f"{link.to_port.fmu_name}", f"{link.to_port.port_name}"]
                                 for link in node.links]

        if node.start_values:
            json_node["start"] = [[f"{port.fmu_name}", f"{port.port_name}", value]                  # 13
                                  for port, value in node.start_values.items()]

        if node.drop_ports:
            json_node["drop"] = [[f"{port.fmu_name}", f"{port.port_name}"] for port in node.drop_ports]  # 14

        return json_node

    def read_ssp(self):
        """Parse an SSP (System Structure and Parameterization) archive, SSP 1.0 or 2.0.

        Extracts the embedded FMUs, validates `SystemStructure.ssd` against the SSP schema (warnings only), then
        builds the assembly tree from it: systems, FMU components, connections, parameter values, start and stop
        times. What the container cannot honour is refused, or reported when it changes nothing (see
        [SSDParser][fmu_manipulation_toolbox.ssp.SSDParser]).

        An assembly is written back as SSP by `write_ssp`.
        """

        # Imported here: `ssp` builds on this module, and loads the SSP schema only when an SSP file is read.
        from .ssp import SSDParser, validate_ssd

        with zipfile.ZipFile(self.fmu_directory / self.filename) as zin:
            extract_folder = self.fmu_directory / self.filename.with_suffix(".dir")
            extract_folder.mkdir(exist_ok=True)

            for file in zin.filelist:
                if file.filename.endswith(".fmu"):
                    # FMUs keep their path relative to the archive root: two FMUs with the same file name in
                    # different directories do not overwrite each other.
                    zin.extract(file, path=extract_folder)
                    logger.debug(f"Extracted '{file.filename}' into '{extract_folder}'.")

            self.description_pathname = None
            if "SystemStructure.ssd" in zin.namelist():
                validate_ssd(zin.read("SystemStructure.ssd"), "SystemStructure.ssd")
                sdd = SSDParser(zin, extract_folder.name, step_size=self.default_step_size, auto_link=False,
                                mt=self.default_mt, profiling=self.default_profiling,
                                auto_input=False, auto_output=False, auto_parameter=False,
                                mt_threshold=self.default_mt_threshold)
                self.root = sdd.parse("SystemStructure.ssd")
                self.root.name = str(self.filename.with_suffix(".fmu"))
            else:
                raise AssemblyError(f"'SystemStructure.ssd' not found in '{self.fmu_directory / self.filename}'.")

    def make_simulink(self, filename: str | Path) -> Path:
        """Write the MATLAB script that builds the Simulink model of the assembly, with FMU blocks.

        The script designates the FMUs in place, relative to its own folder: the script and the FMUs must keep their
        relative places. Run the script `toto.m` (function `toto()`) in MATLAB R2024a or newer: it builds the model
        and saves it as `toto_model.slx` next to the script. See
        [SimulinkExporter][fmu_manipulation_toolbox.simulink.SimulinkExporter].

        Args:
            filename (str | Path): The `.m` script; its stem, a valid MATLAB identifier, names the function, and
                the model is `<stem>_model`.

        Returns:
            Path: The script.

        Raises:
            AssemblyError: If the assembly cannot be exported to Simulink.
        """
        from .simulink import SimulinkExporter  # the Simulink export imports this module
        return SimulinkExporter(self).export(filename)

    def make_fmu(self, dump_json=False, fmi_version=2, datalog=False, filename=None):
        """Build the FMU Container from the loaded assembly.

        Args:
            dump_json (bool): If `True`, also export a JSON dump of the assembly.
            fmi_version (int): FMI version for the container interface (`2` or `3`).
            datalog (bool): If `True`, enable data logging inside the container.
            filename (str | None): Override the output filename.
        """
        self.root.make_fmu(self.fmu_directory, debug=self.debug, description_pathname=self.description_pathname,
                           fmi_version=fmi_version, datalog=datalog, filename=filename)
        if dump_json:
            dump_file = Path(self.input_pathname.stem + "-dump").with_suffix(".json")
            logger.info(f"Writing '{dump_file}'.")
            self.write_json(dump_file)

json_encode()

Export the assembly as a JSON file.

Source code in fmu_manipulation_toolbox/assembly.py
def json_encode(self) -> dict[str, Any]:
    """Export the assembly as a JSON file."""
    if self.root:
        return self._json_encode_node(self.root)
    else:
        return {}

make_fmu(dump_json=False, fmi_version=2, datalog=False, filename=None)

Build the FMU Container from the loaded assembly.

Parameters:

Name Type Description Default
dump_json bool

If True, also export a JSON dump of the assembly.

False
fmi_version int

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

2
datalog bool

If True, enable data logging inside the container.

False
filename str | None

Override the output filename.

None
Source code in fmu_manipulation_toolbox/assembly.py
def make_fmu(self, dump_json=False, fmi_version=2, datalog=False, filename=None):
    """Build the FMU Container from the loaded assembly.

    Args:
        dump_json (bool): If `True`, also export a JSON dump of the assembly.
        fmi_version (int): FMI version for the container interface (`2` or `3`).
        datalog (bool): If `True`, enable data logging inside the container.
        filename (str | None): Override the output filename.
    """
    self.root.make_fmu(self.fmu_directory, debug=self.debug, description_pathname=self.description_pathname,
                       fmi_version=fmi_version, datalog=datalog, filename=filename)
    if dump_json:
        dump_file = Path(self.input_pathname.stem + "-dump").with_suffix(".json")
        logger.info(f"Writing '{dump_file}'.")
        self.write_json(dump_file)

Write the MATLAB script that builds the Simulink model of the assembly, with FMU blocks.

The script designates the FMUs in place, relative to its own folder: the script and the FMUs must keep their relative places. Run the script toto.m (function toto()) in MATLAB R2024a or newer: it builds the model and saves it as toto_model.slx next to the script. See SimulinkExporter.

Parameters:

Name Type Description Default
filename str | Path

The .m script; its stem, a valid MATLAB identifier, names the function, and the model is <stem>_model.

required

Returns:

Name Type Description
Path Path

The script.

Raises:

Type Description
AssemblyError

If the assembly cannot be exported to Simulink.

Source code in fmu_manipulation_toolbox/assembly.py
def make_simulink(self, filename: str | Path) -> Path:
    """Write the MATLAB script that builds the Simulink model of the assembly, with FMU blocks.

    The script designates the FMUs in place, relative to its own folder: the script and the FMUs must keep their
    relative places. Run the script `toto.m` (function `toto()`) in MATLAB R2024a or newer: it builds the model
    and saves it as `toto_model.slx` next to the script. See
    [SimulinkExporter][fmu_manipulation_toolbox.simulink.SimulinkExporter].

    Args:
        filename (str | Path): The `.m` script; its stem, a valid MATLAB identifier, names the function, and
            the model is `<stem>_model`.

    Returns:
        Path: The script.

    Raises:
        AssemblyError: If the assembly cannot be exported to Simulink.
    """
    from .simulink import SimulinkExporter  # the Simulink export imports this module
    return SimulinkExporter(self).export(filename)

read()

Read and parse the description file.

The format is determined by the file extension: .json, .ssp, or .csv.

Raises:

Type Description
AssemblyError

If the file format is not supported.

Source code in fmu_manipulation_toolbox/assembly.py
def read(self):
    """Read and parse the description file.

    The format is determined by the file extension: `.json`, `.ssp`, or `.csv`.

    Raises:
        AssemblyError: If the file format is not supported.
    """
    if self.filename:
        logger.info(f"Reading '{self.filename}'.")
        if self.filename.suffix == ".json":
            self.read_json()
        elif self.filename.suffix == ".ssp":
            self.read_ssp()
        elif self.filename.suffix == ".csv":
            self.read_csv()
        else:
            raise AssemblyError(f"File format of '{self.filename}' is not supported.")
    else:
        raise AssemblyError("Filename should be specified for reading.")

read_csv()

Parse a CSV description file and populate the assembly tree.

Source code in fmu_manipulation_toolbox/assembly.py
def read_csv(self):
    """Parse a CSV description file and populate the assembly tree."""
    name = str(self.filename.with_suffix(".fmu"))
    self.root = AssemblyNode(name, step_size=self.default_step_size, auto_link=self.default_auto_link,
                             mt=self.default_mt, profiling=self.default_profiling,
                             sequential=self.default_sequential, auto_input=self.default_auto_input,
                             auto_output=self.default_auto_output, auto_parameter=self.default_auto_parameter,
                             auto_local=self.default_auto_local, ts_multiplier=self.default_ts_multiplier,
                             reset_ports=self.default_reset_ports, mt_threshold=self.default_mt_threshold)

    with open_text(self.input_pathname) as file:
        reader = csv.reader(file, delimiter=';')
        self._check_csv_headers(reader)
        for i, row in enumerate(reader):
            if not row or row[0][0] == '#':  # skip blank line of comment
                continue

            try:
                rule, from_fmu_filename, from_port_name, to_fmu_filename, to_port_name = row
            except ValueError:
                logger.error(f"Line #{i+2}: expecting 5 columns. Line skipped.")
                continue

            try:
                self._read_csv_rule(self.root, rule.upper(),
                                    from_fmu_filename, from_port_name, to_fmu_filename, to_port_name)
            except AssemblyError as e:
                logger.error(f"Line #{i+2}: {e} Line skipped.")
                continue

read_json()

Parse a JSON description file and populate the assembly tree.

Raises:

Type Description
AssemblyError

If the JSON is malformed or contains invalid keywords.

Source code in fmu_manipulation_toolbox/assembly.py
def read_json(self):
    """Parse a JSON description file and populate the assembly tree.

    Raises:
        AssemblyError: If the JSON is malformed or contains invalid keywords.
    """
    with open_text(self.input_pathname) as file:
        try:
            data = json.load(file)
        except json.decoder.JSONDecodeError as e:
            raise AssemblyError(f"Cannot read the JSON file: {e}.") from e
    self.root = self._json_decode_node(data)
    if not self.root.name:
        self.root.name = str(self.filename.with_suffix(".fmu").name)

read_ssp()

Parse an SSP (System Structure and Parameterization) archive, SSP 1.0 or 2.0.

Extracts the embedded FMUs, validates SystemStructure.ssd against the SSP schema (warnings only), then builds the assembly tree from it: systems, FMU components, connections, parameter values, start and stop times. What the container cannot honour is refused, or reported when it changes nothing (see SSDParser).

An assembly is written back as SSP by write_ssp.

Source code in fmu_manipulation_toolbox/assembly.py
def read_ssp(self):
    """Parse an SSP (System Structure and Parameterization) archive, SSP 1.0 or 2.0.

    Extracts the embedded FMUs, validates `SystemStructure.ssd` against the SSP schema (warnings only), then
    builds the assembly tree from it: systems, FMU components, connections, parameter values, start and stop
    times. What the container cannot honour is refused, or reported when it changes nothing (see
    [SSDParser][fmu_manipulation_toolbox.ssp.SSDParser]).

    An assembly is written back as SSP by `write_ssp`.
    """

    # Imported here: `ssp` builds on this module, and loads the SSP schema only when an SSP file is read.
    from .ssp import SSDParser, validate_ssd

    with zipfile.ZipFile(self.fmu_directory / self.filename) as zin:
        extract_folder = self.fmu_directory / self.filename.with_suffix(".dir")
        extract_folder.mkdir(exist_ok=True)

        for file in zin.filelist:
            if file.filename.endswith(".fmu"):
                # FMUs keep their path relative to the archive root: two FMUs with the same file name in
                # different directories do not overwrite each other.
                zin.extract(file, path=extract_folder)
                logger.debug(f"Extracted '{file.filename}' into '{extract_folder}'.")

        self.description_pathname = None
        if "SystemStructure.ssd" in zin.namelist():
            validate_ssd(zin.read("SystemStructure.ssd"), "SystemStructure.ssd")
            sdd = SSDParser(zin, extract_folder.name, step_size=self.default_step_size, auto_link=False,
                            mt=self.default_mt, profiling=self.default_profiling,
                            auto_input=False, auto_output=False, auto_parameter=False,
                            mt_threshold=self.default_mt_threshold)
            self.root = sdd.parse("SystemStructure.ssd")
            self.root.name = str(self.filename.with_suffix(".fmu"))
        else:
            raise AssemblyError(f"'SystemStructure.ssd' not found in '{self.fmu_directory / self.filename}'.")

write(filename)

Export the assembly to a file.

Parameters:

Name Type Description Default
filename str

Output filename. The format is determined by the extension (.csv or .json).

required

Raises:

Type Description
AssemblyError

If the format is not supported.

Source code in fmu_manipulation_toolbox/assembly.py
def write(self, filename: str):
    """Export the assembly to a file.

    Args:
        filename (str): Output filename. The format is determined by the
            extension (`.csv` or `.json`).

    Raises:
        AssemblyError: If the format is not supported.
    """
    if filename.endswith(".csv"):
        self.write_csv(filename)
    elif filename.endswith(".json"):
        self.write_json(filename)
    else:
        raise AssemblyError(f"Unable to write to '{filename}': format unsupported.")

write_csv(filename)

Export the assembly as a CSV file.

Parameters:

Name Type Description Default
filename str | Path

Output filename, relative to fmu_directory.

required

Raises:

Type Description
AssemblyError

If the assembly contains nested containers (not representable in CSV).

Source code in fmu_manipulation_toolbox/assembly.py
def write_csv(self, filename: str | Path):
    """Export the assembly as a CSV file.

    Args:
        filename (str | Path): Output filename, relative to `fmu_directory`.

    Raises:
        AssemblyError: If the assembly contains nested containers
            (not representable in CSV).
    """
    if self.root.children:
        raise AssemblyError("This assembly is not flat. Cannot export to CSV file.")
    if self.root.fmu_paths:
        raise AssemblyError("This assembly embeds an FMU several times. Cannot export to CSV file: "
                            "use the JSON format.")

    with open(self.fmu_directory / filename, "w", encoding=ENCODING) as outfile:
        outfile.write("rule;from_fmu;from_port;to_fmu;to_port\n")
        for fmu in self.root.fmu_names_list:
            outfile.write(f"FMU;{fmu};;;\n")
        for port, source in self.root.input_ports.items():
            outfile.write(f"INPUT;;{source};{port.fmu_name};{port.port_name}\n")
        for port, target in self.root.output_ports.items():
            outfile.write(f"OUTPUT;{port.fmu_name};{port.port_name};;{target}\n")
        for link in self.root.links:
            outfile.write(f"LINK;{link.from_port.fmu_name};{link.from_port.port_name};"
                          f"{link.to_port.fmu_name};{link.to_port.port_name}\n")
        for port, value in self.root.start_values.items():
            outfile.write(f"START;{port.fmu_name};{port.port_name};{value};\n")
        for port in self.root.drop_ports:
            outfile.write(f"DROP;{port.fmu_name};{port.port_name};;\n")

write_json(filename, basenames_only=False)

Export the assembly as a JSON file.

FMU paths referenced in the fmu, link, input, output, start and drop blocks are made relative to the directory of the produced JSON file, so that the assembly stays portable (e.g. if the FMUs are stored alongside the JSON file, or in a sibling directory).

Parameters:

Name Type Description Default
filename str | Path

Output filename, relative to fmu_directory.

required
basenames_only bool

If True, reference embedded FMUs only by their filename (no directory), instead of computing a path relative to the JSON's own directory. Useful when the JSON is written to a location that has no lasting meaning (e.g. a temporary directory used to embed a documentation copy inside a built FMU).

False
Source code in fmu_manipulation_toolbox/assembly.py
def write_json(self, filename: str | Path, basenames_only: bool = False):
    """Export the assembly as a JSON file.

    FMU paths referenced in the `fmu`, `link`, `input`, `output`, `start`
    and `drop` blocks are made relative to the directory of the produced
    JSON file, so that the assembly stays portable (e.g. if the FMUs are
    stored alongside the JSON file, or in a sibling directory).

    Args:
        filename (str | Path): Output filename, relative to `fmu_directory`.
        basenames_only (bool): If `True`, reference embedded FMUs only by
            their filename (no directory), instead of computing a path
            relative to the JSON's own directory. Useful when the JSON is
            written to a location that has no lasting meaning (e.g. a
            temporary directory used to embed a documentation copy inside
            a built FMU).
    """
    output_pathname = self.fmu_directory / filename
    with open(output_pathname, "w", encoding=ENCODING) as file:
        data = self.json_encode()
        if basenames_only:
            data = _basename_json(data)
        else:
            data = _relativize_json(data, output_pathname.resolve().parent)
        json.dump(data, file, indent=2)

write_ssp(filename, ssp_version='2.0')

Write the assembly as an SSP archive: SystemStructure.ssd and the embedded FMUs.

The routing is written resolved (the links and ports of the auto_* rules become connections) and the options of each container go in an annotation, so that the file read back gives the same container (see SSPWriter).

Parameters:

Name Type Description Default
filename str | Path

The .ssp file to write, relative to fmu_directory (as write_json).

required
ssp_version str

"2.0" (default) or "1.0".

'2.0'

Returns:

Name Type Description
Path Path

The file written.

Raises:

Type Description
AssemblyError

If the assembly is empty or the version unknown.

Source code in fmu_manipulation_toolbox/assembly.py
def write_ssp(self, filename: str | Path, ssp_version: str = "2.0") -> Path:
    """Write the assembly as an SSP archive: `SystemStructure.ssd` and the embedded FMUs.

    The routing is written resolved (the links and ports of the `auto_*` rules become connections) and the
    options of each container go in an annotation, so that the file read back gives the same container (see
    [SSPWriter][fmu_manipulation_toolbox.ssp.SSPWriter]).

    Args:
        filename (str | Path): The `.ssp` file to write, relative to `fmu_directory` (as `write_json`).
        ssp_version (str): `"2.0"` (default) or `"1.0"`.

    Returns:
        Path: The file written.

    Raises:
        AssemblyError: If the assembly is empty or the version unknown.
    """
    from .ssp import SSPWriter

    return SSPWriter(self, ssp_version).write(self.fmu_directory / filename)

Represents a node in the assembly tree, defining a container and its topology.

An AssemblyNode describes how to build a single FMU Container: which FMUs it embeds, how their ports are connected (links), which ports are exposed as container inputs/outputs, and which runtime options (multi-threading, profiling, etc.) are enabled.

Nodes can be nested via add_sub_node to create hierarchical containers.

Attributes:

Name Type Description
name str | None

Output filename for the container (e.g. "container.fmu").

step_size float | None

Internal fixed time step in seconds, or None to deduce from embedded FMUs.

mt bool

Whether multithreaded mode is enabled.

mt_threshold float

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

profiling bool

Whether profiling mode is enabled.

sequential bool

Whether sequential scheduling is used.

auto_link bool

Automatically link ports with matching names and types.

auto_input bool

Automatically expose unconnected input ports.

auto_output bool

Automatically expose unconnected output ports.

auto_parameter bool

Automatically expose parameters of embedded FMUs.

auto_local bool

Automatically expose local variables of embedded FMUs.

ts_multiplier bool

Add a TS_MULTIPLIER input port to control step size dynamically.

reset_ports bool

Add a container.reset input to each embedded FMU, to reset it during the simulation.

parent AssemblyNode | None

Parent node in a hierarchical assembly, or None for root.

children dict[str, AssemblyNode]

Sub-container nodes, keyed by name.

fmu_names_list list[str]

Ordered list of the names of the embedded FMUs. A name is also the path of the FMU file, unless fmu_paths gives another one.

fmu_paths dict[str, str]

Path of the FMU file of the names that are not their own path: the instances of an FMU embedded several times (see instance_name).

input_ports dict[Port, str]

Mapping from destination port to exposed input name.

output_ports dict[Port, str]

Mapping from source port to exposed output name.

start_values dict[Port, str]

Mapping from port to its start value.

drop_ports list[Port]

List of output ports to explicitly ignore.

links list[Connection]

List of connections between embedded FMUs.

architecture_wires list[ArchitectureWire]

Dependencies between embedded FMUs read from an SSP file, kept as hints for the GUI; they are neither links nor part of the JSON description.

fmu_geometry dict[str, tuple[float, float, float, float]]

Position of embedded FMUs read from an SSP file: (x1, y1, x2, y2) of the ElementGeometry of their component (SSP coordinates, y upwards). A hint for the GUI, not part of the JSON description.

start_time float | None

Start time of the default experiment of the container, from the DefaultExperiment of an SSP file; None to take the one of its first FMU. Not part of the JSON description.

stop_time float | None

Stop time of the default experiment of the container, likewise.

Source code in fmu_manipulation_toolbox/assembly.py
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
class AssemblyNode:
    """Represents a node in the assembly tree, defining a container and its topology.

    An `AssemblyNode` describes how to build a single FMU Container: which FMUs it
    embeds, how their ports are connected (links), which ports are exposed as container
    inputs/outputs, and which runtime options (multi-threading, profiling, etc.) are enabled.

    Nodes can be nested via `add_sub_node` to create hierarchical containers.

    Attributes:
        name (str | None): Output filename for the container (e.g. `"container.fmu"`).
        step_size (float | None): Internal fixed time step in seconds, or `None` to deduce
            from embedded FMUs.
        mt (bool): Whether multithreaded mode is enabled.
        mt_threshold (float): Multithreaded mode: the embedded FMUs whose mean step takes at least this duration, in
            seconds, get a worker thread.
        profiling (bool): Whether profiling mode is enabled.
        sequential (bool): Whether sequential scheduling is used.
        auto_link (bool): Automatically link ports with matching names and types.
        auto_input (bool): Automatically expose unconnected input ports.
        auto_output (bool): Automatically expose unconnected output ports.
        auto_parameter (bool): Automatically expose parameters of embedded FMUs.
        auto_local (bool): Automatically expose local variables of embedded FMUs.
        ts_multiplier (bool): Add a `TS_MULTIPLIER` input port to control step size dynamically.
        reset_ports (bool): Add a `container.reset` input to each embedded FMU, to reset it during the simulation.
        parent (AssemblyNode | None): Parent node in a hierarchical assembly, or `None` for root.
        children (dict[str, AssemblyNode]): Sub-container nodes, keyed by name.
        fmu_names_list (list[str]): Ordered list of the names of the embedded FMUs. A name is also the path of
            the FMU file, unless `fmu_paths` gives another one.
        fmu_paths (dict[str, str]): Path of the FMU file of the names that are not their own path: the instances
            of an FMU embedded several times (see `instance_name`).
        input_ports (dict[Port, str]): Mapping from destination port to exposed input name.
        output_ports (dict[Port, str]): Mapping from source port to exposed output name.
        start_values (dict[Port, str]): Mapping from port to its start value.
        drop_ports (list[Port]): List of output ports to explicitly ignore.
        links (list[Connection]): List of connections between embedded FMUs.
        architecture_wires (list[ArchitectureWire]): Dependencies between embedded FMUs read from an SSP file,
            kept as hints for the GUI; they are neither links nor part of the JSON description.
        fmu_geometry (dict[str, tuple[float, float, float, float]]): Position of embedded FMUs read from an SSP
            file: `(x1, y1, x2, y2)` of the `ElementGeometry` of their component (SSP coordinates, y upwards). A hint
            for the GUI, not part of the JSON description.
        start_time (float | None): Start time of the default experiment of the container, from the
            `DefaultExperiment` of an SSP file; `None` to take the one of its first FMU. Not part of the JSON
            description.
        stop_time (float | None): Stop time of the default experiment of the container, likewise.
    """

    def __init__(self, name: str, step_size: float | str | None = None, mt=False, profiling=False, sequential=False,
                 auto_link=True, auto_input=True, auto_output=True, auto_parameter=False, auto_local=False,
                 ts_multiplier=False, reset_ports=False, mt_threshold: float = MT_THRESHOLD):
        self.name = name
        self.step_size: float | None
        if step_size:
            try:
                self.step_size = float(step_size)
            except ValueError:
                logger.warning(f"Step size '{step_size}' is not a number.")
                self.step_size = None
        else:
            self.step_size = None
        self.mt = mt
        try:
            self.mt_threshold = float(mt_threshold)
        except (TypeError, ValueError):
            raise AssemblyError(f"Threshold of the multithreaded mode '{mt_threshold}' is not a number.") from None
        self.profiling = profiling
        self.sequential = sequential
        self.auto_link = auto_link
        self.auto_input = auto_input
        self.auto_output = auto_output
        self.auto_parameter = auto_parameter
        self.auto_local = auto_local
        self.ts_multiplier = ts_multiplier
        self.reset_ports = reset_ports
        #: Whether the implicit links and ports (`auto_*`) were made explicit by a build (`make_fmu`).
        self.implicit_resolved = False

        self.parent: AssemblyNode | None = None
        self.children: dict[str, AssemblyNode] = {}     # sub-containers
        self.fmu_names_list: list[str] = []             # FMUs contained at this level (ordered list)
        self.fmu_paths: dict[str, str] = {}             # name -> FMU file, when they differ
        self.input_ports: dict[Port, str] = {}          # value is input port name, key is the source
        self.output_ports: dict[Port, str] = {}         # value is output port name, key is the origin
        self.start_values: dict[Port, str] = {}
        self.drop_ports: list[Port] = []
        self.links: list[Connection] = []
        self.architecture_wires: list[ArchitectureWire] = []
        self.fmu_geometry: dict[str, tuple[float, float, float, float]] = {}
        self.start_time: float | None = None
        self.stop_time: float | None = None

    def add_sub_node(self, sub_node):
        """Add a child `AssemblyNode` to create a hierarchical (nested) container.

        Args:
            sub_node (AssemblyNode): The child node to add. Its name will be
                auto-generated if `None`.

        Raises:
            AssemblyError: If the sub-node is already parented or already a child
                of this node.
        """
        if sub_node.name is None:
            sub_node.name = str(uuid.uuid4())+".fmu"

        if sub_node.parent is not None:
            raise AssemblyError(f"Internal error: node '{sub_node.name}' already has a parent.")

        if sub_node.name in self.children:
            raise AssemblyError(f"Internal error: node '{sub_node.name}' is already a child of '{self.name}'.")

        sub_node.parent = self
        self.children[sub_node.name] = sub_node

    def add_fmu(self, fmu_name: str, fmu_path: str | None = None):
        """Declare an embedded FMU.

        Args:
            fmu_name (str): Name of the FMU, used by the links, inputs, outputs, start values and dropped ports
                (e.g. `"model.fmu"`). It is also the path of the FMU file, unless `fmu_path` is given.
            fmu_path (str | None): Path of the FMU file, when it differs from `fmu_name`: an instance of an FMU
                embedded several times (see `instance_name`).

        Raises:
            AssemblyError: If `fmu_name` is already declared with another file.
        """
        if fmu_path == fmu_name:
            fmu_path = None
        if fmu_name in self.fmu_names_list:
            if self.fmu_paths.get(fmu_name) != fmu_path:
                raise AssemblyError(f"FMU '{fmu_name}' is already declared with another file "
                                    f"('{self.fmu_path(fmu_name)}').")
            return
        self.fmu_names_list.append(fmu_name)
        if fmu_path is not None:
            self.fmu_paths[fmu_name] = fmu_path

    def fmu_path(self, fmu_name: str) -> str:
        """Path of the FMU file of the embedded FMU `fmu_name`."""
        return self.fmu_paths.get(fmu_name, fmu_name)

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

        Args:
            from_port_name (str): Name of the exposed input on the container.
            to_fmu_filename (str): Filename of the embedded FMU.
            to_port_name (str): Name of the input port on the embedded FMU.
        """
        self.input_ports[Port(to_fmu_filename, to_port_name)] = from_port_name

    def add_output(self, from_fmu_filename: str, from_port_name: str, to_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.
            to_port_name (str): Name of the exposed output on the container.
        """
        self.output_ports[Port(from_fmu_filename, from_port_name)] = to_port_name

    def add_drop_port(self, fmu_filename: str, port_name: str):
        """Mark an output port to be explicitly ignored.

        Args:
            fmu_filename (str): Filename of the embedded FMU.
            port_name (str): Name of the output port to drop.
        """
        self.drop_ports.append(Port(fmu_filename, port_name))

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

        Args:
            from_fmu_filename (str): Filename of the source FMU.
            from_port_name (str): Name of the output port on the source FMU.
            to_fmu_filename (str): Filename of the destination FMU.
            to_port_name (str): Name of the input port on the destination FMU.
        """
        self.links.append(Connection(Port(from_fmu_filename, from_port_name),
                          Port(to_fmu_filename, to_port_name)))

    def add_architecture_wire(self, start_fmu: str, end_fmu: str, orientation: str, description: str | None = None):
        """Declare a dependency between two embedded FMUs, without naming variables (see `ArchitectureWire`).

        Args:
            start_fmu (str): Name of the embedded FMU at the start of the wire.
            end_fmu (str): Name of the embedded FMU at the end of the wire.
            orientation (str): `"directed"` (from start to end), `"bidirectional"` or `"undirected"`.
            description (str | None): Free text (Markdown) attached to the wire.
        """
        self.architecture_wires.append(ArchitectureWire(start_fmu, end_fmu, orientation, description))

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

        Args:
            fmu_filename (str): Filename of the embedded FMU.
            port_name (str): Name of the port.
            value (str): Start value as a string.
        """
        self.start_values[Port(fmu_filename, port_name)] = value

    def make_fmu(self, fmu_directory: Path, debug=False, description_pathname=None, fmi_version=2, datalog=False,
                 filename=None):
        """Build the FMU Container.

        Recursively builds any child containers first, then creates the container FMU
        by delegating to
        [FMUContainer][fmu_manipulation_toolbox.container.FMUContainer].

        Args:
            fmu_directory (Path): Directory containing the source FMUs and where the
                container will be generated.
            debug (bool): If `True`, keep intermediate build artifacts and enable
                verbose logging.
            description_pathname (Path | None): Path to the original description file
                to embed in the FMU.
            fmi_version (int): FMI version for the container interface (`2` or `3`).
            datalog (bool): If `True`, generate a datalog configuration file inside
                the container.
            filename (str | None): Override the output filename. Defaults to `name`.
        """
        for node in self.children.values():
            node.make_fmu(fmu_directory, debug=debug, fmi_version=fmi_version)

        identifier = str(Path(self.name).stem)
        container = FMUContainer(identifier, fmu_directory, description_pathname=description_pathname,
                                 fmi_version=fmi_version, reset_ports=self.reset_ports)
        container.start_time = self.start_time
        container.stop_time = self.stop_time

        for node in self.children.values():
            container.get_fmu(node.name)

        for fmu_name in self.fmu_names_list:
            container.get_fmu(self.fmu_path(fmu_name), fmu_name)

        for port, source in self.input_ports.items():
            container.add_input(source, port.fmu_name, port.port_name)

        for port, target in self.output_ports.items():
            container.add_output(port.fmu_name, port.port_name, target)

        for link in self.links:
            container.add_link(link.from_port.fmu_name, link.from_port.port_name,
                               link.to_port.fmu_name, link.to_port.port_name)

        for drop in self.drop_ports:
            container.drop_port(drop.fmu_name, drop.port_name)

        for port, value in self.start_values.items():
            container.add_start_value(port.fmu_name, port.port_name, value)

        wired = container.add_implicit_rule(auto_input=self.auto_input,
                                            auto_output=self.auto_output,
                                            auto_link=self.auto_link,
                                            auto_parameter=self.auto_parameter,
                                            auto_local=self.auto_local)
        for input_rule in wired.rule_input:
            self.add_input(input_rule[0], input_rule[1], input_rule[2])
        for output_rule in wired.rule_output:
            self.add_output(output_rule[0], output_rule[1], output_rule[2])
        for link_rule in wired.rule_link:
            self.add_link(link_rule[0], link_rule[1], link_rule[2], link_rule[3])
        self.implicit_resolved = True

        if filename is None:
            filename = self.name

        container.make_fmu(filename, self.step_size, mt=self.mt, profiling=self.profiling, sequential=self.sequential,
                           debug=debug, ts_multiplier=self.ts_multiplier, datalog=datalog,
                           mt_threshold=self.mt_threshold)

        for node in self.children.values():
            logger.info(f"Deleting the transient FMU container '{node.name}'.")
            (fmu_directory / node.name).unlink()

    def get_final_from(self, port: Port) -> Port:
        """Resolve the ultimate source port by traversing the assembly hierarchy upward.

        Args:
            port (Port): The port to trace back to its origin.

        Returns:
            Port: The resolved source port (either a top-level input or an
                embedded FMU port).

        Raises:
            AssemblyError: If the port is not connected upstream.
        """
        if port in self.input_ports:
            ancestor = Port(self.name, self.input_ports[port])
            if self.parent:
                return self.parent.get_final_from(ancestor)  # input port
            else:
                return ancestor  # TOPLEVEL input port
        elif port.fmu_name in self.fmu_names_list:
            return port  # embedded FMU
        elif port.fmu_name in self.children:
                child = self.children[port.fmu_name]
                ancestors = [key for key, val in child.output_ports.items() if val == port.port_name]
                if len(ancestors) == 1:
                    return child.get_final_from(ancestors[0])  # child output port

        raise AssemblyError(f"'{self.name}': port '{port}' is not connected upstream.")

    def get_final_to(self, port: Port) -> Port:
        """Resolve the ultimate destination port by traversing the assembly hierarchy downward.

        Args:
            port (Port): The port to trace forward to its destination.

        Returns:
            Port: The resolved destination port (either a top-level output or an
                embedded FMU port).

        Raises:
            AssemblyError: If the port is not connected downstream.
        """
        if port in self.output_ports:
            successor = Port(self.name, self.output_ports[port])
            if self.parent:
                return self.parent.get_final_to(successor)  # Output port
            else:
                return successor  # TOPLEVEL output port
        elif port.fmu_name in self.fmu_names_list:
            return port  # embedded FMU
        elif port.fmu_name in self.children:
                child = self.children[port.fmu_name]
                successors = [key for key, val in child.input_ports.items() if val == port.port_name]
                if len(successors) == 1:
                    return child.get_final_to(successors[0])  # Child input port

        raise AssemblyError(f"'{self.name}': port '{port}' is not connected downstream.")

    def get_fmu_connections(self, fmu_name: str) -> list[Connection]:
        """Get all resolved connections involving a specific embedded FMU.

        Returns connections where the given FMU is either source or destination,
        with ports resolved through the full assembly hierarchy.

        Args:
            fmu_name (str): Filename of the embedded FMU.

        Returns:
            list[Connection]: List of connections involving the specified FMU.

        Raises:
            AssemblyError: If the FMU is not embedded in this node.
        """
        connections = []
        if fmu_name not in self.fmu_names_list:
            raise AssemblyError(f"Internal error: FMU '{fmu_name}' is not embedded by '{self.name}'.")
        for link in self.links:
            if link.from_port.fmu_name == fmu_name:
                connections.append(Connection(link.from_port, self.get_final_to(link.to_port)))
            elif link.to_port.fmu_name == fmu_name:
                connections.append(Connection(self.get_final_from(link.from_port), link.to_port))

        for to_port, input_port_name in self.input_ports.items():
            if to_port.fmu_name == fmu_name:
                if self.parent:
                    connections.append(Connection(self.parent.get_final_from(Port(self.name, input_port_name)),
                                                  to_port))
                else:
                    connections.append(Connection(Port(self.name, input_port_name), to_port))

        for from_port, output_port_name in self.output_ports.items():
            if from_port.fmu_name == fmu_name:
                if self.parent:
                    connections.append(Connection(from_port,
                                                  self.parent.get_final_to(Port(self.name, output_port_name))))
                else:
                    connections.append(Connection(from_port, Port(self.name, output_port_name))) ###HERE

        return connections

add_architecture_wire(start_fmu, end_fmu, orientation, description=None)

Declare a dependency between two embedded FMUs, without naming variables (see ArchitectureWire).

Parameters:

Name Type Description Default
start_fmu str

Name of the embedded FMU at the start of the wire.

required
end_fmu str

Name of the embedded FMU at the end of the wire.

required
orientation str

"directed" (from start to end), "bidirectional" or "undirected".

required
description str | None

Free text (Markdown) attached to the wire.

None
Source code in fmu_manipulation_toolbox/assembly.py
def add_architecture_wire(self, start_fmu: str, end_fmu: str, orientation: str, description: str | None = None):
    """Declare a dependency between two embedded FMUs, without naming variables (see `ArchitectureWire`).

    Args:
        start_fmu (str): Name of the embedded FMU at the start of the wire.
        end_fmu (str): Name of the embedded FMU at the end of the wire.
        orientation (str): `"directed"` (from start to end), `"bidirectional"` or `"undirected"`.
        description (str | None): Free text (Markdown) attached to the wire.
    """
    self.architecture_wires.append(ArchitectureWire(start_fmu, end_fmu, orientation, description))

add_drop_port(fmu_filename, port_name)

Mark an output port to be explicitly ignored.

Parameters:

Name Type Description Default
fmu_filename str

Filename of the embedded FMU.

required
port_name str

Name of the output port to drop.

required
Source code in fmu_manipulation_toolbox/assembly.py
def add_drop_port(self, fmu_filename: str, port_name: str):
    """Mark an output port to be explicitly ignored.

    Args:
        fmu_filename (str): Filename of the embedded FMU.
        port_name (str): Name of the output port to drop.
    """
    self.drop_ports.append(Port(fmu_filename, port_name))

add_fmu(fmu_name, fmu_path=None)

Declare an embedded FMU.

Parameters:

Name Type Description Default
fmu_name str

Name of the FMU, used by the links, inputs, outputs, start values and dropped ports (e.g. "model.fmu"). It is also the path of the FMU file, unless fmu_path is given.

required
fmu_path str | None

Path of the FMU file, when it differs from fmu_name: an instance of an FMU embedded several times (see instance_name).

None

Raises:

Type Description
AssemblyError

If fmu_name is already declared with another file.

Source code in fmu_manipulation_toolbox/assembly.py
def add_fmu(self, fmu_name: str, fmu_path: str | None = None):
    """Declare an embedded FMU.

    Args:
        fmu_name (str): Name of the FMU, used by the links, inputs, outputs, start values and dropped ports
            (e.g. `"model.fmu"`). It is also the path of the FMU file, unless `fmu_path` is given.
        fmu_path (str | None): Path of the FMU file, when it differs from `fmu_name`: an instance of an FMU
            embedded several times (see `instance_name`).

    Raises:
        AssemblyError: If `fmu_name` is already declared with another file.
    """
    if fmu_path == fmu_name:
        fmu_path = None
    if fmu_name in self.fmu_names_list:
        if self.fmu_paths.get(fmu_name) != fmu_path:
            raise AssemblyError(f"FMU '{fmu_name}' is already declared with another file "
                                f"('{self.fmu_path(fmu_name)}').")
        return
    self.fmu_names_list.append(fmu_name)
    if fmu_path is not None:
        self.fmu_paths[fmu_name] = fmu_path

add_input(from_port_name, to_fmu_filename, to_port_name)

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

Parameters:

Name Type Description Default
from_port_name str

Name of the exposed input on the container.

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
Source code in fmu_manipulation_toolbox/assembly.py
def add_input(self, from_port_name: str, to_fmu_filename: str, to_port_name: str):
    """Expose a port of an embedded FMU as a container input.

    Args:
        from_port_name (str): Name of the exposed input on the container.
        to_fmu_filename (str): Filename of the embedded FMU.
        to_port_name (str): Name of the input port on the embedded FMU.
    """
    self.input_ports[Port(to_fmu_filename, to_port_name)] = from_port_name

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

Parameters:

Name Type Description Default
from_fmu_filename str

Filename of the source FMU.

required
from_port_name str

Name of the output port on the source FMU.

required
to_fmu_filename str

Filename of the destination FMU.

required
to_port_name str

Name of the input port on the destination FMU.

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

    Args:
        from_fmu_filename (str): Filename of the source FMU.
        from_port_name (str): Name of the output port on the source FMU.
        to_fmu_filename (str): Filename of the destination FMU.
        to_port_name (str): Name of the input port on the destination FMU.
    """
    self.links.append(Connection(Port(from_fmu_filename, from_port_name),
                      Port(to_fmu_filename, to_port_name)))

add_output(from_fmu_filename, from_port_name, to_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
to_port_name str

Name of the exposed output on the container.

required
Source code in fmu_manipulation_toolbox/assembly.py
def add_output(self, from_fmu_filename: str, from_port_name: str, to_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.
        to_port_name (str): Name of the exposed output on the container.
    """
    self.output_ports[Port(from_fmu_filename, from_port_name)] = to_port_name

add_start_value(fmu_filename, port_name, value)

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

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.

required
Source code in fmu_manipulation_toolbox/assembly.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.

    Args:
        fmu_filename (str): Filename of the embedded FMU.
        port_name (str): Name of the port.
        value (str): Start value as a string.
    """
    self.start_values[Port(fmu_filename, port_name)] = value

add_sub_node(sub_node)

Add a child AssemblyNode to create a hierarchical (nested) container.

Parameters:

Name Type Description Default
sub_node AssemblyNode

The child node to add. Its name will be auto-generated if None.

required

Raises:

Type Description
AssemblyError

If the sub-node is already parented or already a child of this node.

Source code in fmu_manipulation_toolbox/assembly.py
def add_sub_node(self, sub_node):
    """Add a child `AssemblyNode` to create a hierarchical (nested) container.

    Args:
        sub_node (AssemblyNode): The child node to add. Its name will be
            auto-generated if `None`.

    Raises:
        AssemblyError: If the sub-node is already parented or already a child
            of this node.
    """
    if sub_node.name is None:
        sub_node.name = str(uuid.uuid4())+".fmu"

    if sub_node.parent is not None:
        raise AssemblyError(f"Internal error: node '{sub_node.name}' already has a parent.")

    if sub_node.name in self.children:
        raise AssemblyError(f"Internal error: node '{sub_node.name}' is already a child of '{self.name}'.")

    sub_node.parent = self
    self.children[sub_node.name] = sub_node

fmu_path(fmu_name)

Path of the FMU file of the embedded FMU fmu_name.

Source code in fmu_manipulation_toolbox/assembly.py
def fmu_path(self, fmu_name: str) -> str:
    """Path of the FMU file of the embedded FMU `fmu_name`."""
    return self.fmu_paths.get(fmu_name, fmu_name)

get_final_from(port)

Resolve the ultimate source port by traversing the assembly hierarchy upward.

Parameters:

Name Type Description Default
port Port

The port to trace back to its origin.

required

Returns:

Name Type Description
Port Port

The resolved source port (either a top-level input or an embedded FMU port).

Raises:

Type Description
AssemblyError

If the port is not connected upstream.

Source code in fmu_manipulation_toolbox/assembly.py
def get_final_from(self, port: Port) -> Port:
    """Resolve the ultimate source port by traversing the assembly hierarchy upward.

    Args:
        port (Port): The port to trace back to its origin.

    Returns:
        Port: The resolved source port (either a top-level input or an
            embedded FMU port).

    Raises:
        AssemblyError: If the port is not connected upstream.
    """
    if port in self.input_ports:
        ancestor = Port(self.name, self.input_ports[port])
        if self.parent:
            return self.parent.get_final_from(ancestor)  # input port
        else:
            return ancestor  # TOPLEVEL input port
    elif port.fmu_name in self.fmu_names_list:
        return port  # embedded FMU
    elif port.fmu_name in self.children:
            child = self.children[port.fmu_name]
            ancestors = [key for key, val in child.output_ports.items() if val == port.port_name]
            if len(ancestors) == 1:
                return child.get_final_from(ancestors[0])  # child output port

    raise AssemblyError(f"'{self.name}': port '{port}' is not connected upstream.")

get_final_to(port)

Resolve the ultimate destination port by traversing the assembly hierarchy downward.

Parameters:

Name Type Description Default
port Port

The port to trace forward to its destination.

required

Returns:

Name Type Description
Port Port

The resolved destination port (either a top-level output or an embedded FMU port).

Raises:

Type Description
AssemblyError

If the port is not connected downstream.

Source code in fmu_manipulation_toolbox/assembly.py
def get_final_to(self, port: Port) -> Port:
    """Resolve the ultimate destination port by traversing the assembly hierarchy downward.

    Args:
        port (Port): The port to trace forward to its destination.

    Returns:
        Port: The resolved destination port (either a top-level output or an
            embedded FMU port).

    Raises:
        AssemblyError: If the port is not connected downstream.
    """
    if port in self.output_ports:
        successor = Port(self.name, self.output_ports[port])
        if self.parent:
            return self.parent.get_final_to(successor)  # Output port
        else:
            return successor  # TOPLEVEL output port
    elif port.fmu_name in self.fmu_names_list:
        return port  # embedded FMU
    elif port.fmu_name in self.children:
            child = self.children[port.fmu_name]
            successors = [key for key, val in child.input_ports.items() if val == port.port_name]
            if len(successors) == 1:
                return child.get_final_to(successors[0])  # Child input port

    raise AssemblyError(f"'{self.name}': port '{port}' is not connected downstream.")

get_fmu_connections(fmu_name)

Get all resolved connections involving a specific embedded FMU.

Returns connections where the given FMU is either source or destination, with ports resolved through the full assembly hierarchy.

Parameters:

Name Type Description Default
fmu_name str

Filename of the embedded FMU.

required

Returns:

Type Description
list[Connection]

list[Connection]: List of connections involving the specified FMU.

Raises:

Type Description
AssemblyError

If the FMU is not embedded in this node.

Source code in fmu_manipulation_toolbox/assembly.py
def get_fmu_connections(self, fmu_name: str) -> list[Connection]:
    """Get all resolved connections involving a specific embedded FMU.

    Returns connections where the given FMU is either source or destination,
    with ports resolved through the full assembly hierarchy.

    Args:
        fmu_name (str): Filename of the embedded FMU.

    Returns:
        list[Connection]: List of connections involving the specified FMU.

    Raises:
        AssemblyError: If the FMU is not embedded in this node.
    """
    connections = []
    if fmu_name not in self.fmu_names_list:
        raise AssemblyError(f"Internal error: FMU '{fmu_name}' is not embedded by '{self.name}'.")
    for link in self.links:
        if link.from_port.fmu_name == fmu_name:
            connections.append(Connection(link.from_port, self.get_final_to(link.to_port)))
        elif link.to_port.fmu_name == fmu_name:
            connections.append(Connection(self.get_final_from(link.from_port), link.to_port))

    for to_port, input_port_name in self.input_ports.items():
        if to_port.fmu_name == fmu_name:
            if self.parent:
                connections.append(Connection(self.parent.get_final_from(Port(self.name, input_port_name)),
                                              to_port))
            else:
                connections.append(Connection(Port(self.name, input_port_name), to_port))

    for from_port, output_port_name in self.output_ports.items():
        if from_port.fmu_name == fmu_name:
            if self.parent:
                connections.append(Connection(from_port,
                                              self.parent.get_final_to(Port(self.name, output_port_name))))
            else:
                connections.append(Connection(from_port, Port(self.name, output_port_name))) ###HERE

    return connections

make_fmu(fmu_directory, debug=False, description_pathname=None, fmi_version=2, datalog=False, filename=None)

Build the FMU Container.

Recursively builds any child containers first, then creates the container FMU by delegating to FMUContainer.

Parameters:

Name Type Description Default
fmu_directory Path

Directory containing the source FMUs and where the container will be generated.

required
debug bool

If True, keep intermediate build artifacts and enable verbose logging.

False
description_pathname Path | None

Path to the original description file to embed in the FMU.

None
fmi_version int

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

2
datalog bool

If True, generate a datalog configuration file inside the container.

False
filename str | None

Override the output filename. Defaults to name.

None
Source code in fmu_manipulation_toolbox/assembly.py
def make_fmu(self, fmu_directory: Path, debug=False, description_pathname=None, fmi_version=2, datalog=False,
             filename=None):
    """Build the FMU Container.

    Recursively builds any child containers first, then creates the container FMU
    by delegating to
    [FMUContainer][fmu_manipulation_toolbox.container.FMUContainer].

    Args:
        fmu_directory (Path): Directory containing the source FMUs and where the
            container will be generated.
        debug (bool): If `True`, keep intermediate build artifacts and enable
            verbose logging.
        description_pathname (Path | None): Path to the original description file
            to embed in the FMU.
        fmi_version (int): FMI version for the container interface (`2` or `3`).
        datalog (bool): If `True`, generate a datalog configuration file inside
            the container.
        filename (str | None): Override the output filename. Defaults to `name`.
    """
    for node in self.children.values():
        node.make_fmu(fmu_directory, debug=debug, fmi_version=fmi_version)

    identifier = str(Path(self.name).stem)
    container = FMUContainer(identifier, fmu_directory, description_pathname=description_pathname,
                             fmi_version=fmi_version, reset_ports=self.reset_ports)
    container.start_time = self.start_time
    container.stop_time = self.stop_time

    for node in self.children.values():
        container.get_fmu(node.name)

    for fmu_name in self.fmu_names_list:
        container.get_fmu(self.fmu_path(fmu_name), fmu_name)

    for port, source in self.input_ports.items():
        container.add_input(source, port.fmu_name, port.port_name)

    for port, target in self.output_ports.items():
        container.add_output(port.fmu_name, port.port_name, target)

    for link in self.links:
        container.add_link(link.from_port.fmu_name, link.from_port.port_name,
                           link.to_port.fmu_name, link.to_port.port_name)

    for drop in self.drop_ports:
        container.drop_port(drop.fmu_name, drop.port_name)

    for port, value in self.start_values.items():
        container.add_start_value(port.fmu_name, port.port_name, value)

    wired = container.add_implicit_rule(auto_input=self.auto_input,
                                        auto_output=self.auto_output,
                                        auto_link=self.auto_link,
                                        auto_parameter=self.auto_parameter,
                                        auto_local=self.auto_local)
    for input_rule in wired.rule_input:
        self.add_input(input_rule[0], input_rule[1], input_rule[2])
    for output_rule in wired.rule_output:
        self.add_output(output_rule[0], output_rule[1], output_rule[2])
    for link_rule in wired.rule_link:
        self.add_link(link_rule[0], link_rule[1], link_rule[2], link_rule[3])
    self.implicit_resolved = True

    if filename is None:
        filename = self.name

    container.make_fmu(filename, self.step_size, mt=self.mt, profiling=self.profiling, sequential=self.sequential,
                       debug=debug, ts_multiplier=self.ts_multiplier, datalog=datalog,
                       mt_threshold=self.mt_threshold)

    for node in self.children.values():
        logger.info(f"Deleting the transient FMU container '{node.name}'.")
        (fmu_directory / node.name).unlink()

Name under which the FMU path is embedded, given the names already used at the same level.

The first instance of a file is named after the file itself. When its base name is already used (the same file, or another file with the same base name), the name is the sibling <stem>-<n><suffix> of path, with the smallest free n: /models/model.fmu gives /models/model-1.fmu. Names are compared by base name, since an embedded FMU is designated by its base name in the built container.

Parameters:

Name Type Description Default
path str

Path of the FMU file, as it is given to AssemblyNode.add_fmu.

required
used_names Iterable[str]

Names already used.

required

Returns:

Name Type Description
str str

path itself, or a sibling of it with a free base name.

Source code in fmu_manipulation_toolbox/assembly.py
def instance_name(path: str, used_names: Iterable[str]) -> str:
    """Name under which the FMU `path` is embedded, given the names already used at the same level.

    The first instance of a file is named after the file itself. When its base name is already used (the same file,
    or another file with the same base name), the name is the sibling `<stem>-<n><suffix>` of `path`, with the
    smallest free `n`: `/models/model.fmu` gives `/models/model-1.fmu`. Names are compared by base name, since an
    embedded FMU is designated by its base name in the built container.

    Args:
        path (str): Path of the FMU file, as it is given to `AssemblyNode.add_fmu`.
        used_names (Iterable[str]): Names already used.

    Returns:
        str: `path` itself, or a sibling of it with a free base name.
    """
    used = {_split_basename(name)[1] for name in used_names}
    directory, basename = _split_basename(path)
    if basename not in used:
        return path
    stem, suffix = os.path.splitext(basename)
    n = 1
    while f"{stem}-{n}{suffix}" in used:
        n += 1
    return f"{directory}{stem}-{n}{suffix}"