model
Package
Modules
model module
- class Model(id)[source]
Bases:
objectA unified interface for building digital twin models.
- Parameters:
id (
str) – Unique identifier for the model.
This class serves as a composed interface that integrates both simulation and semantic modeling capabilities for building digital twins. It combines the functionality of
SimulationModelandSemanticModelinto a single, user-friendly interface.Composition Architecture:
The Model class acts as a facade that orchestrates two core components:
SimulationModel: Handles the computational aspects including cycle removal (Algorithm 1), topological sorting (Algorithm 2), component management, and preparation for simulation execution.
SemanticModel: Manages the ontological representation using SAREF4SYST, RDF graphs, semantic queries, and metadata for interoperability.
Key Responsibilities:
Unified Interface: Provides a single entry point for both simulation and semantic operations
Component Management: Delegates component operations to the appropriate underlying model
Model Lifecycle: Orchestrates loading, validation, and execution preparation
Data Integration: Coordinates between semantic metadata and simulation execution
Interoperability: Ensures consistent SAREF-compliant representation across both models
Usage Pattern:
Users typically interact with this Model class rather than directly with SimulationModel or SemanticModel. The Model class automatically handles the coordination between the two underlying models, ensuring consistency and proper initialization order.
- simulation_model
The underlying simulation model handling computational aspects and execution order.
- Type:
- semantic_model
The underlying semantic model managing RDF graphs and ontological representations.
- Type:
- components
Dictionary of all SAREF4SYST System components (delegated to simulation_model).
- Type:
Dict[str, System]
- execution_order
Execution order determined by topological sorting (delegated to simulation_model).
- Type:
List[List[System]]
- flat_execution_order
Flattened execution order for sequential processing (delegated to simulation_model).
- Type:
List[System]
See also
SimulationModelDetailed documentation on Algorithms 1-2, cycle removal, topological sorting, component management, and simulation preparation
SemanticModelDetailed documentation on SAREF4SYST integration, RDF graph management, semantic queries, and ontological operations
SimulatorAlgorithm 3 implementation for executing the prepared simulation model
Examples
Basic model creation and usage:
>>> import twin4build as tb >>> >>> # Create unified model interface >>> model = tb.Model(id="building_model") >>> >>> # Add components (delegates to simulation_model) >>> space = tb.SpaceSystem(id="office_space") >>> heater = tb.SpaceHeaterSystem(id="radiator") >>> model.add_component(space) >>> model.add_component(heater) >>> >>> # Add connections (updates both simulation and semantic models) >>> model.add_connection(space, heater, "indoorTemperature", "zoneTemperature") >>> >>> # Load model (applies Algorithms 1-2, prepares semantic representation) >>> model.load() >>> >>> # Model is now ready for simulation or semantic queries >>> simulator = tb.Simulator(model)
Working with semantic capabilities:
>>> # Access semantic model directly when needed >>> model.semantic_model.visualize() # Generate RDF graph visualization >>> model.semantic_model.serialize() # Export to RDF format >>> >>> # Query semantic information >>> instances = model.semantic_model.get_instances_of_type("s4bldg:SpaceHeater")
Working with simulation capabilities:
>>> # Access simulation model directly when needed >>> print(f"Execution order: {model.simulation_model.execution_order}") >>> print(f"Components: {len(model.simulation_model.components)}") >>> >>> # Check if model is ready for simulation >>> if model.simulation_model._is_loaded: ... simulator = tb.Simulator(model) ... # Run simulation...
Loading from RDF file:
>>> # Load existing semantic model and convert to simulation model >>> model = tb.Model(id="restored_model") >>> model.load(rdf_file="my_building.ttl") >>> # Model now contains both semantic and simulation representations
- add_component(component)[source]
Add a component to the model.
- Parameters:
component (core.System) – The component to add.
- Raises:
AssertionError – If the component is not an instance of core.System.
- Return type:
None
- add_connection(sender_component, receiver_component, outputPort, inputPort)[source]
Add a connection between two components in the system.
- Parameters:
sender_component (core.System) – The component sending the connection.
receiver_component (core.System) – The component receiving the connection.
outputPort (str) – Name of the sender property.
inputPort (str) – Name of the receiver property.
- Raises:
AssertionError – If property names are invalid for the components.
AssertionError – If a connection already exists.
- Return type:
None
- cache(start_time=None, end_time=None, step_size=None, simulator=None)[source]
Cache data and create folder structure for time series data.
- Parameters:
start_time (Optional[datetime.datetime]) – Start time for caching.
end_time (Optional[datetime.datetime]) – End time for caching.
step_size (Optional[int]) – Time step size for caching.
- Return type:
None
- check_for_for_missing_initial_values()[source]
Check for missing initial values in components.
- Raises:
Exception – If any component is missing an initial value.
- Return type:
None
- fcn()[source]
Placeholder for a custom function to be applied during model loading.
- Return type:
None
- get_component_by_class(dict_, class_, filter=None)[source]
Get components of a specific class from a dictionary.
- Parameters:
dict (Dict) – The dictionary to search.
class (Type) – The class to filter by.
filter (Optional[Callable]) – Additional filter function.
- Returns:
List of components matching the class and filter.
- Return type:
List
- get_dir(folder_list=[], filename=None)[source]
Get the directory path for storing model-related files.
- Parameters:
folder_list (List[str]) – List of folder names to create.
filename (Optional[str]) – Name of the file to create.
- Returns:
The full path to the directory or file, and a boolean indicating if the file exists.
- Return type:
Tuple[str, bool]
- get_semantic_object(key)[source]
Get the semantic object for a given key.
- Parameters:
key (str) – The key of the component.
- Returns:
The system component.
- Return type:
core.System
- Raises:
AssertionError – If the mapping is not 1-to-1.
- initialize(start_time, end_time, step_size, simulator)[source]
Initialize the model for simulation.
- Parameters:
start_time (datetime.datetime) – Start time for the simulation.
end_time (datetime.datetime) – End time for the simulation.
step_size (int) – Time step size for the simulation.
simulator (core.Simulator) – Simulator instance.
- Return type:
None
- load(semantic_model_filename=None, simulation_model_filename=None, fcn=None, draw_semantic_model=True, draw_simulation_model=True, verbose=False, validate_model=True, force_config_overwrite=False)[source]
Load and set up the model for simulation.
- Parameters:
semantic_model_filename (Optional[str]) – Path to the semantic model configuration file.
fcn (Optional[Callable]) – Custom function to be applied during model loading.
draw_semantic_model (bool) – Whether to create and save the semantic model graph.
draw_simulation_model (bool) – Whether to create and save the simulation model graph.
verbose (bool) – Whether to print verbose output during loading.
validate_model (bool) – Whether to perform model validation.
- Return type:
None
- load_estimation_result(filename=None, result=None)[source]
Load a chain log from a file or dictionary.
- Parameters:
filename (Optional[str]) – The filename to load the chain log from.
result (Optional[Dict]) – The chain log dictionary to load.
- Raises:
AssertionError – If invalid arguments are provided.
- Return type:
None
- make_pickable()[source]
Make the model instance pickable by removing unpickable references.
This method prepares the Model instance for use with multiprocessing in the Estimator class.
- Return type:
None
- remove_component(component)[source]
Remove a component from the model.
- Parameters:
component (core.System) – The component to remove.
- Return type:
None
- remove_connection(sender_component, receiver_component, outputPort, inputPort)[source]
Remove a connection between two components in the system.
- Parameters:
sender_component (core.System) – The component sending the connection.
receiver_component (core.System) – The component receiving the connection.
outputPort (str) – Name of the sender property.
inputPort (str) – Name of the receiver property.
- Raises:
ValueError – If the specified connection does not exist.
- Return type:
None
- restore_parameters(keep_values=True)[source]
Restore the parameters of the model.
- Return type:
None
- set_custom_initial_dict(custom_initial_dict)[source]
Set custom initial values for components.
- Parameters:
custom_initial_dict (Dict[str, Dict[str, Any]]) – Dictionary of custom initial values.
- Raises:
AssertionError – If unknown component IDs are provided.
- Return type:
None
- set_parameters_from_array(values, components, parameter_names, normalized=None, overwrite=False, save_original=False)[source]
Set parameters for components from an array.
- Parameters:
values (List[Any]) – List of parameter values.
component_list (List[core.System]) – List of components to set parameters for.
attr_list (List[str]) – List of attribute names corresponding to the parameters.
- Raises:
AssertionError – If a component doesn’t have the specified attribute.
- Return type:
None
- property components: dict
- property dir_conf: List[str]
- property execution_order: List[str]
- property flat_execution_order: List[str]
- property id: str
- property is_loaded: bool
- property is_validated: bool
- property result: Any
- property semantic_model: SemanticModel
- property simulation_model: SimulationModel