-
Notifications
You must be signed in to change notification settings - Fork 1
/
minnetonka.py
4977 lines (4041 loc) · 176 KB
/
minnetonka.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""minnetonka.py: value modeling in python"""
__author__ = "Dave Bridgeland"
__copyright__ = "Copyright 2017-2020, Hanging Steel Productions LLC"
__credits__ = ["Dave Bridgeland"]
__version__ = "0.0.1.144"
__maintainer__ = "Dave Bridgeland"
__email__ = "[email protected]"
__status__ = "Prototype"
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache Software License 2.0.
import warnings
import copy
import collections
import itertools
import logging
import json
import time
import inspect
import re
from scipy.stats import norm
import numpy as np
class Model:
"""
A collection of variables, that can be simulated.
A model is a self-contained collection of variables and treatments.
A model can be simulated, perhaps running one step at a time, perhaps
multiple steps, perhaps until the end.
Typically a model is defined as a context using :func:`model`,
with variables and stocks within the model context. See example below.
Parameters
----------
treatments : list of :class:`Treatment`
The treatments defined for the model. Each treatment is a different
simulated scenario, run in parallel.
timestep : int or float, optional
The simulated duration of each call to :meth:`step`. The default is
1.
start_time : int or float, optional
The first time period, before the first call to :meth:`step`. Default:
0
end_time : int or float, optional
The last time period, after a call to :meth:`step`
with ``to_end=True``. Default: None, meaning never end
See Also
--------
:func:`model` : the typical way to create a model
Examples
--------
Create a model with two treatments and three variables:
>>> with model(treatments=['As is', 'To be']) as m:
... variable('Revenue', np.array([30.1, 15, 20]))
... variable('Cost',
... PerTreatment({'As is': np.array([10, 10, 10]),
... {'To be': np.array([5, 5, 20])})
... variable('Earnings', lambda r, c: r - c, 'Revenue', 'Cost')
"""
# is a model being defined in a context manager? which one?
_model_context = None
def __init__(self, treatments, derived_treatments, timestep=1,
start_time=0, end_time=None, on_init=None, on_reset=None):
"""Initialize the model, with treatments and optional timestep."""
self._treatments = treatments
self._derived_treatments = derived_treatments
# prior to m.initialize(), this is a regular dict. It is
# converted to an OrderedDict on initialization, ordered with
# dependent variables prior to independent variables
self._variables = ModelVariables()
self._pseudo_variable = ModelPseudoVariable(self)
self._user_actions = UserActions()
self._timestep = timestep
self._start_time = start_time
self._end_time = end_time
self._constraints = []
self._on_init = on_init
self._on_reset = on_reset
#: Current time in the model, accessible in a specifier. See
#: example detailed in :func:`variable`
self.TIME = start_time
@property
def STARTTIME(self):
return self._start_time
@property
def ENDTIME(self):
return self._end_time
def __getitem__(self, variable_name):
"""Return the named variable, supporting [] notation."""
return self._variables.variable(variable_name)
def __enter__(self):
"""Enter the model context; accumulate variables to add to model."""
self._variables_not_yet_added = []
Model._model_context = self
self._uninitialize()
return self
def __exit__(self, exception_type, exception_value, exception_traceback):
"""Exit the model context; add variables to model."""
logging.info('enter')
if exception_type is None:
self._add_variables_and_initialize(*self._variables_not_yet_added)
self._variables_not_yet_added = []
Model._model_context = None
logging.info('exit')
def step(self, n=1, to_end=False):
"""
Simulate the model **n** steps.
Simulate the model, either one step (default), or ``n`` steps,
or until the model's end.
Parameters
----------
n : int, optional
Number of steps to advance. The default is 1, one step at a time.
to_end : bool, optional
If ``True``, simulate the model until its end time
Returns
-------
None
Raises
------
MinnetonkaError
If ``to_end`` is ``True`` but the model has no end time.
Examples
--------
A model can simulate one step at a time:
>>> m = model([stock('Year', 1, 2019)])
>>> m.step()
>>> m['Year']['']
2020
>>> m.step()
>>> m['Year']['']
2021
A model can simulate several steps at a time:
>>> m2 = model([stock('Year', 1, 2019)])
>>> m2.step(n=10)
>>> m2['Year']['']
2029
A model can simulate until the end:
>>> m3 = model([stock('Year', 1, 2019)], end_time=20)
>>> m3.step(to_end=True)
>>> m3['Year']['']
2039
"""
if to_end and self._end_time:
for i in range(int((self._end_time - self.TIME) / self._timestep)):
self._step_one()
self._user_actions.append_step(n, to_end)
elif self._end_time is None or self.TIME < self._end_time:
for i in range(n):
self._step_one()
self._user_actions.append_step(n, to_end)
else:
raise MinnetonkaError(
'Attempted to simulation beyond end_time: {}'.format(
self._end_time))
def reset(self, reset_external_vars=True):
"""
Reset simulation, back to the begining.
Reset simulation time back to the beginning time, and reset the
amounts of all variables back to their initial amounts.
Parameters
----------
reset_external_vars : bool, optional
Sometimes variables are set to amounts outside the model logic.
(See example below, and more examples with :func:`constant`,
:func:`variable`, and :func:`stock`.)
Should these externally-defined variables be reset to their initial amounts
when the model as a whole is reset? Default: True, reset those
externally-defined variables.
Returns
-------
None
Examples
--------
Create a simple model.
>>> m = model([stock('Year', 1, 2019)])
>>> m['Year']['']
2019
Step the model.
>>> m.step()
>>> m['Year']['']
2020
>>> m.step()
>>> m['Year']['']
2021
Reset the model.
>>> m.reset()
>>> m['Year']['']
2019
Change the amount of year. **Year** is now externally defined.
>>> m['Year'][''] = 1955
>>> m['Year']['']
1955
Reset the model again.
>>> m.reset(reset_external_vars=False)
>>> m['Year']['']
1955
Reset one more time.
>>> m.reset()
>>> m['Year']['']
2019
"""
if self._on_reset:
self._on_reset(self)
self._initialize_time()
self._variables.reset(reset_external_vars)
self._user_actions.append_reset(reset_external_vars)
def initialize(self):
"""Initialize simulation."""
logging.info('enter')
if self._on_init:
self._on_init(self)
self._initialize_time()
self._variables.initialize(self)
def _step_one(self):
"""Advance the simulation a single step."""
self._increment_time()
self._variables.step(self._timestep)
def _increment_time(self):
"""Advance time variables one time step."""
self.TIME = self.TIME + self._timestep
self.STEP = self.STEP + 1
def treatments(self):
"""Return an iterator of the treatments."""
return self._treatments.values()
def _is_valid_treatment(self, treatment):
"""Is the treatment valid?"""
return treatment == '__all__' or treatment in self._treatments
def treatment(self, treatment_name):
"""Return a particular treatment from the model."""
try:
return self._treatments[treatment_name]
except KeyError:
raise MinnetonkaError('Model has no treatment {}'.format(
treatment_name))
def derived_treatment_exists(self, treatment_name):
"""Does the derived treatment exist on the model?"""
return treatment_name in self._derived_treatments
def derived_treatment(self, treatment_name):
"""Return a particular derived treatment from the model."""
try:
return self._derived_treatments[treatment_name]
except KeyError:
raise MinnetonkaError('Model has no derived treatment {}'.format(
treatment_name))
def derived_treatments(self):
"""Iterator over names of all derived treatments."""
return self._derived_treatments.keys()
def variable(self, variable_name):
"""
Return a single variable from the model, by name.
Return a single variable---or stock or constant or accum or previous---
from the model, by providing the variable's name.
A variable is typically accessed from a model by subscription, like a
dictionary value from a dictionary, e.g. ``modl['var']``. The
subscription syntax is syntactic sugar for :meth:`variable`.
Note that :meth:`variable` returns a variable object, not the current
amount of the variable. To find the variable's current amount
in a particular treatment, use a further subscription with the
treatment name, e.g. ``modl['var']['']``. See examples below.
Parameters
----------
variable_name : str
The name of the variable. The variable might be a plain variable,
a stock, an accum, a constant, or any of the variable-like objects
known by the model.
Returns
-------
Variable : newly-defined variable with name ``variable_name``
Raises
------
MinnetonkaError
If no variable named ``variable_name`` exists in the model
Examples
--------
Create a model **m** with three variables, and only the default
treatment.
>>> with model() as m:
... variable('Earnings', lambda r, c: r - c, 'Revenue', 'Cost')
... variable('Cost', 10)
... variable('Revenue', 12)
Find the variable **Cost** ...
>>> m.variable('Cost')
variable('Cost')
... or use subscription syntax to do the same thing
>>> m['Cost']
variable('Cost')
>>> m.variable('Cost') == m['Cost']
True
Find the current amount of **Cost** in the default treatment.
>>> m['Cost']['']
10
"""
return self._variables.variable(variable_name)
def add_variables(self, *variables):
"""Add the variables and everything they depend on.
"""
logging.info('enter on variables {}'.format(variables))
self._variables.add_variables(self, *variables)
@classmethod
def add_variable_to_current_context(cls, var_object):
"""If a context is currently open, add this variable object to it.
:param Variable var_object: the variable object being added to the context
"""
if cls._model_context is not None:
cls._model_context._variables_not_yet_added.append(var_object)
@classmethod
def add_constraint_to_current_context(cls, constraint):
"""If context is currently open, add this constraint."""
if cls._model_context is not None:
cls._model_context._constraints.append(constraint)
def _add_variables_and_initialize(self, *variables):
"""Add variables and initialize. The model may already be inited."""
logging.info('enter on variables {}'.format(variables))
self.add_variables(*variables)
self.initialize()
def _uninitialize(self):
"""Remove the effects of initializtion."""
self._variables.uninitialize()
self._initialize_time()
def _initialize_time(self):
"""Set time variables to the beginning."""
self.TIME = self._start_time
self.STEP = 0
def previous_step(self):
"""Return the prior value of STEP."""
return self.STEP - 1
def recalculate(self):
"""
Recalculate all variables, without advancing the step.
Recalculation is only necessary when the amount of a variable (or
constant or stock) is changed
explicitly, outside of the model logic. The variables that depend on
that changed variable will take amounts that do not reflect the changes,
at least until the model is stepped. If that is not appropriate, a
call to **recalculate()** will calculate new updated amounts for all
those dependent variables.
Example
-------
>>> with model() as m:
... Foo = constant('Foo', 9)
... Bar = variable('Bar', lambda x: x+2, 'Foo')
>>> Bar['']
11
>>> Foo[''] = 7
**Bar** still takes the amount based on the previous amount of **Foo**.
>>> Bar['']
11
Recalculating updates the amounts.
>>> m.recalculate()
>>> Bar['']
9
"""
if self.STEP==0:
self._variables.recalculate(at_start=True)
else:
self._variables.recalculate(at_start=False)
self._user_actions.append_recalculate()
def variable_instance(self, variable_name, treatment_name):
"""Find or create right instance for this variable and treatment."""
# A more pythonic approach than checking for this known string?
if variable_name == '__model__':
return self._pseudo_variable
else:
return self.variable(variable_name).by_treatment(treatment_name)
def validate_and_set(self, variable_name, treatment_name, new_amount,
excerpt='', record=True):
"""Validate the new_amount and if valid set the variable to it."""
res = _Result(
variable=variable_name,
amount=new_amount,
treatment=treatment_name,
excerpt=excerpt)
try:
var = self.variable(variable_name)
except MinnetonkaError:
return res.fail(
'UnknownVariable', f'Variable {variable_name} not known.')
if self._is_valid_treatment(treatment_name):
res = var.validate_and_set(treatment_name, new_amount, res, excerpt)
if res['success'] and record:
self._user_actions.append_set_variable(
variable_name, treatment_name, new_amount, excerpt)
return res
else:
return res.fail(
'UnknownTreatment', f'Treatment {treatment_name} not known.')
def validate_all(self):
"""Validate against all cross-variable constraints. Return results."""
errors = self._validate_errors()
if len(errors) == 0:
return {'success': True}
else:
return {'success': False, 'errors': errors}
def _validate_errors(self):
"""Return all validation errors from all the constraints."""
errors = (constraint.fails(self) for constraint in self._constraints)
return [err for err in errors if err]
def recording(self):
"""Return a string of all the user actions, for persistance."""
return self._user_actions.recording()
def replay(self, recording, rewind_actions_first=True, ignore_step=False):
"""Replay a bunch of previous actions."""
self._user_actions.replay(
recording, self, rewind_first=rewind_actions_first,
ignore_step=ignore_step)
def history(self, base=False):
"""Return history of all amounts of all variables in all treatments."""
return self._variables.history(base=base)
def is_modified(self, varname, treatment_name):
"""Has variable named varname been modified in treatment?"""
return self.variable_instance(varname, treatment_name).is_modified()
def model(variables=[], treatments=[''], derived_treatments=None,
initialize=True, timestep=1, start_time=0, end_time=None,
on_init=None, on_reset=None):
"""
Create and initialize a model, an instance of :class:`Model`
A model is a collection of variables, with one or more treatments. A
model can be simulated, changing the value of variables with each simulated
step.
A model can be created via :meth:`Model`, after treatment objects have
been explicitly created. But typically this function
is used instead, as it is simpler.
A model sets a context, so variables can be defined for
the newly created model, as in the example below.
Parameters
----------
variables : list of :class:`Variable`, optional
List of variables that are part of the model. If not specified,
the default is [], no variables. An alternative to
creating the variables first, then the model, is to define the
variables within the model context, as in the example below.
treatments : list of str, or list of tuple of (str, str), optional
List of treatment specs. Each treatment specs is a simulation scenario,
simulated in parallel. Typical treatments might include 'As is',
'To be', 'At risk', 'Currently', With minor intervention',
etc. A treatment can be either a string---the name of the
treatment---or a tuple of two strings---the name and a short
description. See examples below.
If not specified, the default is ``['']``, a single
treatment named by the empty string.
initialize : bool, optional
After the variables are added to the model, should all the variables
be given their initial values? If more variables need to be added to
the model, wait to initialize. Default: True
timestep : int, optional
How much simulated time should elapse between each step? Default: 1
time unit
start_time : int, optional
At what time should the simulated clock start? Default: start at 0
end_time : int, optional
At what simulated time should the simulatation end? Default: None,
never end
Returns
-------
Model
the newly created model
See Also
--------
:class:`Model` : a model, once created
variable : Create a :class:`Variable` to put in a model
constant : Create a :class:`Constant` to put in a model
previous : Create a :class:`Previous` to put in a model
stock : Create a system dynamics :class:`Stock`, to put in a model
accum : Create an :class:`Accum`, to put in a model
Examples
--------
Create a model with no variables and only the null treatment:
>>> m = model()
A model that defines two treatments:
>>> model(treatments=['As is', 'To be'])
One of the treatments has a description:
>>> model(treatments=[('As is', 'The current situation'), 'To be'])
A model with two variables:
>>> m = model([DischargeBegins, DischargeEnds])
Variables can be defined when the model is created:
>>> m = model([
... variable('Revenue', np.array([30.1, 15, 20])),
... variable('Cost', np.array([10, 10, 10])),
... variable('Earnings', lambda r, c: r - c, 'Revenue', 'Cost')
... ])
A model is a context, supporting variable addition:
>>> with model() as m:
... variable('Revenue', np.array([30.1, 15, 20]))
... variable('Cost', np.array([10, 10, 10]))
... variable('Earnings', lambda r, c: r - c, 'Revenue', 'Cost')
"""
def _create_treatment_from_spec(spec):
"""Create treatment.
Spec is either a name or a tuple of name and description.
"""
try:
name, description = spec
return Treatment(name, description)
except ValueError:
return Treatment(spec)
derived_treatments={} if derived_treatments is None else derived_treatments
for dt in derived_treatments.keys():
if dt in treatments:
raise MinnetonkaError(f'Derived treatment {dt} is also a treatment')
if end_time is not None and end_time < start_time:
raise MinnetonkaError('End time {} is before start time {}'.format(
end_time, start_time))
m = Model(
{t.name: t for t in [
_create_treatment_from_spec(spec) for spec in treatments]},
derived_treatments=derived_treatments,
timestep=timestep,
start_time=start_time,
end_time=end_time,
on_init=on_init,
on_reset=on_reset)
m.add_variables(*variables)
if initialize and variables:
m.initialize()
return m
class UserActions:
"""Manage the list of user actions."""
def __init__(self):
self._actions = []
def append_set_variable(self, varname, treatment_name, new_amount, excerpt):
"""Add a single user action (e.g. set variable) to record."""
self._append_action(ValidateAndSetAction(
varname, treatment_name, excerpt, new_amount))
def _append_action(self, new_action):
"""Add the new action to the lsit of actions."""
if any(new_action.supercedes(action) for action in self._actions):
self._actions = [action for action in self._actions
if not new_action.supercedes(action)]
self._actions.append(new_action)
def append_step(self, n, to_end):
"""Add a single user step action to record."""
self._append_action(StepAction(n, to_end))
def append_recalculate(self):
"""Append a single recalculate action to records."""
self._append_action(RecalculateAction())
def append_reset(self, reset_external_vars):
"""Append a single reset to records."""
self._append_action(ResetAction(reset_external_vars))
def recording(self):
"""Record a string of all user actions, for persistance."""
return json.dumps([action.freeze() for action in self._actions])
def thaw_recording(self, recording):
return json.loads(recording)
def replay(self, recording, mod, rewind_first=True, ignore_step=False):
"""Replay a previous recording."""
if rewind_first:
self.rewind()
for frozen_action in self.thaw_recording(recording):
action_type = frozen_action['type']
if ignore_step and action_type =='step':
pass
else:
del frozen_action['type']
action = {
'validate_and_set': ValidateAndSetAction,
'step': StepAction,
'recalculate': RecalculateAction,
'reset': ResetAction
}[action_type](**frozen_action)
action.thaw(mod)
def rewind(self):
"""Set the action list back to no actions."""
self._actions = []
class ValidateAndSetAction:
"""A single user action for setting a variable"""
def __init__(self, variable_name, treatment_name, excerpt, amount):
self.variable = variable_name
self.treatment = treatment_name
self.excerpt = excerpt
try:
json.dumps(amount)
self.amount = amount
except TypeError:
raise MinnetonkaError(
f'Cannot save amount for later playback: {amount}')
def supercedes(self, other_action):
"""Does this action supercede the other? Note: amounts do not matter."""
if isinstance(other_action, ValidateAndSetAction):
return (
self.variable == other_action.variable and
self.treatment == other_action.treatment and
self.excerpt == other_action.excerpt)
else:
return False
def freeze(self):
"""Freeze this to simple json."""
return {
'type': 'validate_and_set',
'variable_name': self.variable,
'treatment_name': self.treatment,
'excerpt': self.excerpt,
'amount': self.amount
}
def thaw(self, mod):
"""Apply once-frozen action to model."""
res = mod.validate_and_set(
self.variable, self.treatment, self.amount, self.excerpt)
if not res['success']:
raise MinnetonkaError(
'Failed to replay action {}["{}"]{} = {},'.format(
variable, treatment, excerpt, amount) +
'Result: {}'.format(res))
class StepAction:
"""A single user action for stepping the model."""
def __init__(self, n, to_end):
self.n = n
self.to_end = to_end
def freeze(self):
"""Freeze this to simple json."""
return {'type': 'step', 'n': self.n, 'to_end': self.to_end }
def thaw(self, mod):
"""Apply once-frozen action to model."""
mod.step(n=self.n, to_end=self.to_end)
def supercedes(self, other_action):
"""Does this action supercede the prior action? No it does not"""
return False
class RecalculateAction:
"""A single user action to recalculate the model."""
def __init__(self):
pass
def freeze(self):
"""Freeze this to simple json."""
return {'type': 'recalculate'}
def thaw(self, mod):
"""Apply once-frozen action to model."""
mod.recalculate()
def supercedes(self, other_action):
"""Does this action supercede the prior action? No it does not"""
return False
class ResetAction:
"""A single user action to reset the simulation."""
def __init__(self, reset_external_vars):
self.reset_external_vars = reset_external_vars
def freeze(self):
"""Freeze this to simple json."""
return {
'type': 'reset',
'reset_external_vars': self.reset_external_vars
}
def thaw(self, mod):
"""Apply once-frozen action to model."""
mod.reset(reset_external_vars=self.reset_external_vars)
def supercedes(self, other_action):
"""Does the action supercede the prior action?"""
if self.reset_external_vars:
# Remove everything already done
return True
elif isinstance(other_action, ValidateAndSetAction):
return False
else:
return True
class ModelVariables:
"""Manage the ordered list of variables of a model."""
def __init__(self):
"""Initialize the model variables."""
self._variables = {}
self._is_ordered = False
def _variable_iterator(self):
"""Return an iterator over variables."""
return self._variables.values()
def _varirable_name_iterator(self):
"""Return an iterator over variable names."""
return self._variables.keys()
def add_variables(self, model, *variables):
"""Add the list of variables."""
logging.info('enter with variables {}'.format(variables))
assert not self._is_ordered, (
'Cannot add variables {} after the variables are ordered').format(
variables)
for var in variables:
self._add_single_variable(model, var)
def _add_single_variable(self, model, var):
"""Add a variable to the model variables."""
logging.info('enter with variable {}'.format(var))
if var.name() in self._variables:
warnings.warn(
'Variable {} redefined'.format(var.name()), MinnetonkaWarning)
self._variables[var.name()] = var
var.note_model(model)
def variable(self, variable_name):
"""Return the variable with variable_name, if it exists."""
try:
return self._variables[variable_name]
except AttributeError:
try:
return self._variables_ordered_for_init[variable_name]
except KeyError:
raise MinnetonkaError(
'Unknown variable {}'.format(variable_name))
except KeyError:
raise MinnetonkaError('Unknown variable {}'.format(variable_name))
def initialize(self, model):
"""Initialize the variables of the simulation."""
logging.info('enter')
self._check_for_cycles(model)
self._label_taries()
self._create_all_variable_instances()
self._wire_variable_instances(model)
self._sort_variables()
self.set_initial_amounts()
logging.info('exit')
def _check_for_cycles(self, model):
"""Check for any cycle among variables, raising error if necessary."""
logging.info('enter')
variables_seen = []
for variable in self._variable_iterator():
if variable not in variables_seen:
variable.check_for_cycle(variables_seen)
def _label_taries(self):
"""Label every model variable as either unitary or multitary."""
self._label_tary_initial()
self._label_multitary_succedents()
self._label_unknowns_unitary()
def _label_tary_initial(self):
"""Label the tary of model variables, with some unknown."""
for var in self._variable_iterator():
if not var.has_unitary_definition():
var.tary = 'multitary'
elif var.antecedents(ignore_pseudo=True) == []:
var.tary = 'unitary'
else:
var.tary = 'unknown'
def _label_multitary_succedents(self):
"""Label all succedents of multitary variables as multitary."""
succedents = self._collect_succedents()
multitaries = [v for v in self._variable_iterator()
if v.tary == 'multitary']
for var in multitaries:
self._label_all_succedents_multitary(var, succedents)
def _collect_succedents(self):
"""Return dict of succedents of each variable."""
succedents = {v: set([]) for v in self._variable_iterator()}
for var in self._variable_iterator():
for ante in var.antecedents(ignore_pseudo=True):
succedents[ante].add(var)
return succedents
def _label_all_succedents_multitary(self, var, succedents):
"""Label all succedents (and their succedents) or var as multitary."""
var.tary = 'multitary'
for succ in succedents[var]:
if succ.tary == 'unknown':
self._label_all_succedents_multitary(succ, succedents)
def _label_unknowns_unitary(self):
"""Label every unknown variable as unitary."""
for v in self._variable_iterator():
if v.tary == 'unknown':
v.tary = 'unitary'
def _create_all_variable_instances(self):
"""Create all variable instances."""
logging.info('enter')
for variable in self._variable_iterator():
variable.create_variable_instances()
def _wire_variable_instances(self, model):
"""Provide each of the var instances with its antecedent instances."""
logging.info('enter')
for variable in self._variable_iterator():
variable.wire_instances()
def _sort_variables(self):
"""Sort the variables from dependent to independent, twice.
Create two sorted lists, one for init and the other for step.
They are identical, except for the effect of accums and stock and
previous.
"""
logging.info('enter')
self._variables_ordered_for_init = self._sort_variables_for(
for_init=True)
self._variables_ordered_for_step = self._sort_variables_for(
for_init=False)
self._is_ordered = True
def _sort_variables_for(self, for_init=False):
"""Sort the variables from dependent to independent."""
ordered_variables = collections.OrderedDict()
def _maybe_insert_variable_and_antes(variable_name, already_seen):
"""Insert the variable and its antecedents if they do exist."""
if variable_name in already_seen:
pass
elif (variable_name not in ordered_variables):
var = self.variable(variable_name)
for ante in var.depends_on(
for_init=for_init, for_sort=True, ignore_pseudo=True):
_maybe_insert_variable_and_antes(
ante, [variable_name] + already_seen)
ordered_variables[variable_name] = var
for variable in self._variable_iterator():
_maybe_insert_variable_and_antes(variable.name(), list())
return ordered_variables
def set_initial_amounts(self):
"""Set initial amounts for all the variables."""
logging.info('enter')
for var in self._variables_ordered_for_init.values():
var.set_all_initial_amounts()
logging.info('exit')
def uninitialize(self):
"""Undo the initialization, typically to add more variables."""
self._is_ordered = False
self._delete_existing_variable_instances()
def _delete_existing_variable_instances(self):
"""Delete any variable instances that were previouslsy created."""
for variable in self._variable_iterator():
variable.delete_all_variable_instances()
def reset(self, reset_external_vars):
"""Reset variables.
If reset_external_vars is false, don't reset the external variables,
those whose value has been set outside the model itself.
"""
for var in self._variables_ordered_for_init.values():
var.reset_all(reset_external_vars)
def step(self, timestep):
"""Advance all the variables one step in the simulation."""
for var in self._variables_ordered_for_step.values():
var.calculate_all_increments(timestep)
for var in self._variables_ordered_for_step.values():