or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

parameter-management.mddocs/

0

# Parameter and State Management

1

2

PySD's Model class provides comprehensive capabilities for setting model parameters, managing initial conditions, and accessing model state. Parameters can be constants, time series data, or callable functions.

3

4

## Capabilities

5

6

### Setting Model Parameters

7

8

Modify model parameters and variables with support for constants, time series, and function values.

9

10

```python { .api }

11

def set_components(self, params):

12

"""

13

Set values of model parameters/variables.

14

15

Parameters:

16

- params: dict - Parameter names and values where values can be:

17

- Scalar constants (int, float)

18

- pandas.Series for time series data (index must be time values)

19

- Callable functions that accept time and return scalar values

20

- NumPy arrays for subscripted variables

21

22

Raises:

23

KeyError: If parameter name doesn't exist in model

24

ValueError: If value type/shape doesn't match parameter requirements

25

TypeError: If callable function has incorrect signature

26

"""

27

```

28

29

#### Usage Examples

30

31

Setting constant parameters:

32

33

```python

34

import pysd

35

import pandas as pd

36

import numpy as np

37

38

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

39

40

# Set constant values

41

model.set_components({

42

'birth_rate': 0.05,

43

'death_rate': 0.02,

44

'initial_population': 1000,

45

'carrying_capacity': 50000

46

})

47

48

results = model.run()

49

```

50

51

Setting time series parameters:

52

53

```python

54

# Create time series data

55

time_index = pd.Series(range(0, 51))

56

birth_rate_series = pd.Series(

57

np.linspace(0.05, 0.02, 51), # Declining birth rate over time

58

index=time_index

59

)

60

61

model.set_components({

62

'birth_rate': birth_rate_series,

63

'migration_rate': pd.Series([0.01] * 51, index=time_index)

64

})

65

66

results = model.run()

67

```

68

69

Setting function parameters:

70

71

```python

72

# Define custom functions

73

def seasonal_birth_rate(time):

74

"""Birth rate that varies seasonally."""

75

base_rate = 0.04

76

seasonal_variation = 0.01 * np.sin(2 * np.pi * time)

77

return base_rate + seasonal_variation

78

79

def policy_intervention(time):

80

"""Policy that changes at specific time."""

81

return 0.03 if time < 25 else 0.015

82

83

model.set_components({

84

'birth_rate': seasonal_birth_rate,

85

'death_rate': policy_intervention

86

})

87

88

results = model.run()

89

```

90

91

### Accessing Model State

92

93

Retrieve current values of model variables and access historical data.

94

95

```python { .api }

96

def __getitem__(self, param):

97

"""

98

Get current value of model component using bracket notation.

99

100

Parameters:

101

- param: str - Name of model variable/parameter

102

103

Returns:

104

float or numpy.ndarray: Current value of the specified component

105

106

Raises:

107

KeyError: If parameter name doesn't exist in model

108

"""

109

110

def get_series_data(self, param):

111

"""

112

Get original data from lookup/data components.

113

114

Parameters:

115

- param: str - Name of lookup or data component

116

117

Returns:

118

pandas.Series or numpy.ndarray: Original data series

119

120

Raises:

121

KeyError: If parameter name doesn't exist

122

TypeError: If parameter is not a data/lookup component

123

"""

124

```

125

126

#### Usage Examples

127

128

```python

129

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

130

131

# Get current values

132

current_population = model['Population']

133

current_birth_rate = model['birth_rate']

134

135

print(f"Current population: {current_population}")

136

print(f"Current birth rate: {current_birth_rate}")

137

138

# Access original lookup table data

139

original_lookup = model.get_series_data('GDP_lookup_table')

140

print(original_lookup)

141

```

142

143

### Model Introspection

144

145

Access model metadata, structure, and dependency information.

146

147

```python { .api }

148

@property

149

def doc(self):

150

"""

151

Model documentation as pandas DataFrame.

152

153

Returns:

154

pandas.DataFrame: Documentation with columns for variable names,

155

units, limits, subscripts, types, and descriptions

156

"""

157

158

@property

159

def namespace(self):

160

"""

161

Model namespace dictionary.

162

163

Returns:

164

dict: Mapping of model variable names to Python function names

165

"""

166

167

@property

168

def dependencies(self):

169

"""

170

Model dependencies dictionary.

171

172

Returns:

173

dict: Variable dependency relationships

174

"""

175

176

@property

177

def subscripts(self):

178

"""

179

Model subscripts dictionary.

180

181

Returns:

182

dict: Variable subscript definitions and ranges

183

"""

184

```

185

186

#### Usage Examples

187

188

```python

189

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

190

191

# View model documentation

192

print(model.doc)

193

194

# Check available variables

195

print("Available variables:", list(model.namespace.keys()))

196

197

# Examine variable dependencies

198

print("Dependencies for Population:", model.dependencies.get('population', []))

199

200

# Check subscripted variables

201

print("Subscripts:", model.subscripts)

202

```

203

204

### Advanced Parameter Access

205

206

Get detailed information about model components including arguments and coordinates.

207

208

```python { .api }

209

def get_args(self, param):

210

"""

211

Get function arguments for a model element.

212

213

Parameters:

214

- param: str - Name of model element

215

216

Returns:

217

list: Function argument names

218

219

Raises:

220

KeyError: If parameter name doesn't exist

221

"""

222

223

def get_coords(self, param):

224

"""

225

Get coordinates and dimensions of a model element.

226

227

Parameters:

228

- param: str - Name of model element

229

230

Returns:

231

dict: Coordinate information including dimensions and subscript ranges

232

233

Raises:

234

KeyError: If parameter name doesn't exist

235

"""

236

```

237

238

#### Usage Examples

239

240

```python

241

# Check function arguments

242

args = model.get_args('complex_calculation')

243

print(f"Arguments for complex_calculation: {args}")

244

245

# Get coordinate information for subscripted variables

246

coords = model.get_coords('population_by_age_group')

247

print(f"Coordinates: {coords}")

248

```

249

250

### State Persistence

251

252

Export and import model state for reproducible analysis and checkpointing.

253

254

```python { .api }

255

def export(self, file_name):

256

"""

257

Export model state to pickle file.

258

259

Parameters:

260

- file_name: str - Path to output pickle file

261

262

Raises:

263

IOError: If file cannot be written

264

"""

265

266

def import_pickle(self, file_name):

267

"""

268

Import model state from pickle file.

269

270

Parameters:

271

- file_name: str - Path to pickle file

272

273

Raises:

274

IOError: If file cannot be read

275

pickle.UnpicklingError: If file is corrupted or incompatible

276

"""

277

```

278

279

#### Usage Examples

280

281

```python

282

# Set up model state

283

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

284

model.run(final_time=25) # Run to midpoint

285

286

# Save state

287

model.export('midpoint_state.pkl')

288

289

# Later, restore state

290

model.import_pickle('midpoint_state.pkl')

291

292

# Continue simulation from saved state

293

final_results = model.run(final_time=50)

294

```

295

296

### Subscripted Variables

297

298

Handle multi-dimensional variables with subscripts (arrays).

299

300

```python

301

# Set subscripted parameter values

302

model.set_components({

303

'population_by_region': np.array([1000, 1500, 800, 1200]), # 4 regions

304

'birth_rate_by_age': {

305

'young': 0.06,

306

'middle': 0.04,

307

'old': 0.01

308

}

309

})

310

311

# Access subscripted values

312

regional_pop = model['population_by_region']

313

print(f"Population by region: {regional_pop}")

314

315

# Get specific subscript element

316

young_birth_rate = model['birth_rate_by_age']['young']

317

```

318

319

### Parameter Validation

320

321

PySD performs validation when setting parameters:

322

323

- **Name validation**: Parameter must exist in model

324

- **Type validation**: Value type must be compatible with parameter

325

- **Shape validation**: Array dimensions must match subscript structure

326

- **Function validation**: Callable parameters must accept time argument

327

328

```python

329

try:

330

model.set_components({'invalid_param': 100})

331

except KeyError:

332

print("Parameter name not found in model")

333

334

try:

335

model.set_components({'birth_rate': 'invalid_value'})

336

except ValueError:

337

print("Invalid parameter value type")

338

```

339

340

### Time Series Data Integration

341

342

Load parameter values from external data sources:

343

344

```python

345

# Load from CSV

346

data = pd.read_csv('historical_data.csv', index_col='time')

347

model.set_components({

348

'birth_rate': data['births'],

349

'death_rate': data['deaths'],

350

'migration_rate': data['migration']

351

})

352

353

# Load from Excel with multiple sheets

354

excel_data = pd.read_excel('model_inputs.xlsx', sheet_name='parameters', index_col='time')

355

model.set_components(excel_data.to_dict('series'))

356

```