uesgraphs.systemmodels package
Submodules
uesgraphs.systemmodels.systemmodelheating module
This module includes the UESModel graph to write Modelica code from uesgraphs
- uesgraphs.systemmodels.systemmodelheating.set_up_logger(name, log_dir=None, level=40)[source]
Sets up a configured logger with file handler.
Creates a logger with specified name and logging level. Log files are stored in a directory with timestamp in filename. If no directory is specified, the system’s temporary directory is used.
- Parameters:
- Returns:
Configured logger object
- Return type:
Example
>>> logger = set_up_logger("my_app", "/var/log", logging.INFO) >>> logger.info("Application started")
Notes
Log filename format: {name}_{YYYYMMDD_HHMMSS}.log
Log entry format: time - logger_name - [file:line] - level - message
- class uesgraphs.systemmodels.systemmodelheating.SystemModelHeating(model_name='Test', network_type='heating', logger=None)[source]
Bases:
UESGraphWrites Modelica code for system models from uesgraphs information
While a uesgraph object uses edges to describe pipe connections between nodes, the Modelica model needs a specific node representing the pipe model and connections between connectors of each model. Therefore, UESModel initializes a new graph object from information of an uesgraph object. At the current stage, the uesgraph object should be a subgraph that only contains one network.
- Parameters:
model_name (str) –
model (Name of the) –
file (will be used for naming components and output) –
- network_type
Type of network to be modeled
- Type:
{‘heating’}
- add_ground_around_pipe
For True, the ground around the pipe will be modeled by an RC network. This requires values for RExt, RExtRem, CExt, T_ground_start, and n for each edge to parameterize a model using AixLib.ThermalZones.ReducedOrder.RC.BaseClasses.ExteriorWall for the ground
- Type:
boolean
- __init__(model_name='Test', network_type='heating', logger=None)[source]
Construct SystemModelHeating class.
- property time
- property doc_string
- property medium
- import_nodes_from_uesgraph(uesgraph_input, logger=None)[source]
Adds uesgraph_input’s nodes to the model graph
As a first step for the conversion from a uesgraph to a uesmodel graph, this method imports the uesgraph’s nodes to the nodes of this class. The method conserves each node’s attributes, but converts the x and y coordinates from GIS data to coordinates on the canvas for graphical representation of the Modelica model.
- Parameters:
uesgraph_input (uesgraphs.uesgraph.UESGraph object) – At current stage, this uesgraph should contain only 1 network of 1 type that is indexed in the corrsponding nodelist as ‘default’
logger (logging.Logger, optional) – Logger instance for debugging
- add_pipe_node(name=None, position=None, logger=None)[source]
Adds a pipe node to the graph
- Parameters:
name (str, int, or float) – A name for the building represented by this node. If None is given, the newly assigned node number will also be used as name.
position (shapely.geometry.Point object) – New node’s position
logger (logging.Logger, optional) – Logger instance for debugging
- Returns:
node_number – Identifier of the newly created pipe node
- Return type:
- remove_pipe_node(node_number, logger=None)[source]
Removes the specified pipe node from the graph
- Parameters:
node_number (int) – Identifier of the node in the graph
logger (logging.Logger, optional) – Logger instance for debugging
- import_pipes_from_uesgraph(uesgraph_input, logger=None)[source]
Adds uesgraph_input’s pipe edges as nodes to uesmodel graph
The second step for conversion of a uesgraph to a uesmodel graph involves the conversion of pipes from edges to nodes of their own. They keep their attributes like length and diameter and in addition are assigned x and y coordinates which locate them in the middle between the nodes they originally connected. Furthermore, new edges are created representing the connection from the pipe model’s ports to the next nodes.
- Parameters:
uesgraph_input (uesgraphs.uesgraph.UESGraph object) – At current stage, this uesgraph should contain only 1 network of 1 type that is indexed in the corresponding nodelist as ‘default’
logger (logging.Logger, optional) – Logger instance for debugging
- import_from_uesgraph(uesgraph_input, logger=None)[source]
Imports nodes and edges from uesgraph and transform edges to nodes which will later be pipes in modelica
- Parameters:
uesgraph_input (uesgraphs.uesgraph.UESGraph object) – At current stage, this uesgraph should contain only 1 network of 1 type that is indexed in the corresponding nodelist as ‘default’
logger (logging.Logger, optional) – Logger instance for debugging
- set_connection(remove_network_nodes=True, logger=None)[source]
Sets connections between supplies, pipes and buildings
To connect supplies, pipes, and buildings, each edge of the model graph is assigned four attributes (‘con1’, ‘con2’, ‘con1R’, ‘con2R’) that characterize the connected node (supply, pipe, building) and the used port of the node (port_a, port_b). In case the node is a supply, a pipe, or a building, the attribute (con1, con2, con1R, con2R) contains the corresponding Modelica-Code. In case the node is a network-node the attribute only contains the number of the node, since network-nodes can be connected to more then one node. The connections of the network-nodes is written later on in method ‘write_network_model()’.
- For remove_network_nodes is True, ports depend on type of node:
pipe network building supply
con1 a/b node # a b con1R a/b node # b a con2 a/b node # a b con2R a/b node # b a
- Parameters:
remove_network_nodes (boolean) – If True, all connections at network nodes will be clustered onto connecting ports. If False, network nodes will get their own representation in the conncetion network.
logger (logging.Logger, optional) – Logger instance for debugging
- write_medium_definition()[source]
Write the rendered Modelica code for the Medium definition
- Returns:
mo_medium – Rendered Modelica code for the medium definition
- Return type:
- write_supply_definitions()[source]
Write the rendered Modelica code for the supply model definitions
- Returns:
mo_supplies – Rendered Modelica code for the supply definitions
- Return type:
- write_t_ground_definitions()[source]
Write the rendered Modelica code for the ground temperature def
- Returns:
mo_t_ground – Rendered Modelica code for the ground temperature definition
- Return type:
- write_demand_definitions()[source]
Write the rendered Modelica code for the demand model definitions
- Returns:
mo_demands – Rendered Modelica code for the demand definitions
- Return type:
- write_pipe_definitions()[source]
Write the rendered Modelica code for the pipe model definitions
- Returns:
mo_pipes – Rendered Modelica code for the pipe definitions
- Return type:
- write_annotations()[source]
Write the rendered Modelica code for annotations
- Returns:
mo_ann – Rendered Modelica code for the annotations
- Return type:
- write_input_connections()[source]
Write the rendered Modelica code for the input connections
- Returns:
mo_con – Rendered Modelica code for the input connections
- Return type:
- write_network_connections()[source]
Write the rendered Modelica code for the network connections
- Returns:
mo_con – Rendered Modelica code for the network connections
- Return type:
- write_network_model(save_at)[source]
Writes a network model to Modelica code file
- Parameters:
save_at (str) – Path where to create the subfolders, in which the Modelica files are saved
- write_modelica_package(save_at)[source]
Writes a system model and inputs to Modelica package
- Parameters:
save_at (str) – Path where to create the subfolders, in which the Modelica files are saved
- write_modelica_system(save_at)[source]
Writes a system model with inputs
- Parameters:
save_at (str) – Path where to store the generated model
- write_input_txt(save_as, name_variable, time, values, digits, description='')[source]
Writes a time series to input text file for Resources directory
- Parameters:
save_as (str) – File to store input data to
name_variable (str) – Name of the variable to be referenced in model
time (list) – Time vector as float in seconds
values (list) – The input values corresponding to the the time steps
digits (int) – Number of digits to round to in output table
description (str) – Optional description to describe the input data
- set_control_pressure(name_supply, dp, name_building='max_distance', p_max=1000000.0, k=None, ti=None)[source]
Set a pressure control to provide a given dp at a building
- Parameters:
name_supply (str) – Name of supply to control the pressure in the network
dp (float) – Pressure difference to be held at reference building
name_building (str) – Name of the reference building for the network. For default ‘max_distance’, the building with the greatest distance from the supply unit will be chosen
p_max (float) – Maximum pressure allowed for the pressure controller
k (int) – gain of controller
ti (int) – time constant for integrator block
uesgraphs.systemmodels.templates module
This module includes the UESModel graph to write Modelica code from uesgraphs
- class uesgraphs.systemmodels.templates.UESTemplates(model_name, model_type, template_path=None)[source]
Bases:
objectA class to handle templates for model generation with uesgraphs.
- model_name
Name of the modelica model. (e.g. AixLib.Fluid.DistrictHeatingCooling.Supplies.OpenLoop.SourceIdeal)
- Type:
- call_function(function_string)[source]
Calls function in template .. attribute:: function_string
Name of the function in the .mako file.
- type:
str
- generate_new_template(path_library)[source]
Generates a new template based on parameter and package information of the given class :param path_library: Path to package.mo of the used library (e.g. C:...Aixlibpackage.mo)
or list of paths to multiple used libraries
- render(node_data, i=None, number_of_instances=None, package_name=None)[source]
Write Modelica code for Demands.OpenLoop.HeatPumpCarnot
- classmethod generate_bulk(models_dict: Dict[str, List[str]], library_path: str | List[str], workspace: str | None = None, rigorous: bool = False) Dict[str, str][source]
Generate multiple templates in bulk.
- Parameters:
models_dict – Dictionary mapping model types to lists of model names. Example: {“Demand”: [“Model1”, “Model2”], “Pipe”: [“Model3”]}
library_path – Path to Modelica library or list of library paths
workspace – Directory for generated templates (optional)
rigorous – If True, auto-overwrite existing templates without confirmation
- Returns:
Dictionary mapping model names to their template paths or error messages
Example
>>> results = UESTemplates.generate_bulk( ... {"Demand": ["AixLib.Fluid.SomeModel"]}, ... "/path/to/aixlib" ... )
- classmethod generate_from_config(config_file: str, library_path: str | List[str] | None = None, **kwargs) Dict[str, str][source]
Generate templates from JSON configuration file.
- Parameters:
config_file – Path to JSON configuration file
library_path – Path to Modelica library, list of paths, or None for auto-detection
**kwargs – Additional arguments passed to generate_bulk (workspace, rigorous, etc.)
- Returns:
Dictionary mapping model names to template paths or error messages
Example
>>> results = UESTemplates.generate_from_config( ... "data/templates/template_aixlib_components.json" ... )
- class uesgraphs.systemmodels.templates.Parameter(value: Any, type: str, category: str = '', description: str = '', unit: str = '')[source]
Bases:
NamedTupleA named tuple representing a modelica parameter.
- value
The value of the parameter.
- Type:
Any
- type
The type of the parameter in model. Like Modelica.Units.SI.SpecificHeatCapacity or Boolean
- Type:
- category
The category of the parameter. Either “optional” or “mandatory”. Specified in _extract_parameters. Important for the template generation.
- Type:
str, optional
- description
A brief description of the parameter. Defaults to “”. Not needed yet.
- Type:
str, optional
- unit
The unit of measurement for the parameter. Defaults to “”. Not needed yet.
- Type:
str, optional
Example
>>> param = Parameter(value=42, type="Integer", category="mandatory", ... description="The answer to life, the universe, and everything", ... unit="") >>> print(param.value) 42 >>> print(param.category) mandatory
- class uesgraphs.systemmodels.templates.Connector(type)[source]
Bases:
NamedTuple
- class uesgraphs.systemmodels.templates.ModelInfoExtractor(path_library: str, log_level: int = 20)[source]
Bases:
objectA class to extract model information from OpenModelica classes.
- list_main_models()[source]
Lists all main models in the loaded library.
This method queries OpenModelica for a list of all main models in the currently loaded library. It returns a list of class names that can be used for further analysis.
Returns:
- List[str]
A list of class names representing the main models in the loaded library.
Notes:
The method logs debug information about the found classes.
uesgraphs.systemmodels.utilities module
This module collects utilities and convenience functions for model generation
- uesgraphs.systemmodels.utilities.set_up_logger(name, log_dir=None, level=20)[source]
Set up a file-based logger with timestamp and detailed formatting.
- Parameters:
- Returns:
Configured logger instance writing to timestamped file
- Return type:
- uesgraphs.systemmodels.utilities.prepare_graph(graph, T_supply, p_supply, T_return, p_return, dT_design, m_flow_nominal=None, dp_nominal=None, dT_building=None, T_supply_building=None, cop_nominal=None, T_con_nominal=None, T_eva_nominal=None, dTEva_nominal=None, dTCon_nominal=None)[source]
Adds data for model generation to the uesgraph
- Parameters:
graph (uesgraphs.uesgraph.UESGraph) – Network graph with all data for the model
T_supply (list) – Design supply temperature in K
p_supply (float) – Prescribed supply pressure in Pa
T_return (float) – Design return temperature in K
p_return (float) – Prescribed return pressure in Pa
dT_design (float) – Design temperature difference over substation in K
m_flow_nominal (float) – Nominal mass flow rate in kg/s
dp_nominal (float) – Nominal pressure drop over the substation in Pa
dT_building (float) – Prescribed temperature difference for the building heating system in K
T_supply_building (float) – Supply temperature of the building heating system in K
cop_nominal (float) – A nominal COP for substations that use a heat pump
T_con_nominal (float) – Nominal condenser temperature of heat pump
T_eva_nominal (float) – Nominal evaporator temperature of heat pump
dTEva_nominal (float (default -10 K)) – Nominal temperature difference at heat pump evaporator
dTCon_nominal (float (default 10 K)) – Nominal temperature difference at heat pump condenser
- uesgraphs.systemmodels.utilities.create_model(name, save_at, graph, stop_time, timestep, model_supply, model_demand, model_pipe, model_medium, model_ground, T_nominal, p_nominal, solver=None, tolerance=1e-05, params_kusuda=None, fraction_glycol=None, pressure_control_supply=None, pressure_control_dp=None, pressure_control_building=None, pressure_control_p_max=None, pressure_control_k=None, pressure_control_ti=None, t_ground_prescribed=None, short_pipes_static=None, meta_data=None, logger=None)[source]
Generic model generation for setup defined through the parameters
- Parameters:
name (str) – Name of the model (First character will be capitalized, cannot start with digit)
save_at (str) – Directory where to store the generated model package
graph (uesgraphs.uesgraph.UESGraph) – Network graph with all necessary data for model generation
stop_time (int) – Stop time of the simulation in seconds
timestep (int) – Timestep of the simulation in seconds
model_supply (str) – One of the supply models supported by uesmodels
model_demand (str) – One of the demand models supported by uesmodels
model_pipe (str) – One of the pipe models supported by uesmodels
model_medium (str) – One of the medium models supported by uesmodels
model_ground (str) – One of the ground models supported by uesmodels
T_nominal (float) – Nominal temperature for model initialization in K
p_nominal (float) – Nominal pressure for model initialization in Pa
solver (str) – Solver to use in dymola
tolerance (float) – Solver tolerance to store in the model
params_kusuda (dict) – Kusuda ground model parameters. Default values are for Aachen taken from TRY file
fraction_glycol (float) – Value between 0 (100 % water) and 0.6 (60 % glycol) for the medium in the network
pressure_control_supply (str) – Name of supply to control the pressure in the network
pressure_control_dp (float) – Pressure difference to be held at reference building
pressure_control_building (str) – Name of the reference building for the network. For default ‘max_distance’, the building with the greatest distance from the supply unit will be chosen
pressure_control_p_max (float) – Maximum pressure allowed for the pressure controller
pressure_control_k (int) – gain of controller
pressure_control_ti (int) – time constant for integrator block
t_ground_prescribed (list) – List of ground temperatures for every time step when using model_ground=”t_ground_table”
short_pipes_static (float) – The float value specifies the length of pipes considered short. If a pipe length is smaller than the value for short_pipes_static, a static pipe model will be used for it.
meta_data (dict) – Dictionary with meta data
logger (logging.Logger, optional) – Logger instance for debugging
- uesgraphs.systemmodels.utilities.save_system_model_to_json(model, filepath)[source]
Save a SystemModelHeating object to a JSON file with comprehensive attribute capturing.
- Parameters:
model – SystemModelHeating - The model to save
filepath – str - Path where the JSON file should be saved
- Returns:
str - Path to the saved file
- uesgraphs.systemmodels.utilities.load_system_model_from_json(filepath)[source]
Load a SystemModelHeating object from a JSON file, respecting the constructor’s signature.
- Parameters:
filepath – str - Path to the JSON file
- Returns:
SystemModelHeating - The reconstructed model
- uesgraphs.systemmodels.utilities.estimate_fac(graph, u_form_distance=25, n_gate_valve=2.0)[source]
Calculate fac for all pipes based on m_flow_nominal
- Parameters:
graph (uesgraphs.uesgraph.UESGraph) – Graph of the network
u_form_distance (int) – distance between U-form for thermal stress of pipes. Default: every 25m one U-Form is added
n_gate_valve (float) – number of gate valves per pipe. For average values, n_gate_valve is a float. Default: 2 Gate valves per pipe.
- Returns:
graph – Graph of the network
- Return type:
- uesgraphs.systemmodels.utilities.estimate_m_flow_nominal(graph, dT_design, network_type, cp=4184)[source]
DEPRECATED: Use estimate_m_flow_demand_based instead.
This function is maintained for backward compatibility and will be removed in version X.Y.Z.
Calculate all design mass flows based on nominal loads for each edge.
- Parameters:
graph (uesgraphs.uesgraph.UESGraph) – Graph of the network
dT_design (float) – Design temperature difference between supply and return in K
network_type (str) – {‘heating’, ‘cooling’}
cp (float) – Specific heat capacity of fluid in the network
- Returns:
graph – Graph of the network
- Return type:
- uesgraphs.systemmodels.utilities.estimate_m_flow_nominal_tablebased(graph, network_type)[source]
Calculate m_flow_nominal based on the pipe diameter.
This function calculates the m_flow_nominal based on the pipe diameter and according to the isoplus table for suggested m_flows for specific pipe diameters with a average pressure loss of 70 Pa/m. Link: http://www.isoplus.de/fileadmin/user_upload/downloads/documents/germany/Catalogue_German/Kapitel_2_Starre_Verbundsysteme.pdf page 9
- Parameters:
graph (uesgraphs.uesgraph.UESGraph) – Graph of the network
network_type (str) – {‘heating’, ‘cooling’}
- Returns:
graph – Graph of the network
- Return type:
- uesgraphs.systemmodels.utilities.size_hydronic_network(graph: Any, m_flow_key=None, catalog=None, dT_attribute: str = 'dT_Network', network_type: str = 'heating', demand_attribute: str = 'input_heat', load_scenario: str = 'peak_load', cp: float = 4184, logger: Logger | None = None) Any[source]
- uesgraphs.systemmodels.utilities.estimate_m_flow_demand_based(graph: Any, network_type: str = 'heating', demand_attribute: str = 'input_heat', load_scenario: str = 'peak_load', cp: float = 4184, dT_attribute: str = 'dT_Network', logger: Logger | None = None) Any[source]
Estimates mass flow for each edge by calculating flows at demand nodes and propagating backwards.
This function implements a physically correct approach where mass flows are calculated at each demand node based on their specific load and temperature difference, then aggregated backwards through the network following mass conservation principles.
- Parameters:
graph (UESGraph or nx.Graph) – The graph representing the network with nodelist_building attribute.
network_type (str, optional) – Type of network, default is “heating”. Must be “heating” or “cooling”.
demand_attribute (str, optional) – Attribute name containing load values in demand nodes, default is “input_heat”.
load_scenario (str, optional) – Load scenario for calculation, default is “peak_load”. Options: “peak_load” (maximum value) or “average_load” (mean value).
cp (float, optional) – Specific heat capacity of the fluid in J/(kg*K), default is 4184.
dT_attribute (str) – Node attribute name for temperature difference values in Kelvin. Must be present in all demand nodes with positive numeric values. Used for individual mass flow calculations at each demand node.
logger (logging.Logger, optional) – Logger instance for logging messages. If None, creates a default logger.
- Returns:
graph – Input graph with additional edge attributes: - m_flow_{load_scenario}: Mass flow rate in kg/s for each edge - contributing_demands_{load_scenario}: List of demand nodes contributing to edge flow - supply_attribution_{load_scenario}: Dictionary showing which supply serves which demands
- Return type:
UESGraph or nx.Graph
- Raises:
TypeError – If graph does not have required nodelist_building attribute.
ValueError – If network_type or load_scenario parameters are invalid. If no supply or demand nodes are found. If required node attributes are missing.
- uesgraphs.systemmodels.utilities.build_flow_paths(graph: Any, supply_nodes: List[Any], demand_nodes: List[Any], logger: Logger) Dict[Tuple[Any, Any], List[Tuple[Any, Any]]][source]
Build flow paths from each supply node to reachable demand nodes.
This function identifies all supply-demand pairs that are connected and determines the shortest path between them, converting paths to edge lists.
- Parameters:
graph (UESGraph or nx.Graph) – Network graph
supply_nodes (List[Any]) – List of supply node identifiers
demand_nodes (List[Any]) – List of demand node identifiers
logger (logging.Logger) – Logger for status messages
- Returns:
Dictionary mapping (supply, demand) tuples to lists of edges in the flow path
- Return type:
Dict[Tuple[Any, Any], List[Tuple[Any, Any]]]
- uesgraphs.systemmodels.utilities.get_pipe_catalog_DN_m_flow(graph, pipe_catalog: DataFrame, logger: Logger, mass_flow_key: str, dn_key: str, diameter_key: str, robust: bool = True) None[source]
Assign pipe diameters to edges based on mass flow and catalog data.
- Parameters:
graph (Graph) – Network graph with edges containing mass flow data
pipe_catalog (pd.DataFrame) – Catalog with columns: DN, inner_diameter, mass_flow_min, mass_flow_max
logger (logging.Logger) – Logger instance
mass_flow_key (str) – Edge attribute containing mass flow [kg/s]
dn_key (str) – Edge attribute to store DN (default: “DN”)
diameter_key (str) – Edge attribute to store diameter [m] (default: “diameter”)
robust (bool) – If True, selects next larger pipe when no exact match (default: True)
- uesgraphs.systemmodels.utilities.load_pipe_catalog(catalog_name: str = 'isoplus', custom_path: str | None = None) DataFrame[source]
Load pipe catalog data from CSV file in the data/pipe_catalogs directory.
This function loads manufacturer pipe catalog data containing pipe dimensions and flow capacities for different nominal diameters (DN). The catalog files are expected to be located in the data/pipe_catalogs subdirectory relative to the systemmodels module.
- Parameters:
catalog_name (str, optional) – Name of the pipe catalog to load (default: “isoplus”) The function will look for a file named “{catalog_name}.csv”
- Returns:
DataFrame containing pipe catalog data with columns: - DN: Nominal diameter [designated, e.g. DN20] - wall_thickness: Pipe wall thickness [m] - inner_diameter: Inner pipe diameter [m] - mass_flow_min: Minimum mass flow capacity [kg/s] - mass_flow_max: Maximum mass flow capacity [kg/s]
- Return type:
pd.DataFrame
- Raises:
FileNotFoundError – If the specified catalog file does not exist
ValueError – If the catalog file exists but contains invalid data structure
Examples
>>> catalog = load_pipe_catalog("isoplus") >>> print(catalog.columns.tolist()) ['DN', 'wall_thickness', 'inner_diameter', 'mass_flow_min', 'mass_flow_max']
>>> # Load different catalog (if available) >>> rehau_catalog = load_pipe_catalog("rehau")
Notes
The CSV files can contain comment lines starting with ‘#’ which will be automatically ignored during loading. This allows for metadata and source information to be stored directly in the catalog files.
The function expects the catalog files to be located at: {module_directory}/uesgraphs/data/pipe_catalogs/{catalog_name}.csv
- uesgraphs.systemmodels.utilities.get_inner_diameter_from_DN(dn_value, catalog_name='isoplus', custom_path: str | None = None)[source]
Quick lookup for inner diameter based on DN value only.
Simplified version for imports that only have DN information (like GeoJSON) without mass flow data.
- Parameters:
- Returns:
Inner diameter in meters, or None if not found
- Return type:
Notes
For more sophisticated selection based on mass flow, use get_pipe_catalog_DN_m_flow() instead.