or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-tools.mdexternal-data.mdfunctions-module.mdindex.mdmodel-loading.mdmodel-simulation.mdparameter-management.mdstateful-components.mdutils-module.md
tile.json

tessl/pypi-pysd

System Dynamics modeling library for Python that integrates with data science tools

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pysd@3.14.x

To install, run

npx @tessl/cli install tessl/pypi-pysd@3.14.0

index.mddocs/

PySD

PySD 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.

Package Information

  • Package Name: pysd
  • Language: Python
  • Installation: pip install pysd
  • Python Version: >=3.9

Core Imports

import pysd

For accessing specific functionality:

from pysd import read_vensim, read_xmile, load
from pysd import functions, statefuls, utils, external, Component

Basic Usage

Load 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()

Architecture

PySD follows a translation-based architecture:

  • Translators: Convert Vensim (.mdl) and XMILE (.xml) models to Python code
  • Model Class: Primary interface for simulation, inheriting from Macro class
  • Backend Modules: Functions, statefuls, utilities for model execution
  • Components System: Manages model variables, dependencies, and metadata
  • External Data: Integrates time series and lookup data from external sources

This design enables seamless integration with Python's data science ecosystem while maintaining compatibility with established SD modeling tools.

Capabilities

Model Loading and Translation

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
    """

Model Loading and Translation

Model Simulation and Execution

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

Parameter and State Management

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

Mathematical and Utility Functions

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

Stateful Model Components

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."""

Stateful Model Components

External Data Integration

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."""

External Data Integration

Command Line Interface and Tools

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

Utility Functions and Classes

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: ...

Utility Functions and Classes

Types

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]