### Install pyplantsim via pip Source: https://github.com/malun22/pyplantsim/blob/main/README.md Install the pyplantsim package using pip. This is the primary method for obtaining the library. ```bash pip install pyplantsim ``` -------------------------------- ### Run Full Simulation with Callbacks (Python) Source: https://context7.com/malun22/pyplantsim/llms.txt Starts a simulation and blocks until completion. Use lifecycle callbacks for initialization, completion, error handling, and progress reporting. Ensure deterministic results by setting a seed. ```python import os from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion, SimulationException def on_init(instance: Plantsim): instance.set_seed(42) # set deterministic seed before each run def on_endsim(instance: Plantsim): result = instance.get_value('.Models.Model.DataTable["Throughput", 1]') print(f"Throughput: {result}") def on_progress(instance: Plantsim, percent: float): print(f"Progress: {percent:.1f}%") def on_error(instance: Plantsim, error: SimulationException): print(f"SimTalk error in {error}") with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) try: plantsim.run_simulation( without_animation=True, on_init=on_init, on_endsim=on_endsim, on_progress=on_progress, on_simulation_error=on_error, ) except SimulationException as e: print(f"Unhandled simulation error: {e}") ``` -------------------------------- ### Catching PlantsimException for COM Errors Source: https://context7.com/malun22/pyplantsim/llms.txt Use this snippet to catch COM-level startup errors, such as Plant Simulation not being installed or an incorrect version being specified. It requires importing `PlantsimException`. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion from pyplantsim import PlantsimException, SimulationException # Catch a COM-level startup error (e.g. wrong version, not installed) try: ps = Plantsim(version=PlantsimVersion.V_MJ_16_MI_0, license=PlantsimLicense.RESEARCH) except PlantsimException as e: print(f"COM error: {e}") # "Plantsim Message: ... - Plantsim Exception ID: ..." ``` -------------------------------- ### Plantsim.run_simulation Source: https://context7.com/malun22/pyplantsim/llms.txt Starts the simulation and blocks until it finishes or an error occurs. Accepts lifecycle callbacks for initialization, completion, error handling, and periodic progress reporting. ```APIDOC ## `Plantsim.run_simulation` — Run a Full Simulation (Blocking) Starts the simulation and blocks until it finishes or an error occurs. Accepts lifecycle callbacks for initialization, completion, error handling, and periodic progress reporting (updated every second). ```python import os from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion, SimulationException def on_init(instance: Plantsim): instance.set_seed(42) # set deterministic seed before each run def on_endsim(instance: Plantsim): result = instance.get_value('.Models.Model.DataTable["Throughput", 1]') print(f"Throughput: {result}") def on_progress(instance: Plantsim, percent: float): print(f"Progress: {percent:.1f}%") def on_error(instance: Plantsim, error: SimulationException): print(f"SimTalk error in {error}") with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) try: plantsim.run_simulation( without_animation=True, on_init=on_init, on_endsim=on_endsim, on_progress=on_progress, on_simulation_error=on_error, ) except SimulationException as e: print(f"Unhandled simulation error: {e}") ``` ``` -------------------------------- ### Plantsim.install_error_handler / Plantsim.remove_error_handler Source: https://context7.com/malun22/pyplantsim/llms.txt Manages the installation and removal of a SimTalk error handler. When installed, runtime errors are caught, serialized to JSON, and raised as Python `SimulationException`. ```APIDOC ## `Plantsim.install_error_handler` / `Plantsim.remove_error_handler` — Error Handler Management ### Description Installs a SimTalk error handler into the model at `basis.ErrorHandler`. When a SimTalk runtime error occurs, it is caught, serialized to JSON, and raised as a `SimulationException` in Python with the method path and line number of the fault. ### Method Signature `install_error_handler()` `remove_error_handler()` ### Usage Call `install_error_handler()` to enable error catching. Use a `try...except SimulationException` block to handle errors. Call `remove_error_handler()` to disable it, typically in a `finally` block. ### Example ```python plantsim.install_error_handler() # installs into basis.ErrorHandler try: plantsim.run_simulation(without_animation=True) except SimulationException as e: # e.g. "Method .Models.Model.SomeMethod crashed on line 12." print(f"Caught SimTalk error: {e}") finally: plantsim.remove_error_handler() ``` ``` -------------------------------- ### Set Active Network and Error Handler with `Plantsim.set_network` Source: https://context7.com/malun22/pyplantsim/llms.txt Configures the active network path within the loaded Plant Simulation model and optionally sets the EventController and installs a built-in error handler for SimTalk errors. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network( path=".Models.Model", set_event_controller=True, # sets EventController automatically install_error_handler=True, # installs error handler under basis.ErrorHandler ) print(plantsim.network_path) # .Models.Model ``` -------------------------------- ### Manage SimTalk Error Handling with Plantsim.install_error_handler Source: https://context7.com/malun22/pyplantsim/llms.txt Install a SimTalk error handler using `install_error_handler` to catch runtime errors, serialize them to JSON, and raise them as `SimulationException` in Python. Remember to call `remove_error_handler` in a `finally` block. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion, SimulationException with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True) plantsim.install_error_handler() # installs into basis.ErrorHandler try: plantsim.run_simulation(without_animation=True) except SimulationException as e: # e.g. "Method .Models.Model.SomeMethod crashed on line 12." print(f"Caught SimTalk error: {e}") finally: plantsim.remove_error_handler() ``` -------------------------------- ### Initialize and Use Plantsim Wrapper Source: https://github.com/malun22/pyplantsim/blob/main/README.md Demonstrates how to initialize the pyplantsim wrapper with specific license and version, and then create and save a new Plant Simulation model. Ensure the license and version parameters are correctly set for your environment. ```python import pyplantsim with Plantsim(license=PlantsimLicense.STUDENT, version=PlantsimVersion.V_MJ_22_MI_1, visible=True, trusted=True, suppress_3d=False, show_msg_box=False) as plantsim: plantsim.new_model() plantsim.save_model( folder_path=r"C:\\users\\documents\\plantsimmodels", file_name="MyNewModel") ``` -------------------------------- ### Initialize Plant Simulation Instance with `Plantsim` Source: https://context7.com/malun22/pyplantsim/llms.txt Instantiates and configures a single Plant Simulation COM instance. Use as a context manager for automatic cleanup. Supports custom callbacks for simulation events and SimTalk messages. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion, SimulationException with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, visible=True, trusted=True, suppress_3d=False, show_msg_box=False, disable_log_message=False, simulation_finished_callback=lambda: print("Simulation finished!"), simtalk_msg_callback=lambda msg: print("SimTalk:", msg), simulation_error_callback=lambda e: print("Error:", e), ) as plantsim: print(plantsim) # Plantsim(version=, visible=True, trusted=True, ...) ``` -------------------------------- ### Configure Plant Simulation Version and License Source: https://context7.com/malun22/pyplantsim/llms.txt Use `PlantsimVersion` and `PlantsimLicense` enumerations to specify the Plant Simulation release and license tier. Enum members are recommended for clarity and type safety. Raw strings can be used for specific version pinning. ```python from pyplantsim import PlantsimVersion, PlantsimLicense, Plantsim # Available versions print([v.value for v in PlantsimVersion]) # ['25.4', '24.4', '23.2', '22.1', '22.0', '16.0'] # Available licenses print([l.value for l in PlantsimLicense]) # ['Professional', 'Standard', 'Foundation', 'Application', # 'Runtime', 'Research', 'Educational', 'Student', 'Viewer'] # Use enum members (recommended) with Plantsim(version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.STUDENT) as ps: print(ps.version) # print(ps.license) # PlantsimLicense.STUDENT # Or use raw strings (useful when pinning to an unlisted minor version) with Plantsim(version="24.4", license="Research") as ps: print(ps.version) # ``` -------------------------------- ### Create and Save a New Plant Simulation Model Source: https://context7.com/malun22/pyplantsim/llms.txt Creates a blank Plant Simulation model and saves it to a specified directory with a given file name. Useful for generating models programmatically. ```python import pyplantsim with pyplantsim.Plantsim( license=pyplantsim.PlantsimLicense.STUDENT, version=pyplantsim.PlantsimVersion.V_MJ_22_MI_1, visible=True, trusted=True, ) as plantsim: plantsim.new_model() plantsim.save_model( folder_path=r"C:\Users\user\Documents\models", file_name="MyNewModel" ) # Saves to: C:\Users\user\Documents\models\MyNewModel.spp print(plantsim.model_path) # C:\Users\user\Documents\models\MyNewModel.spp ``` -------------------------------- ### Plantsim Initialization Source: https://context7.com/malun22/pyplantsim/llms.txt Initializes a single Plant Simulation COM instance with various configuration options. Supports use as a context manager for clean shutdown. ```APIDOC ## Plantsim ### Description Wraps one Plant Simulation COM instance, managing its lifecycle and exposing the remote-control API. Supports context management for automatic cleanup. ### Method `Plantsim(...)` ### Parameters - **version** (PlantsimVersion) - Required - The Plant Simulation version to use. - **license** (PlantsimLicense) - Required - The license type for the Plant Simulation instance. - **visible** (bool) - Optional - Whether the Plant Simulation GUI should be visible. - **trusted** (bool) - Optional - Whether to trust the COM instance. - **suppress_3d** (bool) - Optional - Whether to suppress 3D graphics. - **show_msg_box** (bool) - Optional - Whether to show message boxes. - **disable_log_message** (bool) - Optional - Whether to disable log messages. - **simulation_finished_callback** (callable) - Optional - Callback function for when a simulation finishes. - **simtalk_msg_callback** (callable) - Optional - Callback function for SimTalk messages. - **simulation_error_callback** (callable) - Optional - Callback function for simulation errors. ### Request Example ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, visible=True, trusted=True, suppress_3d=False, show_msg_box=False, disable_log_message=False, simulation_finished_callback=lambda: print("Simulation finished!"), simtalk_msg_callback=lambda msg: print("SimTalk:", msg), simulation_error_callback=lambda e: print("Error:", e), ) as plantsim: print(plantsim) ``` ``` -------------------------------- ### Load Plant Simulation Model with `Plantsim.load_model` Source: https://context7.com/malun22/pyplantsim/llms.txt Loads an existing Plant Simulation model file (`.spp`) into the active instance. Can optionally load encrypted models with a password or close any currently open model before loading. ```python import os from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: model_path = r"C:\Users\user\models\factory.spp" plantsim.load_model(model_path) # load model # plantsim.load_model(model_path, password="secret") # encrypted model # plantsim.load_model(other_path, close_other=True) # close existing first print(plantsim.model_loaded) # True print(plantsim.model_path) # C:\Users\user\models\factory.spp ``` -------------------------------- ### Plantsim.new_model / Plantsim.save_model Source: https://context7.com/malun22/pyplantsim/llms.txt Creates a new, blank Plant Simulation model and saves it to a specified location on disk. ```APIDOC ## Plantsim.new_model / Plantsim.save_model ### Description Creates a blank new model in the current Plant Simulation instance and saves it to disk as an `.spp` file. This is useful for programmatic model generation workflows. ### Method `new_model()` `save_model(folder_path: str, file_name: str)` ### Parameters - **folder_path** (str) - Required - The directory where the model will be saved. - **file_name** (str) - Required - The desired name for the model file (without extension). ### Request Example ```python import pyplantsim with pyplantsim.Plantsim( license=pyplantsim.PlantsimLicense.STUDENT, version=pyplantsim.PlantsimVersion.V_MJ_22_MI_1, visible=True, trusted=True, ) as plantsim: plantsim.new_model() plantsim.save_model( folder_path=r"C:\Users\user\Documents\models", file_name="MyNewModel" ) # Saves to: C:\Users\user\Documents\models\MyNewModel.spp print(plantsim.model_path) # C:\Users\user\Documents\models\MyNewModel.spp ``` ``` -------------------------------- ### Exchange Tables as DataFrames (Python) Source: https://context7.com/malun22/pyplantsim/llms.txt Read Plant Simulation tables into pandas DataFrames and write DataFrames back. Preserves index configurations. Use `get_table` to read and `set_table` to write. ```python import pandas as pd from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) # Read tables with different index configurations df_no_idx = plantsim.get_table(".Models.Model.DataTableNoIndex") df_col_idx = plantsim.get_table(".Models.Model.DataTableColIndex") df_row_idx = plantsim.get_table(".Models.Model.DataTableRowIndex") df_both_idx = plantsim.get_table(".Models.Model.DataTableBothIndex") print(df_col_idx) # PartType Quantity CycleTime # 0 TypeA 10 12.5 # 1 TypeB 20 8.0 # Modify and write back df_col_idx["Quantity"] = df_col_idx["Quantity"] * 2 plantsim.set_table(".Models.Model.DataTableColIndex", df_col_idx) ``` -------------------------------- ### Plantsim.open_console_log_file / Plantsim.close_console_log_file Source: https://context7.com/malun22/pyplantsim/llms.txt Routes all Plant Simulation console output to a specified log file. Useful for capturing SimTalk `print` output during headless runs. ```APIDOC ## `Plantsim.open_console_log_file` / `Plantsim.close_console_log_file` — Console Logging to File ### Description Routes all Plant Simulation console output to a log file on disk. Useful for capturing SimTalk `print` output during headless batch runs. Calling `close_console_log_file()` stops routing. ### Method Signature `open_console_log_file(log_file_path: str)` `close_console_log_file()` ### Parameters * **log_file_path** (str) - Required - The full path to the log file where console output will be written. ### Usage Call `open_console_log_file()` before the simulation run and `close_console_log_file()` afterwards to manage the log file. ### Example ```python plantsim.open_console_log_file(r"C:\logs\simulation_run.log") plantsim.run_simulation(without_animation=True) plantsim.close_console_log_file() # All SimTalk console output is now in simulation_run.log ``` ``` -------------------------------- ### Auto-Scale Simulations with DynamicInstanceHandler Source: https://context7.com/malun22/pyplantsim/llms.txt Utilize `DynamicInstanceHandler` for an auto-scaling worker pool that monitors CPU and memory usage to adjust the number of Plant Simulation processes. This is ideal for large batch studies with variable resource availability. Configure scaling parameters like `max_cpu`, `max_memory`, `min_instances`, and `max_instances`. ```python from functools import partial from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion, SimulationException from pyplantsim.instance_handler import DynamicInstanceHandler, SimulationJob def on_init(instance: Plantsim, config: dict): if not instance.model_loaded: instance.load_model(r"C:\\models\\factory.spp") instance.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) instance.reset_simulation() instance.set_seed(config["seed"]) instance.set_value(".Models.Model.Params.BatchSize", config["batch_size"]) def on_endsim(instance: Plantsim): result = instance.get_value('.Models.Model.DataTable["Throughput", 1]') print(f"Throughput: {result}") with DynamicInstanceHandler( max_cpu=0.75, # scale down if CPU exceeds 75% max_memory=0.70, # scale down if RAM exceeds 70% min_instances=1, # always keep at least 1 worker alive max_instances=8, # never exceed 8 simultaneous instances scale_interval=15.0, # re-evaluate resource usage every 15 seconds version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, visible=False, suppress_3d=True, ) as handler: jobs = [] configs = [{"seed": i, "batch_size": 50 + i * 10} for i in range(100)] for config in configs: job = handler.queue_job(SimulationJob( without_animation=True, on_init=partial(on_init, config=config), on_endsim=on_endsim, )) jobs.append(job) for job in jobs: handler.wait_for(job) print("All 100 parameter-study runs complete.") ``` -------------------------------- ### Route Console Output to File with Plantsim.open_console_log_file Source: https://context7.com/malun22/pyplantsim/llms.txt Use `open_console_log_file` to redirect all Plant Simulation console output to a specified log file, which is useful for capturing SimTalk `print` statements during headless runs. Call `close_console_log_file()` to stop logging. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, visible=False, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) plantsim.open_console_log_file(r"C:\logs\simulation_run.log") plantsim.run_simulation(without_animation=True) plantsim.close_console_log_file() # All SimTalk console output is now in simulation_run.log ``` -------------------------------- ### Profile SimTalk Methods with Plantsim.get_call_cycles Source: https://context7.com/malun22/pyplantsim/llms.txt Use `get_call_cycles` to run the simulation with the profiler activated. It returns a list of `CallCycle` objects detailing method calls, counts, and execution times, which is useful for performance analysis. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) # Run with profiler; returns results after simulation ends call_cycles = plantsim.get_call_cycles() for cc in call_cycles: print(f"Method: {cc.method.method}") print(f" Called: {cc.method.called}") print(f" Self time: {cc.method.self_time:.4f}s") print(f" Callee time: {cc.method.callees_time:.4f}s") for caller in cc.callers: print(f" <- {caller.caller} ({caller.called}x)") ``` -------------------------------- ### Plantsim.load_model Source: https://context7.com/malun22/pyplantsim/llms.txt Loads an existing Plant Simulation model file into the current instance. Can optionally close any currently open model. ```APIDOC ## Plantsim.load_model ### Description Loads an `.spp` model file into the running Plant Simulation instance. Raises an exception if the file does not exist or another model is already open, unless `close_other=True` is specified. ### Method `load_model(model_path: str, password: Optional[str] = None, close_other: bool = False)` ### Parameters - **model_path** (str) - Required - The full path to the `.spp` model file. - **password** (str, optional) - The password for encrypted models. - **close_other** (bool) - Optional - If `True`, closes any currently open model before loading the new one. ### Request Example ```python import os from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: model_path = r"C:\Users\user\models\factory.spp" plantsim.load_model(model_path) # plantsim.load_model(model_path, password="secret") # plantsim.load_model(other_path, close_other=True) print(plantsim.model_loaded) # True print(plantsim.model_path) # C:\Users\user\models\factory.spp ``` ``` -------------------------------- ### Run Parallel Simulations with FixedInstanceHandler Source: https://context7.com/malun22/pyplantsim/llms.txt Use `FixedInstanceHandler` to manage a fixed pool of Plant Simulation processes for parallel execution. Jobs are queued and dispatched to available workers, with each worker reusing its instance across multiple jobs. Ensure necessary imports and define callback functions for initialization, completion, and errors. ```python import os from functools import partial from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion, SimulationException from pyplantsim.instance_handler import FixedInstanceHandler, SimulationJob def on_init(instance: Plantsim, seed: int): model_path = r"C:\\models\\factory.spp" if not instance.model_loaded: instance.load_model(model_path) instance.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) instance.reset_simulation() instance.set_seed(seed) def on_endsim(instance: Plantsim): result = instance.get_value('.Models.Model.DataTable["Output", 1]') print(f"Output: {result}") def on_error(instance: Plantsim, error: SimulationException): print(f"Error: {error}") with FixedInstanceHandler( amount_instances=4, # spawn 4 parallel Plant Simulation windows version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, visible=False, suppress_3d=True, ) as handler: jobs = [] for seed in range(20): # queue 20 simulation runs job = handler.queue_job(SimulationJob( without_animation=True, on_init=partial(on_init, seed=seed), on_endsim=on_endsim, on_simulation_error=on_error, )) jobs.append(job) handler.wait_all() # block until every job finishes print("All 20 runs complete.") ``` -------------------------------- ### Plantsim.get_table / Plantsim.set_table Source: https://context7.com/malun22/pyplantsim/llms.txt Reads a Plant Simulation table into a `pandas.DataFrame`, preserving column indexes, row indexes, and their names. The matching `set_table` writes a DataFrame back into the simulation table. ```APIDOC ## `Plantsim.get_table` / `Plantsim.set_table` — Exchange Tables as DataFrames Reads a Plant Simulation table into a `pandas.DataFrame`, preserving column indexes, row indexes, and their names. The matching `set_table` writes a DataFrame back into the simulation table. ```python import pandas as pd from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) # Read tables with different index configurations df_no_idx = plantsim.get_table(".Models.Model.DataTableNoIndex") df_col_idx = plantsim.get_table(".Models.Model.DataTableColIndex") df_row_idx = plantsim.get_table(".Models.Model.DataTableRowIndex") df_both_idx = plantsim.get_table(".Models.Model.DataTableBothIndex") print(df_col_idx) # PartType Quantity CycleTime # 0 TypeA 10 12.5 # 1 TypeB 20 8.0 # Modify and write back df_col_idx["Quantity"] = df_col_idx["Quantity"] * 2 plantsim.set_table(".Models.Model.DataTableColIndex", df_col_idx) ``` ``` -------------------------------- ### Plantsim.get_call_cycles / Plantsim.read_call_cycles Source: https://context7.com/malun22/pyplantsim/llms.txt Profiles the simulation by activating the built-in profiler and returning detailed information about SimTalk method calls, their frequency, and execution time. ```APIDOC ## `Plantsim.get_call_cycles` / `Plantsim.read_call_cycles` — SimTalk Profiling ### Description Runs the simulation with the built-in profiler activated and returns a list of `CallCycle` objects describing which SimTalk methods were called, how many times, and how long they took. Useful for performance analysis and bottleneck identification. ### Method Signature `get_call_cycles() -> List[CallCycle]` `read_call_cycles() -> List[CallCycle]` ### Returns * List[CallCycle] - A list of `CallCycle` objects containing profiling information. ### Example ```python call_cycles = plantsim.get_call_cycles() for cc in call_cycles: print(f"Method: {cc.method.method}") print(f" Called: {cc.method.called}") print(f" Self time: {cc.method.self_time:.4f}s") print(f" Callee time: {cc.method.callees_time:.4f}s") for caller in cc.callers: print(f" <- {caller.caller} ({caller.called}x)") ``` ``` -------------------------------- ### Catching SimulationException for SimTalk Runtime Errors Source: https://context7.com/malun22/pyplantsim/llms.txt This snippet demonstrates how to catch SimTalk runtime errors that occur during simulation execution. It requires setting up an error handler and using a `try-except` block around the `run_simulation` call. The `SimulationException` provides method path and line number information. ```python # Catch a SimTalk runtime error with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) try: plantsim.run_simulation(without_animation=True) except SimulationException as e: print(f"SimTalk fault: {e}") # "Method .Models.Model.ProcessLogic crashed on line 7." ``` -------------------------------- ### Execute Arbitrary SimTalk Code (Python) Source: https://context7.com/malun22/pyplantsim/llms.txt Execute SimTalk expressions or multi-statement blocks directly. Positional parameters are available as `?1`, `?2`, etc. in SimTalk. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True) # Execute a simple SimTalk expression result = plantsim.execute_sim_talk("1 + 1") print(result) # 2 # Execute SimTalk with parameters (?1, ?2 are the positional args) code = "?1 * ?2" result = plantsim.execute_sim_talk(code, 6, 7) print(result) # 42 # Multi-line SimTalk block simtalk_block = """ var x: integer; x := .Models.Model.Counter.Counter; x * 10 """ value = plantsim.execute_sim_talk(simtalk_block) print(value) ``` -------------------------------- ### Plantsim.set_network Source: https://context7.com/malun22/pyplantsim/llms.txt Configures the active network path and optionally the EventController and error handler within the Plant Simulation model. ```APIDOC ## Plantsim.set_network ### Description Sets the active network path context in the model. It can also optionally configure the EventController and install the built-in error handler, which enables `SimulationException` to be raised on SimTalk errors. ### Method `set_network(path: str, set_event_controller: bool = False, install_error_handler: bool = False)` ### Parameters - **path** (str) - Required - The network path to set as active. - **set_event_controller** (bool) - Optional - If `True`, automatically sets the EventController. - **install_error_handler** (bool) - Optional - If `True`, installs the built-in error handler. ### Request Example ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network( path=".Models.Model", set_event_controller=True, install_error_handler=True, ) print(plantsim.network_path) # .Models.Model ``` ``` -------------------------------- ### Plantsim.execute_sim_talk Source: https://context7.com/malun22/pyplantsim/llms.txt Executes a SimTalk expression or multi-statement block directly in the running instance and returns the result. Optional positional parameters can be passed and are available in SimTalk as `?1`, `?2`, etc. ```APIDOC ## `Plantsim.execute_sim_talk` — Execute Arbitrary SimTalk Code Executes a SimTalk expression or multi-statement block directly in the running instance and returns the result. Optional positional parameters can be passed and are available in SimTalk as `?1`, `?2`, etc. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True) # Execute a simple SimTalk expression result = plantsim.execute_sim_talk("1 + 1") print(result) # 2 # Execute SimTalk with parameters (?1, ?2 are the positional args) code = "?1 * ?2" result = plantsim.execute_sim_talk(code, 6, 7) print(result) # 42 # Multi-line SimTalk block simtalk_block = """ var x: integer; x := .Models.Model.Counter.Counter; x * 10 """ value = plantsim.execute_sim_talk(simtalk_block) print(value) ``` ``` -------------------------------- ### Read/Write Object Attributes (Python) Source: https://context7.com/malun22/pyplantsim/llms.txt Access any Plant Simulation object attribute using dot-notation. Supports scalar values and table cells. Use `get_value` to read and `set_value` to write. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True) # Read a scalar attribute speed = plantsim.get_value(".Models.Model.Conveyor.Speed") print(f"Conveyor speed: {speed}") # e.g. 1.5 # Read a table cell: column 2, row 3 cell = plantsim.get_value('.Models.Model.ParamTable["WIP", 3]') print(f"WIP at row 3: {cell}") # Write a scalar attribute plantsim.set_value(".Models.Model.Conveyor.Speed", 2.0) # Write a table cell plantsim.set_value('.Models.Model.ParamTable["WIP", 3]', 150) ``` -------------------------------- ### Check Path Existence with Plantsim.exists_path Source: https://context7.com/malun22/pyplantsim/llms.txt Use `exists_path` to safely check if a dot-notation path points to an existing object in the loaded model before attempting to access it. This prevents runtime errors when dealing with optional model elements. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True) if plantsim.exists_path(".Models.Model.OptionalConveyor"): speed = plantsim.get_value(".Models.Model.OptionalConveyor.Speed") print(f"Optional conveyor speed: {speed}") else: print("Optional conveyor not present in this model variant") if not plantsim.exists_path(".Models.Model"): raise RuntimeError("Core model object missing!") ``` -------------------------------- ### Plantsim.get_value / Plantsim.set_value Source: https://context7.com/malun22/pyplantsim/llms.txt Reads or writes any attribute on any Plant Simulation object using its dot-notation path. Supports table cell access using `[col, row]` notation. ```APIDOC ## `Plantsim.get_value` / `Plantsim.set_value` — Read and Write Object Attributes Reads or writes any attribute on any Plant Simulation object using its dot-notation path. Supports table cell access using `[col, row]` notation. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True) # Read a scalar attribute speed = plantsim.get_value(".Models.Model.Conveyor.Speed") print(f"Conveyor speed: {speed}") # e.g. 1.5 # Read a table cell: column 2, row 3 cell = plantsim.get_value('.Models.Model.ParamTable["WIP", 3]') print(f"WIP at row 3: {cell}") # Write a scalar attribute plantsim.set_value(".Models.Model.Conveyor.Speed", 2.0) # Write a table cell plantsim.set_value('.Models.Model.ParamTable["WIP", 3]', 150) ``` ``` -------------------------------- ### Set Random Seed for Deterministic Simulations with Plantsim.set_seed Source: https://context7.com/malun22/pyplantsim/llms.txt Call `set_seed` to make simulations deterministic by setting the `RandomNumbersVariant` attribute on the EventController. The seed must be an integer within the range [-2147483647, 2147483647]. ```python from pyplantsim import Plantsim, PlantsimLicense, PlantsimVersion with Plantsim( version=PlantsimVersion.V_MJ_25_MI_4, license=PlantsimLicense.RESEARCH, trusted=True, ) as plantsim: plantsim.load_model(r"C:\models\factory.spp") plantsim.set_network(".Models.Model", set_event_controller=True, install_error_handler=True) results = [] for seed in [1, 2, 3]: plantsim.reset_simulation() plantsim.set_seed(seed) plantsim.run_simulation(without_animation=True) value = plantsim.get_value('.Models.Model.DataTable["Output", 1]') results.append((seed, value)) print(f"Seed {seed}: output = {value}") ``` -------------------------------- ### Plantsim.exists_path Source: https://context7.com/malun22/pyplantsim/llms.txt Checks if a given dot-notation path points to an existing object in the loaded model. This is useful for safely probing for optional model elements before accessing them. ```APIDOC ## `Plantsim.exists_path` — Check Whether a Path Exists in the Model ### Description Checks if a given dot-notation path points to an existing object in the loaded model. Useful for safely probing for optional model elements before accessing them. ### Method Signature `exists_path(path: str) -> bool` ### Parameters * **path** (str) - Required - The dot-notation path to check in the model. ### Returns * bool - True if the path exists, False otherwise. ### Example ```python if plantsim.exists_path(".Models.Model.OptionalConveyor"): speed = plantsim.get_value(".Models.Model.OptionalConveyor.Speed") print(f"Optional conveyor speed: {speed}") else: print("Optional conveyor not present in this model variant") ``` ``` -------------------------------- ### Plantsim.set_seed Source: https://context7.com/malun22/pyplantsim/llms.txt Sets the Random Number Seed for deterministic simulations. The seed must be an integer within a specified range. ```APIDOC ## `Plantsim.set_seed` — Set the Random Number Seed ### Description Sets the `RandomNumbersVariant` attribute on the EventController to make simulations deterministic. The seed must be an integer in the range `[-2147483647, 2147483647]`. ### Method Signature `set_seed(seed: int)` ### Parameters * **seed** (int) - Required - An integer representing the random number seed. Must be between -2147483647 and 2147483647. ### Example ```python plantsim.reset_simulation() plantsim.set_seed(1) plantsim.run_simulation(without_animation=True) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.