or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# PySD

1

2

PySD is a Python library for running [System Dynamics](http://en.wikipedia.org/wiki/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.

3

4

## Package Information

5

6

- **Package Name**: pysd

7

- **Language**: Python

8

- **Installation**: `pip install pysd`

9

- **Python Version**: >=3.9

10

11

## Core Imports

12

13

```python

14

import pysd

15

```

16

17

For accessing specific functionality:

18

19

```python

20

from pysd import read_vensim, read_xmile, load

21

from pysd import functions, statefuls, utils, external, Component

22

```

23

24

## Basic Usage

25

26

Load and run a System Dynamics model:

27

28

```python

29

import pysd

30

31

# Load a Vensim model

32

model = pysd.read_vensim('model.mdl')

33

34

# Run simulation

35

results = model.run()

36

print(results)

37

38

# Run with different parameters

39

results = model.run(params={'initial_population': 1000})

40

41

# Set specific parameter values

42

model.set_components({'birth_rate': 0.05, 'death_rate': 0.02})

43

results = model.run()

44

```

45

46

Load an XMILE model:

47

48

```python

49

# Load XMILE model

50

model = pysd.read_xmile('model.xml')

51

results = model.run()

52

```

53

54

Load a pre-translated Python model:

55

56

```python

57

# Load existing Python model file

58

model = pysd.load('translated_model.py')

59

results = model.run()

60

```

61

62

## Architecture

63

64

PySD follows a translation-based architecture:

65

66

- **Translators**: Convert Vensim (.mdl) and XMILE (.xml) models to Python code

67

- **Model Class**: Primary interface for simulation, inheriting from Macro class

68

- **Backend Modules**: Functions, statefuls, utilities for model execution

69

- **Components System**: Manages model variables, dependencies, and metadata

70

- **External Data**: Integrates time series and lookup data from external sources

71

72

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

73

74

## Capabilities

75

76

### Model Loading and Translation

77

78

Load models from Vensim .mdl files, XMILE .xml files, or pre-translated Python files. Supports split views, custom encodings, and external data integration.

79

80

```python { .api }

81

def read_vensim(mdl_file, data_files=None, data_files_encoding=None,

82

initialize=True, missing_values="warning", split_views=False,

83

encoding=None, **kwargs):

84

"""

85

Construct a model from Vensim .mdl file.

86

87

Returns:

88

Model: PySD Model object ready for simulation

89

"""

90

91

def read_xmile(xmile_file, data_files=None, data_files_encoding=None,

92

initialize=True, missing_values="warning"):

93

"""

94

Construct a model from XMILE file.

95

96

Returns:

97

Model: PySD Model object ready for simulation

98

"""

99

100

def load(py_model_file, data_files=None, data_files_encoding=None,

101

initialize=True, missing_values="warning"):

102

"""

103

Load a pre-translated Python model file.

104

105

Returns:

106

Model: PySD Model object ready for simulation

107

"""

108

```

109

110

[Model Loading and Translation](./model-loading.md)

111

112

### Model Simulation and Execution

113

114

Run simulations with customizable parameters, time settings, and output configuration. Supports both batch execution and step-by-step simulation.

115

116

```python { .api }

117

class Model:

118

def run(self, params=None, return_columns=None, return_timestamps=None,

119

initial_condition='original', final_time=None, time_step=None,

120

saveper=None, reload=False, progress=False, flatten_output=False,

121

cache_output=True, output_file=None):

122

"""

123

Execute model simulation.

124

125

Returns:

126

pandas.DataFrame: Simulation results with time series data

127

"""

128

129

def step(self, num_steps=1, step_vars={}):

130

"""Execute one or more simulation steps."""

131

```

132

133

[Model Simulation and Execution](./model-simulation.md)

134

135

### Parameter and State Management

136

137

Set model parameters, initial conditions, and access model state. Supports constants, time series data, and callable functions as parameter values.

138

139

```python { .api }

140

class Model:

141

def set_components(self, params):

142

"""Set values of model parameters/variables."""

143

144

def set_initial_condition(self, initial_condition):

145

"""Set initial simulation conditions."""

146

147

def __getitem__(self, param):

148

"""Get current value using bracket notation."""

149

150

def get_series_data(self, param):

151

"""Get original lookup/data component data."""

152

```

153

154

[Parameter and State Management](./parameter-management.md)

155

156

### Mathematical and Utility Functions

157

158

Comprehensive set of System Dynamics functions equivalent to Vensim/XMILE built-ins, including mathematical operations, time functions, and array manipulations.

159

160

```python { .api }

161

# Mathematical functions

162

def if_then_else(condition, val_if_true, val_if_false): ...

163

def xidz(numerator, denominator, x): ...

164

def zidz(numerator, denominator): ...

165

166

# Time functions

167

def ramp(time, slope, start, finish=None): ...

168

def step(time, value, tstep): ...

169

def pulse(time, start, repeat_time=0, **kwargs): ...

170

171

# Array functions

172

def sum(x, dim=None): ...

173

def vmin(x, dim=None): ...

174

def vmax(x, dim=None): ...

175

```

176

177

[Mathematical and Utility Functions](./functions-module.md)

178

179

### Stateful Model Components

180

181

Classes for stateful elements including stocks (integrations), delays, smoothing functions, and forecasting components that maintain state between simulation time steps.

182

183

```python { .api }

184

class Integ(DynamicStateful):

185

"""Integration/stock elements."""

186

187

class Delay(DynamicStateful):

188

"""Variable delay functions."""

189

190

class Smooth(DynamicStateful):

191

"""Smoothing functions."""

192

193

class Forecast(DynamicStateful):

194

"""Forecasting functions."""

195

```

196

197

[Stateful Model Components](./stateful-components.md)

198

199

### External Data Integration

200

201

Handle external data sources including time series from files, lookup tables, constants, and Excel data integration with caching and encoding support.

202

203

```python { .api }

204

class ExtData(External):

205

"""Time series data from external files."""

206

207

class ExtLookup(External):

208

"""Lookup tables from external files."""

209

210

class ExtConstant(External):

211

"""Constants from external files."""

212

213

class Excels:

214

"""Excel file caching utility."""

215

```

216

217

[External Data Integration](./external-data.md)

218

219

### Command Line Interface and Tools

220

221

Command-line tools for model translation, batch execution, benchmarking, and netCDF file processing for automated workflows and testing.

222

223

```python { .api }

224

def main(args):

225

"""Main CLI entry point."""

226

227

def runner(model_file, canonical_file=None, **kwargs):

228

"""Run model and compare with canonical output."""

229

230

class NCFile:

231

"""NetCDF file processing class."""

232

```

233

234

[Command Line Interface and Tools](./cli-tools.md)

235

236

### Utility Functions and Classes

237

238

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.

239

240

```python { .api }

241

def xrsplit(array): ...

242

def rearrange(data, dims, coords): ...

243

def compute_shape(coords, reshape_len=None, py_name=""): ...

244

def load_model_data(root, model_name): ...

245

def load_outputs(file_name, transpose=False, columns=None, encoding=None): ...

246

def get_return_elements(return_columns, namespace): ...

247

def detect_encoding(filename): ...

248

249

class Dependencies: ...

250

class ProgressBar: ...

251

class UniqueDims: ...

252

```

253

254

[Utility Functions and Classes](./utils-module.md)

255

256

## Types

257

258

```python { .api }

259

class Model(Macro):

260

"""

261

Main simulation model interface.

262

263

Primary class for interacting with loaded System Dynamics models.

264

Provides methods for simulation, parameter management, and introspection.

265

"""

266

267

class Component:

268

"""

269

Component metadata handler.

270

271

Manages metadata for model components including names, units, limits,

272

subscripts, types, and dependencies.

273

"""

274

275

class Time:

276

"""Time management for simulations."""

277

278

# External data types

279

External = Union[ExtData, ExtLookup, ExtConstant, ExtSubscript]

280

281

# Stateful types

282

Stateful = Union[Integ, Delay, Smooth, Forecast, Trend, SampleIfTrue, Initial]

283

```