ebcpy.simulationapi package
Simulation APIs help you to perform automated simulations for energy and building climate related models. Parameters can easily be updated, and the initialization-process is much more user-friendly than the provided APIs by Dymola or fmpy.
- class ebcpy.simulationapi.SimulationAPI(working_directory: Path | str, model_name: str, **kwargs)[source]
Bases:
object
Base-class for simulation apis. Every simulation-api class must inherit from this class. It defines the structure of each class.
- Parameters:
working_directory (str,Path) – Working directory path
model_name (str) – Name of the model being simulated.
n_cpu (int) – Number of cores to be used by simulation. If None is given, single core will be used. Maximum number equals the cpu count of the device. Warning: Logging is not yet fully working on multiple processes. Output will be written to the stream handler, but not to the created .log files.
save_logs (bool) – If logs should be stored.
- check_unsupported_variables(variables: List[str], type_of_var: str)[source]
Log warnings if variables are not supported.
- classmethod get_simulation_setup_fields()[source]
Return all fields in the chosen SimulationSetup class.
- property result_names: List[str]
The variables names which to store in results.
- Returns:
list: List of string where the string is the name of the variable to store in the result.
- save_for_reproduction(title: str, path: Path | None = None, files: list | None = None, **kwargs)[source]
Save the settings of the SimulationAPI in order to reproduce the settings of the used simulation.
Should be extended by child-classes to allow custom saving.
- Parameters:
title (str) – Title of the study
path (pathlib.Path) – Where to store the .zip file. If not given, self.cd is used.
files (list) – List of files to save along the standard ones. Examples would be plots, tables etc.
kwargs (dict) – All keyword arguments except title, files, and path of the function save_reproduction_archive. Most importantly, log_message may be specified to avoid input during execution.
- set_working_directory(working_directory: Path | str)[source]
Base function for changing the current working directory.
- property sim_setup: SimulationSetupClass
Return current sim_setup
- abstract simulate(parameters: dict | List[dict] | None = None, return_option: str = 'time_series', **kwargs)[source]
Base function for simulating the simulation-model.
- Parameters:
parameters (dict) – Parameters to simulate. Names of parameters are key, values are value of the dict. It is also possible to specify a list of multiple parameter dicts for different parameter variations to be simulated. Default is an empty dict.
return_option (str) – How to handle the simulation results. Options are: - ‘time_series’: Returns a DataFrame with the results and does not store anything. Only variables specified in result_names will be returned. - ‘last_point’: Returns only the last point of the simulation. Relevant for integral metrics like energy consumption. Only variables specified in result_names will be returned. - ‘savepath’: Returns the savepath where the results are stored. Depending on the API, different kwargs may be used to specify file type etc.
savepath (str,Path) – If path is provided, the relevant simulation results will be saved in the given directory. For multiple parameter variations also a list of savepaths for each parameterset can be specified. The savepaths for each parameter set must be unique. Only relevant if return_option equals ‘savepath’. Default is the current working directory.
result_file_name (str) – Name of the result file. Default is ‘resultFile’. For multiple parameter variations a list of names for each result must be specified. Only relevant if return_option equals ‘savepath’.
inputs ((TimeSeriesData, pd.DataFrame)) – Pandas.Dataframe of the input data for simulating the FMU with fmpy
fail_on_error (Boolean) – If True, an error in fmpy will trigger an error in this script. Default is True
- Returns:
str,os.path.normpath filepath: Only if return_option equals ‘savepath’. Filepath of the result file.
- Returns:
dict: Only if return_option equals ‘last_point’.
- Returns:
Union[List[pd.DataFrame],pd.DataFrame]: If parameters are scalar and squeeze=True, a DataFrame with the columns being equal to self.result_names. If multiple set’s of initial values are given, one dataframe for each set is returned in a list
- property variables
All variables of the simulation model
- property worker_idx
Index of the current worker
- pydantic model ebcpy.simulationapi.SimulationSetup[source]
Bases:
BaseModel
pydantic BaseModel child to define relevant parameters to setup the simulation.
- Config:
extra: str = forbid
- Fields:
- Validators:
- field output_interval: float = 1
The step size of the simulation and thus also output interval of results.
- pydantic model ebcpy.simulationapi.Variable[source]
Bases:
BaseModel
Data-Class to store relevant information for a simulation variable (input, parameter, output or local/state).
- Fields:
- Validators:
- field max: Any = None
Maximal value (upper bound) of the variables value. Only for ints and floats variables.
- Validated by:
- field min: Any = None
Minimal value (lower bound) of the variables value. Only for ints and floats variables.
- Validated by:
Submodules
ebcpy.simulationapi.dymola_api module
Module containing the DymolaAPI used for simulation of Modelica-Models.
- class ebcpy.simulationapi.dymola_api.DymolaAPI(working_directory: Path | str, model_name: str | None = None, packages: List[Path | str] | None = None, **kwargs)[source]
Bases:
SimulationAPI
API to a Dymola instance.
- Parameters:
working_directory (str,Path) – Dirpath for the current working directory of dymola
model_name (str) – Name of the model to be simulated. If None, it has to be provided prior to or when calling simulate().
packages (list) – List with path’s to the packages needed to simulate the model
show_window (Boolean) – True to show the Dymola window. Default is False
modify_structural_parameters (Boolean) – True to automatically set the structural parameters of the simulation model via Modelica modifiers. Default is True. See also the keyword
structural_parameters
of thesimulate
function.equidistant_output (Boolean) – If True (Default), Dymola stores variables in an equisdistant output and does not store variables at events.
n_restart (int) – Number of iterations after which Dymola should restart. This is done to free memory. Default value -1. For values below 1 Dymola does not restart.
extract_variables (bool) – If True (the default), all variables of the model will be extracted on init of this class. This required translating the model.
debug (bool) – If True (not the default), the dymola instance is not closed on exit of the python script. This allows further debugging in dymola itself if API-functions cause a python error.
mos_script_pre (str) – Path to a valid mos-script for Modelica/Dymola. If given, the script is executed prior to laoding any package specified in this API. May be relevant for handling version conflicts.
mos_script_post (str) – Path to a valid mos-script for Modelica/Dymola. If given, the script is executed before closing Dymola.
dymola_version (str) –
Version of Dymola to use. If not given, newest version will be used. If given, the Version needs to be equal to the folder name of your installation.
Example: If you have two versions installed at
C://Program Files//Dymola 2021
andC://Program Files//Dymola 2020x
and you want to use Dymola 2020x, specify
dymola_version='Dymola 2020x'
.This parameter is overwritten if
dymola_path
is specified.dymola_path (str) – Path to the dymola installation on the device. Necessary e.g. on linux, if we can’t find the path automatically. Example:
dymola_path="C://Program Files//Dymola 2020x"
dymola_interface_path (str) – Direct path to the .egg-file of the dymola interface. Only relevant when the dymola_path differs from the interface path.
dymola_exe_path (str) – Direct path to the dymola executable. Only relevant if the dymola installation do not follow the official guideline.
time_delay_between_starts (float) – If starting multiple Dymola instances on multiple cores, a time delay between each start avoids weird behaviour, such as requiring to set the C-Compiler again as Dymola overrides the default .dymx setup file. If you start e.g. 20 instances and specify time_delay_between_starts=5, each 5 seconds one instance will start, taking in total 100 seconds. Default is no delay.
Example:
>>> import os >>> from ebcpy import DymolaAPI >>> # Specify the model name >>> model_name = "Modelica.Thermal.FluidHeatFlow.Examples.PumpAndValve" >>> dym_api = DymolaAPI(working_directory=os.getcwd(), >>> model_name=model_name, >>> packages=[], >>> show_window=True) >>> dym_api.sim_setup = {"start_time": 100, >>> "stop_time": 200} >>> dym_api.simulate() >>> dym_api.close()
- dymola = None
- extract_model_variables()[source]
Extract all variables of the model by translating it and then processing the dsin using the manipulate_ds module.
- static get_dymola_exe_path(dymola_install_dir, dymola_name=None)[source]
Function to get the path of the dymola exe-file on the current used machine.
- static get_dymola_install_paths(basedir=None)[source]
Function to get all paths of dymola installations on the used machine. Supported platforms are: * Windows * Linux * Mac OS X If multiple installation of Dymola are found, the newest version will be returned. This assumes the names are sortable, e.g. Dymola 2020, Dymola 2019 etc.
- Parameters:
basedir (str) – The base-directory to search for the dymola-installation. The default value depends on the platform one is using. On Windows it is “C://Program Files” or “C://Program Files (x86)” (for 64 bit) On Linux it is “/opt” (based on our ci-Docker configuration On Mac OS X “/Application” (based on the default)
- Returns:
str Path to the dymola-installation
- static get_dymola_interface_path(dymola_install_dir)[source]
Function to get the path of the newest dymola interface installment on the used machine
- Parameters:
dymola_install_dir (str) – The dymola installation folder. Example: “C://Program Files//Dymola 2020”
- Returns:
str Path to the dymola.egg-file or .whl file (for 2024 refresh 1 or newer versions)
- import_initial(filepath)[source]
Load given dsfinal.txt into dymola
- Parameters:
filepath (str,os.path.normpath) – Path to the dsfinal.txt to be loaded
- save_for_reproduction(title: str, path: Path | None = None, files: list | None = None, save_total_model: bool = True, export_fmu: bool = True, **kwargs)[source]
Additionally to the basic reproduction, add info for Dymola packages.
Content which is saved: - DymolaAPI configuration - Information on Dymola: Version, flags - All loaded packages - Total model, if save_total_model = True - FMU, if export_fmu = True
- set_compiler(name, path, dll=False, dde=False, opc=False)[source]
Set up the compiler and compiler options on Windows. Optional: Specify if you want to enable dll, dde or opc.
- Parameters:
name (str) – Name of the compiler, avaiable options: - ‘vs’: Visual Studio - ‘gcc’: GCC
path (str,os.path.normpath) – Path to the compiler files. Example for name=’vs’: path=’C:/Program Files (x86)/Microsoft Visual Studio 10.0/Vc’ Example for name=’gcc’: path=’C:/MinGW/bin/gcc’
dll (Boolean) – Set option for dll support. Check Dymolas Manual on what this exactly does.
dde (Boolean) – Set option for dde support. Check Dymolas Manual on what this exactly does.
opc (Boolean) – Set option for opc support. Check Dymolas Manual on what this exactly does.
- Returns:
True, on success.
- set_dymola_cd(dymola, cd)[source]
Set the cd of the Dymola Instance. Before calling the Function, create the path and convert to a modelica-normpath.
- simulate(parameters: dict | List[dict] | None = None, return_option: str = 'time_series', **kwargs)[source]
Simulate the given parameters.
Additional settings:
- Parameters:
model_names (List[str]) – List of Dymola model-names to simulate. Should be either the size of parameters or parameters needs to be sized 1. Keep in mind that different models may use different parameters!
show_eventlog (Boolean) – Default False. True to show evenlog of simulation (advanced)
squeeze (Boolean) – Default True. If only one set of initialValues is provided, a DataFrame is returned directly instead of a list.
table_name (str) – If inputs are given, you have to specify the name of the table in the instance of CombiTimeTable. In order for the inputs to work the value should be equal to the value of ‘tableName’ in Modelica.
file_name (str) – If inputs are given, you have to specify the file_name of the table in the instance of CombiTimeTable. In order for the inputs to work the value should be equal to the value of ‘fileName’ in Modelica.
structural_parameters (List[str]) –
A list containing all parameter names which are structural in Modelica. This means a modifier has to be created in order to change the value of this parameter. Internally, the given list is added to the known states of the model. Hence, you only have to specify this keyword argument if your structural parameter does not appear in the dsin.txt file created during translation.
Example: Changing a record in a model:
>>> sim_api.simulate( >>> parameters={"parameterPipe": "AixLib.DataBase.Pipes.PE_X.DIN_16893_SDR11_d160()"}, >>> structural_parameters=["parameterPipe"])
- to_dict()[source]
Store the most relevant information of this class into a dictionary. This may be used for future configuration.
- Returns:
dict config: Dictionary with keys to re-init this class.
- pydantic model ebcpy.simulationapi.dymola_api.DymolaSimulationSetup[source]
Bases:
SimulationSetup
Adds
tolerance
to the list of possible setup fields.- Config:
extra: str = forbid
- Fields:
- Validators:
ebcpy.simulationapi.fmu module
Module for classes using a fmu to simulate models.
- class ebcpy.simulationapi.fmu.FMU_API(working_directory, model_name, **kwargs)[source]
Bases:
SimulationAPI
Class for simulation using the fmpy library and a functional mockup interface as a model input.
- Parameters:
log_fmu (bool) – Whether to print fmu messages or not.
Example:
>>> import matplotlib.pyplot as plt >>> from ebcpy import FMU_API >>> # Select any valid fmu. Replace the line below if >>> # you don't have this file on your device. >>> model_name = "Path to your fmu" >>> fmu_api = FMU_API(model_name) >>> fmu_api.sim_setup = {"stop_time": 3600} >>> result_df = fmu_api.simulate() >>> fmu_api.close() >>> # Select an exemplary column >>> col = result_df.columns[0] >>> plt.plot(result_df[col], label=col) >>> _ = plt.legend() >>> _ = plt.show()
New in version 0.1.7.
- save_for_reproduction(title: str, path: Path | None = None, files: list | None = None, **kwargs)[source]
Additionally to the basic reproduction, add info for FMU files.
- setup_fmu_instance()[source]
Manually set up and extract the data to avoid this step in the simulate function.
- simulate(parameters: dict | List[dict] | None = None, return_option: str = 'time_series', **kwargs)[source]
Perform the single simulation for the given unzip directory and fmu_instance. See the docstring of simulate() for information on kwargs.
Additional kwargs:
- Parameters:
result_file_suffix (str) – Suffix of the result file. Supported options can be extracted from the TimeSeriesData.save() function. Default is ‘csv’.
parquet_engine (str) – The engine to use for the data format parquet. Supported options can be extracted from the TimeSeriesData.save() function. Default is ‘pyarrow’.
- pydantic model ebcpy.simulationapi.fmu.FMU_Setup[source]
Bases:
SimulationSetup
Add’s custom setup parameters for simulating FMU’s to the basic SimulationSetup
- Config:
extra: str = forbid
- Fields:
- Validators: