CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pysd

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

Pending
Overview
Eval results
Files

model-loading.mddocs/

Model Loading and Translation

PySD's model loading capabilities enable translation of System Dynamics models from Vensim (.mdl) and XMILE (.xml) formats into executable Python code. The translation process preserves model behavior while enabling integration with Python's data science ecosystem.

Capabilities

Loading Vensim Models

Translates Vensim .mdl files into PySD Model objects, supporting various encoding formats, split views for large models, 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.

    Parameters:
    - mdl_file: str or pathlib.Path - Path to Vensim .mdl file
    - data_files: dict or list or str or None - External data files for TabData
    - data_files_encoding: str or dict or None - Encoding for data files
    - initialize: bool - Whether to initialize model on load (default True)
    - missing_values: str - How to handle missing values ("warning", "error", "ignore", "keep")
    - split_views: bool - Parse model views into separate Python files
    - encoding: str or None - Source model file encoding
    - subview_sep: list - Characters for separating views/subviews
    - **kwargs: Additional translation keyword arguments

    Returns:
        Model: PySD Model object ready for simulation

    Raises:
        ImportError: If model was compiled with incompatible PySD version
        FileNotFoundError: If model file doesn't exist
        UnicodeDecodeError: If encoding issues occur
    """

Usage Examples

Basic Vensim model loading:

import pysd

# Load simple model
model = pysd.read_vensim('population_model.mdl')

# Load with custom encoding
model = pysd.read_vensim('model.mdl', encoding='utf-8')

# Load with external data files
model = pysd.read_vensim('model.mdl', 
                        data_files=['data.xlsx', 'lookup_table.csv'])

Advanced loading with split views:

# Load large model with view splitting
model = pysd.read_vensim('large_model.mdl', 
                        split_views=True,
                        subview_sep=[',', '.'])

# Load with specific data file encoding
model = pysd.read_vensim('model.mdl',
                        data_files={'data.csv': 'population_data'},
                        data_files_encoding={'data.csv': 'utf-8'})

Loading XMILE Models

Translates XMILE (.xml) format models into PySD Model objects, supporting the XMILE standard used by tools like Stella and other System Dynamics software.

def read_xmile(xmile_file, data_files=None, data_files_encoding=None,
               initialize=True, missing_values="warning"):
    """
    Construct a model from XMILE file.

    Parameters:
    - xmile_file: str or pathlib.Path - Path to XMILE .xml file
    - data_files: dict or list or str or None - External data files for TabData
    - data_files_encoding: str or dict or None - Encoding for data files  
    - initialize: bool - Whether to initialize model on load (default True)
    - missing_values: str - How to handle missing values ("warning", "error", "ignore", "keep")

    Returns:
        Model: PySD Model object ready for simulation

    Raises:
        ImportError: If model was compiled with incompatible PySD version
        FileNotFoundError: If XMILE file doesn't exist
        XMLSyntaxError: If XMILE file is malformed
    """

Usage Examples

# Load XMILE model
model = pysd.read_xmile('stella_model.xml')

# Load with external data
model = pysd.read_xmile('model.xml',
                       data_files=['time_series.csv'],
                       missing_values='ignore')

Loading Pre-translated Python Models

Loads previously translated PySD Python model files, useful for models that have already been converted or for faster loading of frequently-used models.

def load(py_model_file, data_files=None, data_files_encoding=None,
         initialize=True, missing_values="warning"):
    """
    Load a pre-translated Python model file.

    Parameters:
    - py_model_file: str - Path to translated Python model file
    - data_files: dict or list or str or None - External data files for TabData
    - data_files_encoding: str or dict or None - Encoding for data files
    - initialize: bool - Whether to initialize model on load (default True)  
    - missing_values: str - How to handle missing values ("warning", "error", "ignore", "keep")

    Returns:
        Model: PySD Model object ready for simulation

    Raises:
        ImportError: If Python model file cannot be imported
        FileNotFoundError: If Python model file doesn't exist
    """

Usage Examples

# Load previously translated model
model = pysd.load('translated_population_model.py')

# Load with initialization disabled
model = pysd.load('model.py', initialize=False)
# Initialize later when ready
model.initialize()

Data Files Integration

All loading functions support external data integration through the data_files parameter, enabling models to access time series data, lookup tables, and constants from external sources.

Data Files Format Options

List of filenames - Search all files for needed variables:

data_files = ['data.xlsx', 'lookup.csv', 'constants.txt']

Dictionary mapping - Specify which files contain which variables:

data_files = {
    'population_data.csv': ['births', 'deaths', 'migration'],
    'economic_data.xlsx': ['gdp', 'inflation_rate'],
    'constants.txt': ['country_area']
}

Single filename - Search single file for all variables:

data_files = 'comprehensive_data.xlsx'

Missing Values Handling

Control how missing or incomplete data is handled during model loading:

  • "warning" (default): Show warning and interpolate missing values
  • "error": Raise exception when missing values encountered
  • "ignore": Interpolate missing values silently
  • "keep": Preserve missing values (may cause simulation failure)
# Strict error handling
model = pysd.read_vensim('model.mdl', missing_values='error')

# Silent interpolation
model = pysd.read_vensim('model.mdl', missing_values='ignore')

Translation Process

The loading functions perform these key steps:

  1. Parse Source: Read and parse Vensim .mdl or XMILE .xml file
  2. Abstract Model: Convert to internal abstract model representation
  3. Code Generation: Generate executable Python code using ModelBuilder
  4. Module Loading: Import generated Python code as Model object
  5. Initialization: Set up initial conditions and external data (if enabled)

This process preserves model structure, equations, and behavior while enabling Python integration capabilities.

Install with Tessl CLI

npx tessl i tessl/pypi-pysd

docs

cli-tools.md

external-data.md

functions-module.md

index.md

model-loading.md

model-simulation.md

parameter-management.md

stateful-components.md

utils-module.md

tile.json