System Dynamics modeling library for Python that integrates with data science tools
npx @tessl/cli install tessl/pypi-pysd@3.14.0PySD is a Python library for running System Dynamics models, enabling integration of Big Data and Machine Learning into the SD workflow. It translates models from Vensim and XMILE formats into executable Python code, allowing system dynamicists to leverage the broader data science ecosystem including NumPy, pandas, and xarray.
pip install pysdimport pysdFor accessing specific functionality:
from pysd import read_vensim, read_xmile, load
from pysd import functions, statefuls, utils, external, ComponentLoad and run a System Dynamics model:
import pysd
# Load a Vensim model
model = pysd.read_vensim('model.mdl')
# Run simulation
results = model.run()
print(results)
# Run with different parameters
results = model.run(params={'initial_population': 1000})
# Set specific parameter values
model.set_components({'birth_rate': 0.05, 'death_rate': 0.02})
results = model.run()Load an XMILE model:
# Load XMILE model
model = pysd.read_xmile('model.xml')
results = model.run()Load a pre-translated Python model:
# Load existing Python model file
model = pysd.load('translated_model.py')
results = model.run()PySD follows a translation-based architecture:
This design enables seamless integration with Python's data science ecosystem while maintaining compatibility with established SD modeling tools.
Load models from Vensim .mdl files, XMILE .xml files, or pre-translated Python files. Supports split views, custom encodings, and external data integration.
def read_vensim(mdl_file, data_files=None, data_files_encoding=None,
initialize=True, missing_values="warning", split_views=False,
encoding=None, **kwargs):
"""
Construct a model from Vensim .mdl file.
Returns:
Model: PySD Model object ready for simulation
"""
def read_xmile(xmile_file, data_files=None, data_files_encoding=None,
initialize=True, missing_values="warning"):
"""
Construct a model from XMILE file.
Returns:
Model: PySD Model object ready for simulation
"""
def load(py_model_file, data_files=None, data_files_encoding=None,
initialize=True, missing_values="warning"):
"""
Load a pre-translated Python model file.
Returns:
Model: PySD Model object ready for simulation
"""Run simulations with customizable parameters, time settings, and output configuration. Supports both batch execution and step-by-step simulation.
class Model:
def run(self, params=None, return_columns=None, return_timestamps=None,
initial_condition='original', final_time=None, time_step=None,
saveper=None, reload=False, progress=False, flatten_output=False,
cache_output=True, output_file=None):
"""
Execute model simulation.
Returns:
pandas.DataFrame: Simulation results with time series data
"""
def step(self, num_steps=1, step_vars={}):
"""Execute one or more simulation steps."""Model Simulation and Execution
Set model parameters, initial conditions, and access model state. Supports constants, time series data, and callable functions as parameter values.
class Model:
def set_components(self, params):
"""Set values of model parameters/variables."""
def set_initial_condition(self, initial_condition):
"""Set initial simulation conditions."""
def __getitem__(self, param):
"""Get current value using bracket notation."""
def get_series_data(self, param):
"""Get original lookup/data component data."""Parameter and State Management
Comprehensive set of System Dynamics functions equivalent to Vensim/XMILE built-ins, including mathematical operations, time functions, and array manipulations.
# Mathematical functions
def if_then_else(condition, val_if_true, val_if_false): ...
def xidz(numerator, denominator, x): ...
def zidz(numerator, denominator): ...
# Time functions
def ramp(time, slope, start, finish=None): ...
def step(time, value, tstep): ...
def pulse(time, start, repeat_time=0, **kwargs): ...
# Array functions
def sum(x, dim=None): ...
def vmin(x, dim=None): ...
def vmax(x, dim=None): ...Mathematical and Utility Functions
Classes for stateful elements including stocks (integrations), delays, smoothing functions, and forecasting components that maintain state between simulation time steps.
class Integ(DynamicStateful):
"""Integration/stock elements."""
class Delay(DynamicStateful):
"""Variable delay functions."""
class Smooth(DynamicStateful):
"""Smoothing functions."""
class Forecast(DynamicStateful):
"""Forecasting functions."""Handle external data sources including time series from files, lookup tables, constants, and Excel data integration with caching and encoding support.
class ExtData(External):
"""Time series data from external files."""
class ExtLookup(External):
"""Lookup tables from external files."""
class ExtConstant(External):
"""Constants from external files."""
class Excels:
"""Excel file caching utility."""Command-line tools for model translation, batch execution, benchmarking, and netCDF file processing for automated workflows and testing.
def main(args):
"""Main CLI entry point."""
def runner(model_file, canonical_file=None, **kwargs):
"""Run model and compare with canonical output."""
class NCFile:
"""NetCDF file processing class."""Command Line Interface and Tools
Essential utility functions for data manipulation, file handling, coordinate processing, and model management that support PySD's internal operations and provide useful tools for model developers.
def xrsplit(array): ...
def rearrange(data, dims, coords): ...
def compute_shape(coords, reshape_len=None, py_name=""): ...
def load_model_data(root, model_name): ...
def load_outputs(file_name, transpose=False, columns=None, encoding=None): ...
def get_return_elements(return_columns, namespace): ...
def detect_encoding(filename): ...
class Dependencies: ...
class ProgressBar: ...
class UniqueDims: ...class Model(Macro):
"""
Main simulation model interface.
Primary class for interacting with loaded System Dynamics models.
Provides methods for simulation, parameter management, and introspection.
"""
class Component:
"""
Component metadata handler.
Manages metadata for model components including names, units, limits,
subscripts, types, and dependencies.
"""
class Time:
"""Time management for simulations."""
# External data types
External = Union[ExtData, ExtLookup, ExtConstant, ExtSubscript]
# Stateful types
Stateful = Union[Integ, Delay, Smooth, Forecast, Trend, SampleIfTrue, Initial]