Skip to content

Changes to FmuBuilder.build_FMU. 1. Unload the script module after th… #247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 3, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions pythonfmu/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,6 @@ def get_model_description(filepath: Path, module_name: str, class_name: str) ->
# Produce the xml
return instance.modelName, instance.to_xml()


class FmuBuilder:

@staticmethod
Expand All @@ -201,13 +200,31 @@ def build_FMU(
newargs: dict | None = None,
**options,
) -> Path:
""" Build the FMU from the Python script, additional project files and documentatiion.

Args:
script_file (FilePath): The main Python script containing the Python model class
dest (FilePath)='.': Optional destination path.
If this is a full file name with '.fmu' extension, it is used as FMU file name.
Otherwise the FMU file name is constructed automatically from the script file name.
project_files (Iterable[FilePath]): Optional list/tuple of additional project files needed to run model
documentation_folder (FilePath): Optional additional documentation (beyond modelDescription)
newargs (dict): Optional dict of replacements of model class __init__() arguments.
"""
script_file = Path(script_file)
if not script_file.exists():
raise ValueError(f"No such file {script_file!s}")
if not script_file.suffix.endswith(".py"):
raise ValueError(f"File {script_file!s} must have extension '.py'!")

dest = Path(dest)
if ( dest.suffix == '.fmu' and # explicit FMU file name shall always have suffix '.fmu'
( dest.is_file() or # Note that .is_file() returns False if the file does not yet exist
not dest.is_dir())): # if dest represents an (existing) directory we cannot interpret as file!
dest_file = dest
dest = dest.parent
else:
dest_file = "" # FMU file name is automatically generated below
if not dest.exists():
dest.mkdir(parents=True)
project_files = set(map(Path, project_files))
Expand Down Expand Up @@ -261,13 +278,14 @@ def build_FMU(
temp_dest = temp_dir / file_.name
shutil.copytree(file_, temp_dest)
else:
assert file_.name != script_file.name, ( # avoid the inclusion of the script in project files
"It seems that the script file is included a second time in the project_files")
Comment on lines +281 to +282

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if we want to only check the name of the file for deciding the assertion. The file name be same in different python modules.

shutil.copy2(file_, temp_dir)

model_identifier, xml = get_model_description(
temp_dir.absolute() / script_file.name, module_name, model_class.__name__
)

dest_file = dest / f"{model_identifier}.fmu"
dest_file = dest / f"{model_identifier}.fmu" if dest_file == "" else dest_file

type_node = xml.find("CoSimulation")
option_names = [opt.name for opt in FMI2_MODEL_OPTIONS]
Expand Down Expand Up @@ -317,6 +335,8 @@ def build_FMU(
zip_fmu.writestr(
"modelDescription.xml", xml_str.toprettyxml(encoding="UTF-8")
)
if newargs is not None:
sys.modules.pop(Path(script_file).stem) # otherwise old script may be active when loading the FMU!
Comment on lines +338 to +339
Copy link

@davidhjp01 davidhjp01 Jul 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

module syntax can be aaa.bbb.ccc. Path.stem seems to only return filename without the final suffix - but I don't recall we ever put the main script file in some nested module, so probably this is okay?


return dest_file

Expand Down