bptk-py 0.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. BPTK_Py-0.3.5/BPTK_Py/__init__.py +15 -0
  2. BPTK_Py-0.3.5/BPTK_Py/bptk.py +281 -0
  3. BPTK_Py-0.3.5/BPTK_Py/config/__init__.py +0 -0
  4. BPTK_Py-0.3.5/BPTK_Py/config/config.py +71 -0
  5. BPTK_Py-0.3.5/BPTK_Py/logger/__init__.py +0 -0
  6. BPTK_Py-0.3.5/BPTK_Py/logger/logger.py +26 -0
  7. BPTK_Py-0.3.5/BPTK_Py/modelchecker/model_checker.py +36 -0
  8. BPTK_Py-0.3.5/BPTK_Py/modelmonitor/__init__.py +0 -0
  9. BPTK_Py-0.3.5/BPTK_Py/modelmonitor/model_monitor.py +114 -0
  10. BPTK_Py-0.3.5/BPTK_Py/scenariomanager/__init__.py +0 -0
  11. BPTK_Py-0.3.5/BPTK_Py/scenariomanager/scenario.py +114 -0
  12. BPTK_Py-0.3.5/BPTK_Py/scenariomanager/scenario_manager.py +152 -0
  13. BPTK_Py-0.3.5/BPTK_Py/scenariomanager/scenario_manager_factory.py +329 -0
  14. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/.babelrc +3 -0
  15. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/README.md +217 -0
  16. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/package-lock.json +5552 -0
  17. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/package.json +51 -0
  18. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/spec/SMILEv4.pdf +0 -0
  19. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/spec/XMILEv4.pdf +0 -0
  20. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/cli.js +81 -0
  21. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/ast.js +83 -0
  22. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/index.js +14 -0
  23. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/js/index.js +154 -0
  24. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/js/templates/functions.txt +20 -0
  25. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/js/templates/model.hbs +66 -0
  26. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/js/transforms/builtins.js +137 -0
  27. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/js/transforms/operators.js +26 -0
  28. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/m/index.js +115 -0
  29. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/m/templates/package.hbs +60 -0
  30. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/m/transforms/builtins.js +171 -0
  31. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/m/transforms/operators.js +57 -0
  32. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/py/index.js +137 -0
  33. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/py/templates/functions.txt +20 -0
  34. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/py/templates/model.hbs +82 -0
  35. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/py/transforms/builtins.js +178 -0
  36. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/generators/py/transforms/operators.js +57 -0
  37. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/helpers.js +94 -0
  38. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/parsers/index.js +14 -0
  39. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/parsers/smile/grammar.pegjs +232 -0
  40. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/parsers/smile/index.js +26 -0
  41. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/parsers/xmile/index.js +275 -0
  42. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/expandArrays.js +241 -0
  43. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/filterGhosts.js +21 -0
  44. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/index.js +28 -0
  45. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/makeNameAbsolute.js +109 -0
  46. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/non_negative.js +30 -0
  47. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/nothing.js +9 -0
  48. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/sanitizeNames.js +92 -0
  49. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/sortEntities.js +22 -0
  50. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/plugins/sd/stockExpressions.js +72 -0
  51. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/strategies/index.js +15 -0
  52. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/strategies/load.js +53 -0
  53. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/strategies/xmile/ir.js +21 -0
  54. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/strategies/xmile/js.js +22 -0
  55. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/strategies/xmile/m.js +22 -0
  56. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/src/strategies/xmile/py.js +22 -0
  57. BPTK_Py-0.3.5/BPTK_Py/sd-compiler/webpack.config.js +34 -0
  58. BPTK_Py-0.3.5/BPTK_Py/simulator/__init__.py +0 -0
  59. BPTK_Py-0.3.5/BPTK_Py/simulator/model_simulator.py +211 -0
  60. BPTK_Py-0.3.5/BPTK_Py/simulator/simulation_wrapper.py +181 -0
  61. BPTK_Py-0.3.5/BPTK_Py/visualizations/__init__.py +0 -0
  62. BPTK_Py-0.3.5/BPTK_Py/visualizations/visualize.py +227 -0
  63. BPTK_Py-0.3.5/BPTK_Py/widgetdecorator/__init__.py +0 -0
  64. BPTK_Py-0.3.5/BPTK_Py/widgetdecorator/widget_decorator.py +203 -0
  65. BPTK_Py-0.3.5/BPTK_Py.egg-info/PKG-INFO +394 -0
  66. BPTK_Py-0.3.5/BPTK_Py.egg-info/SOURCES.txt +74 -0
  67. BPTK_Py-0.3.5/BPTK_Py.egg-info/dependency_links.txt +1 -0
  68. BPTK_Py-0.3.5/BPTK_Py.egg-info/not-zip-safe +1 -0
  69. BPTK_Py-0.3.5/BPTK_Py.egg-info/requires.txt +5 -0
  70. BPTK_Py-0.3.5/BPTK_Py.egg-info/top_level.txt +1 -0
  71. BPTK_Py-0.3.5/MANIFEST.in +1 -0
  72. BPTK_Py-0.3.5/PKG-INFO +394 -0
  73. BPTK_Py-0.3.5/setup.cfg +4 -0
  74. BPTK_Py-0.3.5/setup.py +29 -0
  75. BPTK_Py-0.3.5/test/test.py +53 -0
@@ -0,0 +1,15 @@
1
+ #from .scenario_manager.scenario import simulation_scenario
2
+
3
+ import pkg_resources
4
+
5
+
6
+ try:
7
+ __version__ = pkg_resources.get_distribution("BPTK_Py").version
8
+
9
+ except:
10
+ # If I am not installed, I will not be able to set the version
11
+ __version__ = "UNAVAILABLE"
12
+
13
+
14
+ name = "BPTK_Py"
15
+
@@ -0,0 +1,281 @@
1
+ # /`-
2
+ # _ _ _ /####`-
3
+ # | | | | (_) /########`-
4
+ # | |_ _ __ __ _ _ __ ___ ___ _ __ | |_ _ ___ /###########`-
5
+ # | __| '__/ _` | '_ \/ __|/ _ \ '_ \| __| / __| ____ -###########/
6
+ # | |_| | | (_| | | | \__ \ __/ | | | |_| \__ \ | | `-#######/
7
+ # \__|_| \__,_|_| |_|___/\___|_| |_|\__|_|___/ |____| `- # /
8
+ #
9
+ # Copyright (c) 2018 transentis labs GmbH
10
+ # MIT License
11
+
12
+
13
+ ### IMPORTS
14
+ from BPTK_Py.logger.logger import log
15
+ from BPTK_Py.visualizations.visualize import visualizer
16
+ import matplotlib.pyplot as plt
17
+ from BPTK_Py.modelchecker.model_checker import modelChecker
18
+ from BPTK_Py.widgetdecorator.widget_decorator import widgetDecorator
19
+ import BPTK_Py.config.config as config
20
+ from BPTK_Py.scenariomanager.scenario_manager_factory import ScenarioManagerFactory
21
+ from BPTK_Py.simulator.simulation_wrapper import simulationWrapper
22
+ from BPTK_Py.scenariomanager.scenario import simulationScenario
23
+
24
+ plt.interactive(True)
25
+
26
+
27
+ ###
28
+
29
+
30
+ ##################
31
+ ### CLASS BPTK ###
32
+ ##################
33
+
34
+
35
+ ### The Main API entry point for simulating System Dynamics models using python. This class is not supposed to store logic, just call methods in child objects
36
+ class bptk():
37
+
38
+ def __init__(self):
39
+ """
40
+ Configures the matplotlib config and instantiates the scenario manager factory and visualizer
41
+ """
42
+
43
+ # Setup matplotlib
44
+ import BPTK_Py.config.config as config
45
+ for key, value in config.configuration["matplotlib_rc_settings"].items():
46
+ plt.rcParams[key] = value
47
+
48
+ self.scenario_manager_factory = ScenarioManagerFactory()
49
+ self.scenario_manager_factory.get_scenario_managers()
50
+ self.visualizer = visualizer(self.scenario_manager_factory, bptk=self)
51
+
52
+ def run_simulations_with_strategy(self, scenarios, equations=[], output=["frame"], scenario_managers=[]):
53
+ """
54
+ method to run raw simulations (if you want to omit plotting). Simulates with the strategies of the scenarios
55
+ :param scenarios: names of scenarios to simulate
56
+ :param equations: names of equations to simulate
57
+ :param output: output types as list. Default: ["frame"], may add "csv" to store results in results/scenario.csv
58
+ :param scenario_managers: names of scenario managers to select scenarios from
59
+ :return: dict of simulationScenario
60
+ """
61
+ return simulationWrapper(self.scenario_manager_factory).run_simulations_with_strategy(scenarios=scenarios,
62
+ equations=equations,
63
+ output=output,
64
+ scenario_managers=scenario_managers)
65
+
66
+
67
+ def run_simulations(self, scenarios, equations=[], output=["frame"], scenario_managers=[]):
68
+ """
69
+ Method to run simulations (if you want to omit plotting). Use it to bypass plotting and obtain raw results
70
+ :param scenarios: names of scenarios to simulate
71
+ :param equations: names of equations to simulate
72
+ :param output: output types as list. Default: ["frame"], may add "csv" to store results in results/scenario_name.csv
73
+ :param scenario_managers: names of scenario managers to select scenarios from
74
+ :return: dict of simulationScenarios
75
+ """
76
+ return simulationWrapper(self.scenario_manager_factory).run_simulations(scenarios=scenarios,
77
+ equations=equations,
78
+ output=output,
79
+ scenario_managers=scenario_managers)
80
+
81
+
82
+ def plot_scenarios(self, scenarios, equations, scenario_managers=[], kind=config.configuration["kind"],
83
+ alpha=config.configuration["alpha"], stacked=config.configuration["stacked"],
84
+ freq="D", start_date="", title="", visualize_from_period=0, visualize_to_period=0, x_label="",
85
+ y_label="",
86
+ series_names={}, strategy=False,
87
+ return_df=False):
88
+
89
+ """
90
+ Generic method for plotting scenarios
91
+ :param scenarios: names of scenarios to plot
92
+ :param equations: names of equations to plot
93
+ :param scenario_managers: names of scenario managers to plot
94
+ :param kind: type of graph to plot
95
+ :param alpha: transparency 0 < x <= 1
96
+ :param stacked: if yes, use stacked (only with kind="bar")
97
+ :param freq: frequency of time series
98
+ :param start_date: start date for time series
99
+ :param title: title of plot
100
+ :param visualize_from_period: visualize from specific period onwards
101
+ :param visualize_to_period; visualize until a specific period
102
+ :param x_label: label for x axis
103
+ :param y_label: label for y axis
104
+ :param series_names: names of series to rename to, using a dict: {equation_name : rename_to}
105
+ :param strategy: set True if you want to use the scenarios' strategies
106
+ :param return_df: set True if you want to receive a dataFrame instead of the plot
107
+ :return: dataFrame with simulation results if return_df=True
108
+ """
109
+
110
+ return self.visualizer.plot_scenarios(scenarios=scenarios,
111
+ equations=equations,
112
+ scenario_managers=scenario_managers,
113
+ kind=kind,
114
+ alpha=alpha,
115
+ stacked=stacked,
116
+ freq=freq,
117
+ start_date=start_date,
118
+ title=title,
119
+ visualize_from_period=visualize_from_period,
120
+ visualize_to_period=visualize_to_period,
121
+ x_label=x_label,
122
+ y_label=y_label,
123
+ series_names=series_names,
124
+ strategy=strategy,
125
+ return_df=return_df)
126
+
127
+ ## Method for plotting scenarios with sliders. A more generic method that uses the WidgetDecorator class to decorate the plot with the sliders
128
+ def dashboard(self, scenarios, equations, scenario_managers=[], kind=config.configuration["kind"],
129
+ alpha=config.configuration["alpha"], stacked=config.configuration["stacked"],
130
+ freq="D", start_date="", title="", visualize_from_period=0, visualize_to_period=0, x_label="",
131
+ y_label="",
132
+ series_names={}, strategy=False,
133
+ return_df=False, constants=[]):
134
+ """
135
+ Generic method for plotting with interactive widgets
136
+ :param scenarios: names of scenarios to plot
137
+ :param equations: names of equations to plot
138
+ :param scenario_managers: names of scenario managers to plot
139
+ :param kind: type of graph to plot
140
+ :param alpha: transparency 0 < x <= 1
141
+ :param stacked: if yes, use stacked (only with kind="bar")
142
+ :param freq: frequency of time series
143
+ :param start_date: start date for time series
144
+ :param title: title of plot
145
+ :param visualize_from_period: visualize from specific period onwards
146
+ :param visualize_to_period; visualize until a specific period
147
+ :param x_label: label for x axis
148
+ :param y_label: label for y axis
149
+ :param series_names: names of series to modify
150
+ :param strategy: set True if you want to use the scenarios' strategies
151
+ :param return_df: set True if you want to receive a dataFrame instead of the plot
152
+ :param constants: constants to modify and type of widget (widget_type, equation_name, from, to ) --> from, to only for sliders
153
+ :return: dataFrame with simulation results if return_df=True
154
+ """
155
+ log("[INFO] Generating a plot with sliders. Scenarios: {}, Constants with slider and intervals: {}".format(
156
+ scenarios, str(constants)))
157
+ widget_decorator = widgetDecorator(self)
158
+
159
+ return widget_decorator.dashboard(scenarios=scenarios,
160
+ equations=equations,
161
+ scenario_managers=scenario_managers,
162
+ kind=kind,
163
+ alpha=alpha,
164
+ stacked=stacked,
165
+ freq=freq,
166
+ start_date=start_date, title=title,
167
+ visualize_from_period=visualize_from_period,
168
+ visualize_to_period=visualize_to_period,
169
+ x_label=x_label,
170
+ y_label=y_label,
171
+ series_names=series_names,
172
+ strategy=strategy,
173
+ return_df=return_df,
174
+ constants=constants)
175
+
176
+ def modify_strategy(self, scenarios, extended_strategy):
177
+ """
178
+ Modifies a strategy during runtime. Experimental feature for now. You may even add lambdas to strategy
179
+ :param scenarios: names of scenarios to modify the strategies for
180
+ :param extended_strategy: the actual extended strategy as a dict. Consult the readme!
181
+ :return: None
182
+ """
183
+
184
+ for scenario_name in extended_strategy.keys():
185
+
186
+ # Obtain scenario object (which actually IS A POINTER, NOT A COPY)
187
+ scenario = scenarios[scenario_name]
188
+ self.reset_simulation_model(scenario_manager=scenario.group, scenario=scenario_name)
189
+
190
+ ## Points in time where the extended strategy makes changes
191
+ points_to_change_at = list(extended_strategy[scenario_name].keys())
192
+
193
+ # If the scenario does not store an initial strategy in its JSON, create an empty one
194
+ if "strategy" not in scenario.dictionary.keys():
195
+ scenario.dictionary["strategy"] = {}
196
+ ## Points in time where the original strategy makes changes (if any): These are the constant changes from the JSON
197
+
198
+ # Store original lambda in strategy at starttime moment. Logic: Keep original method as constant so it will work until the first point in the strategy
199
+ first_t = points_to_change_at[0]
200
+
201
+ ## Extend existing strategy by the lambda methods
202
+ for t in points_to_change_at:
203
+ if str(t) not in scenario.dictionary["strategy"].keys():
204
+ scenario.dictionary["strategy"][str(t)] = {}
205
+
206
+ for name, equation in extended_strategy[scenario_name][t].items():
207
+ scenario.dictionary["strategy"][str(t)][name] = equation
208
+
209
+ # Backup all original lambdas of modified equations as "constants" for the simulation model
210
+ # --> whenever we inject another lambda at a point in time, we will use the original value until
211
+ # the first occurence of the modified strategy
212
+ if t == first_t and not name in scenario.dictionary["constants"].keys():
213
+ scenario.dictionary["constants"][name] = scenario.model.equations[name]
214
+ log("[INFO] Added extended strategy for scenarios")
215
+
216
+ def destroy(self):
217
+ """
218
+ When we do not want to use the BPTK object anymore but keep the Python Kernel running, use this...
219
+ It essentially only kills all the file monitors and makes sure the Python process can die happily
220
+ :return: None
221
+ """
222
+ log("[INFO] BPTK API: Got destroy signal. Stopping all threads that are running in background")
223
+ self.scenario_manager_factory.destroy()
224
+
225
+ def reset_simulation_model(self, scenario_manager="", scenario=""):
226
+ """
227
+ Resets only the memo (equation results) of a scenario, does not re-read from storage
228
+ :param scenario_manager: name of scenario manager for lookup
229
+ :param scenario: name of scenario
230
+ :return: None
231
+ """
232
+ scenario = self.scenario_manager_factory.get_scenario(scenario_manager=scenario_manager, scenario=scenario)
233
+ for key in scenario.model.memo.keys():
234
+ scenario.model.memo[key] = {}
235
+
236
+ def reset_scenario(self, scenario_manager, scenario):
237
+ """
238
+ Reload scenario from storage
239
+ :param scenario_manager: name of scenario manager for lookup
240
+ :param scenario: name of scenario
241
+ :return: None
242
+ """
243
+ self.scenario_manager_factory.reset_scenario(scenario_manager=scenario_manager, scenario=scenario)
244
+
245
+ def reset_all_scenarios(self):
246
+ """
247
+ Reload all scenarios from storage
248
+ :return: All Scenario Managers
249
+ """
250
+ return self.scenario_manager_factory.reset_all_scenarios()
251
+
252
+ def model_check(self, data, check, message):
253
+ """
254
+ Model checker
255
+ :param data: dataframe series or any data
256
+ :param check: lambda function of structure : lambda data : BOOLEAN CHECK
257
+ :param message: Error message if test failed
258
+ :return: None
259
+ """
260
+ modelChecker().model_check(data=data, check=check, message=message)
261
+
262
+ def add_scenario(self, dictionary):
263
+ """
264
+ Add scenario during runtime
265
+ :param dictionary: dictionary that contains all data required for the scenario. Check the readme!
266
+ :return: None
267
+ """
268
+
269
+ for scenario_manager_name in dictionary.keys():
270
+ source = ""
271
+ if "source" in dictionary[scenario_manager_name].keys():
272
+ source = dictionary[scenario_manager_name]["source"]
273
+ model_file = dictionary[scenario_manager_name]["model"]
274
+ scenarios = [k for k in dictionary[scenario_manager_name].keys() if not k == "source" and not k == "model"]
275
+
276
+ for scenario_name in scenarios:
277
+ scenario = simulationScenario(model=None, name=scenario_name, group=scenario_manager_name,
278
+ dictionary=dictionary[scenario_manager_name][scenario_name])
279
+
280
+ self.scenario_manager_factory.add_scenario(scenario=scenario, scenario_manager=scenario_manager_name,
281
+ source=source, model=model_file)
File without changes
@@ -0,0 +1,71 @@
1
+ # /`-
2
+ # _ _ _ /####`-
3
+ #| | | | (_) /########`-
4
+ #| |_ _ __ __ _ _ __ ___ ___ _ __ | |_ _ ___ /###########`-
5
+ #| __| '__/ _` | '_ \/ __|/ _ \ '_ \| __| / __| ____ -###########/
6
+ #| |_| | | (_| | | | \__ \ __/ | | | |_| \__ \ | | `-#######/
7
+ # \__|_| \__,_|_| |_|___/\___|_| |_|\__|_|___/ |____| `- # /
8
+ #
9
+ # Copyright (c) 2018 transentis labs GmbH
10
+ # MIT License
11
+
12
+ from ipywidgets import Layout
13
+ import BPTK_Py
14
+ import os
15
+
16
+
17
+ ##################################
18
+ ## BPTK_Py Global Configuration ##
19
+ ##################################
20
+
21
+ ### Plot Style settings
22
+ ## matplotlib style setting
23
+ matplotlib_rc_settings = {
24
+ "font.family": "DejaVu Sans",
25
+ "axes.titlesize": 35,
26
+ "axes.labelsize": 25,
27
+ "lines.linewidth": 3,
28
+ "lines.markersize": 15,
29
+ "xtick.labelsize": 15,
30
+ "ytick.labelsize": 15,
31
+ "figure.figsize": (20, 10),
32
+ 'legend.fontsize': 17,
33
+ }
34
+
35
+ transentis_colors = {
36
+ "blue": (0 / 100, 33.3 / 100, 45.1 / 100),
37
+ "olive": (60.8 / 100, 60.8 / 100, 5.9 / 100),
38
+ "orange": (100 / 100, 51 / 100, 0 / 100),
39
+ "grey": (34.1 / 100, 32.9 / 100, 34.1 / 100),
40
+ "red": (70.6 / 100, 0 / 100, 23.5 / 100),
41
+ "beige": (68.6 / 100, 60.8 / 100, 39.2 / 100),
42
+ "turquoise": (0 / 100, 58.8 / 100, 58.8 / 100),
43
+
44
+ }
45
+
46
+
47
+
48
+ sd_py_compiler_root = str(os.path.dirname(BPTK_Py.__file__)) + "/sd-compiler"
49
+
50
+ configuration = {
51
+ "sd_py_compiler_root": sd_py_compiler_root,
52
+ "bptk_Py_module_path" :os.path.dirname(BPTK_Py.__file__),
53
+
54
+ # Graphic settings
55
+ "matplotlib_rc_settings": matplotlib_rc_settings,
56
+ "colors": [color for color in transentis_colors.values()],
57
+ "kind": "area",
58
+ "stacked": False,
59
+ "figsize": matplotlib_rc_settings["figure.figsize"],
60
+ "alpha": 0.25,
61
+ "linewidth": matplotlib_rc_settings["lines.linewidth"],
62
+
63
+ #Relative path to scenario storage
64
+ "scenario_storage": "scenarios/",
65
+ "slider_style" : {'description_width': '40%'},
66
+ "slider_layout" : Layout(width='50%',position="center"),
67
+
68
+ # Log mode. List of strings. Possible values: "print" / "logfile"
69
+ "log_modes": ["logfile"],
70
+ "log_file": "bptk_py.log"
71
+ }
File without changes
@@ -0,0 +1,26 @@
1
+ # /`-
2
+ # _ _ _ /####`-
3
+ #| | | | (_) /########`-
4
+ #| |_ _ __ __ _ _ __ ___ ___ _ __ | |_ _ ___ /###########`-
5
+ #| __| '__/ _` | '_ \/ __|/ _ \ '_ \| __| / __| ____ -###########/
6
+ #| |_| | | (_| | | | \__ \ __/ | | | |_| \__ \ | | `-#######/
7
+ # \__|_| \__,_|_| |_|___/\___|_| |_|\__|_|___/ |____| `- # /
8
+ #
9
+ # Copyright (c) 2018 transentis labs GmbH
10
+ # MIT License
11
+
12
+
13
+
14
+ import BPTK_Py.config.config as config
15
+ import datetime
16
+
17
+
18
+ def log(message):
19
+ """logs all log messages either to file or stdout"""
20
+ message = message.replace("\n", "")
21
+ if "logfile" in config.configuration["log_modes"]:
22
+ with open(config.configuration["log_file"], "a", encoding="UTF-8") as myfile:
23
+ myfile.write(str(datetime.datetime.now()) + ", " + message + "\n")
24
+
25
+ if "print" in config.configuration["log_modes"] or "[ERROR]" in message:
26
+ print(str(datetime.datetime.now()) + ", " + message)
@@ -0,0 +1,36 @@
1
+ # /`-
2
+ # _ _ _ /####`-
3
+ # | | | | (_) /########`-
4
+ # | |_ _ __ __ _ _ __ ___ ___ _ __ | |_ _ ___ /###########`-
5
+ # | __| '__/ _` | '_ \/ __|/ _ \ '_ \| __| / __| ____ -###########/
6
+ # | |_| | | (_| | | | \__ \ __/ | | | |_| \__ \ | | `-#######/
7
+ # \__|_| \__,_|_| |_|___/\___|_| |_|\__|_|___/ |____| `- # /
8
+ #
9
+ # Copyright (c) 2018 transentis labs GmbH
10
+ # MIT License
11
+
12
+
13
+ ##########################
14
+ ### CLASS MODELCHECKER ###
15
+ ##########################
16
+
17
+ # Simple model checking
18
+ class modelChecker():
19
+ """simple model checking class. Can check assertions using lambda methods
20
+ """
21
+
22
+ def model_check(self, data, check, message="None"):
23
+ """
24
+ Model checker
25
+ :param data: dataframe series or any data
26
+ :param check: lambda function of structure : lambda data : BOOLEAN CHECK
27
+ :param message: Error message if test failed
28
+ :return: None
29
+ """
30
+
31
+ try:
32
+ assert check(data), message
33
+ print("[SUCCESS] Model check successful!")
34
+
35
+ except AssertionError as e:
36
+ print("[ERROR] Model Checking failed with message: \"{}\"".format(e))
File without changes
@@ -0,0 +1,114 @@
1
+ # /`-
2
+ # _ _ _ /####`-
3
+ # | | | | (_) /########`-
4
+ # | |_ _ __ __ _ _ __ ___ ___ _ __ | |_ _ ___ /###########`-
5
+ # | __| '__/ _` | '_ \/ __|/ _ \ '_ \| __| / __| ____ -###########/
6
+ # | |_| | | (_| | | | \__ \ __/ | | | |_| \__ \ | | `-#######/
7
+ # \__|_| \__,_|_| |_|___/\___|_| |_|\__|_|___/ |____| `- # /
8
+ #
9
+ # Copyright (c) 2018 transentis labs GmbH
10
+ #
11
+
12
+
13
+ ####### IMPORTS
14
+ from threading import Thread
15
+ import time
16
+ from BPTK_Py.logger.logger import log
17
+ import os
18
+ import BPTK_Py.config.config as config
19
+ #######
20
+
21
+ ########################
22
+ ## ClASS MODELMONITOR ##
23
+ ########################
24
+
25
+
26
+ class modelMonitor():
27
+ """
28
+ Simple monitoring script for itmx files.
29
+ Monitors itmx files and invokes parser when a change is detected
30
+ """
31
+
32
+ def __init__(self, source_file, dest, update_func):
33
+ """
34
+
35
+ :param source_file: path to itmx model
36
+ :param dest: destination file .py
37
+ :param update_func: a function that the monitor calls upon update to the source_file
38
+ """
39
+ self.update_func = update_func
40
+ self.source_file = source_file
41
+ self.dest = dest
42
+
43
+ current_dir = str(os.getcwd())
44
+ self.execute_script = "node -r babel-register src/cli.js -i \"" + current_dir + "/" + source_file + "\" -t py -c > \"" + current_dir + "/" + dest + ".py\""
45
+ log(
46
+ "[INFO] Model Monitor: Starting to Monitor {} for changes. Will transform itmx file to Python model whenever I observe changes to it! Destination file: {}".format(
47
+ source_file, dest))
48
+
49
+ # As long as this is True, I will keep monitoring. Otherwise the thread will terminate
50
+ self.running = True
51
+
52
+ # Initial last modification timestamp
53
+ self._cached_stamp = os.stat(self.source_file).st_mtime
54
+
55
+ # Starting the thread
56
+ t = Thread(target=self.__monitor, args=())
57
+ t.start()
58
+
59
+ def kill(self):
60
+ """
61
+ Kill method. Thread will die after calling this
62
+ :return: None
63
+ """
64
+ self.running = False
65
+
66
+ def __monitor(self):
67
+ """
68
+ Actual method that monitors the source file for changes
69
+ :return: None
70
+ """
71
+ while self.running:
72
+ ## Get last modification timestamp and compare to cached one
73
+ if os.path.isfile(self.source_file):
74
+ # <-- During initialization we change the working dir if the python file is not yet existent.
75
+ # This is a thread, so it runs in background during these folder changes and may throw a "fileNotFrounderror" if we are not yet back to the working dir
76
+ if os.name == "nt":
77
+ stamp = os.stat(str(self.source_file.replace("/", "\\"))).st_mtime
78
+ else:
79
+ stamp = os.stat(str(self.source_file)).st_mtime
80
+
81
+ ## Check if changed
82
+ if stamp > self._cached_stamp:
83
+
84
+ log("[INFO] Model Monitor for {}: Observed a change to the model. Calling the parser".format(
85
+ str(self.source_file)))
86
+ self._cached_stamp = stamp
87
+
88
+ # File has changed, so parse model again
89
+ # Store current directory and chdir to sd compiler dir
90
+ current_dir = str(os.getcwd())
91
+ os.chdir(config.configuration["sd_py_compiler_root"])
92
+
93
+ output = os.popen(self.execute_script).read()
94
+
95
+ # Go back to working dir
96
+ os.chdir(current_dir)
97
+
98
+ ## Check if everything went well, i.e. exit status of the script = 0
99
+ if "error" in str(output).lower():
100
+ log("[ERROR] Tried to convert {} but to {} but got error: {}".format(str(self.source_file), str(
101
+ self.dest) + ".py", str(output)))
102
+ self.running = False
103
+ return None
104
+
105
+ ## Refresh all scenarios with the given model file
106
+ self.update_func(self.source_file)
107
+ log("[INFO] Model Monitor for {}: model updated and relaoded scenarios!".format(
108
+ str(self.source_file)))
109
+
110
+ # Store new timestamp as cached timestamp
111
+ self._cached_stamp = stamp
112
+ time.sleep(1)
113
+
114
+ log("[INFO] Model Monitor for {}: I got killed... Goodbye!".format(str(self.source_file)))
File without changes
@@ -0,0 +1,114 @@
1
+ # /`-
2
+ # _ _ _ /####`-
3
+ # | | | | (_) /########`-
4
+ # | |_ _ __ __ _ _ __ ___ ___ _ __ | |_ _ ___ /###########`-
5
+ # | __| '__/ _` | '_ \/ __|/ _ \ '_ \| __| / __| ____ -###########/
6
+ # | |_| | | (_| | | | \__ \ __/ | | | |_| \__ \ | | `-#######/
7
+ # \__|_| \__,_|_| |_|___/\___|_| |_|\__|_|___/ |____| `- # /
8
+ #
9
+ # Copyright (c) 2018 transentis labs GmbH
10
+ # MIT License
11
+
12
+ ### IMPORTS
13
+ from BPTK_Py.logger.logger import log
14
+ ###
15
+
16
+ ###############################
17
+ ## ClASS SIMULATION_SCENARIO ##
18
+ ###############################
19
+
20
+
21
+ class simulationScenario():
22
+ """
23
+ This class stores the settings for each scenario
24
+ """
25
+
26
+ def __init__(self, dictionary, name, model, group):
27
+ """
28
+ :param dictionary: scenario dictionary from the source JSON file
29
+ :param name: name of the scenario
30
+ :param model: simulation_model object
31
+ :param group: name of scenario manager
32
+ """
33
+
34
+ self.dictionary = dictionary
35
+ self.group = group
36
+ self.model = model
37
+
38
+ if "constants" in dictionary.keys():
39
+ # Overwrite base constants (if any)
40
+ self.constants = dictionary["constants"]
41
+ else:
42
+ self.constants = {}
43
+
44
+ if "strategy" in dictionary.keys():
45
+ self.strategy = dictionary["strategy"]
46
+ else:
47
+ self.strategy = {}
48
+
49
+ if "points" in dictionary.keys():
50
+ self.points = dictionary["points"]
51
+ else:
52
+ self.points = {}
53
+
54
+ self.name = name
55
+
56
+ self.result = None # When we finish a simulation, we will write the resulting dataframe in here. For now, it is an empty object. Just to reserve the pointer
57
+
58
+ def setup_constants(self):
59
+ """
60
+ Sets up the constants of the simulation model upon scenario manager initialization
61
+ :return: None
62
+ """
63
+
64
+ if self.model is not None:
65
+
66
+ for constant, value in self.constants.items():
67
+ try:
68
+ if type(value) == str:
69
+ self.model.equations[constant] = eval("lambda t : " + value)
70
+ log("[INFO] {}, {}: Changed constant {} to {}".format(self.group, self.name, constant,
71
+ str(value)))
72
+ elif type(value) == int or type(value) == float:
73
+ self.model.equations[constant] = eval("lambda t: " + str(value))
74
+ log("[INFO] {}, {}: Changed constant {} to {}".format(self.group, self.name, constant,
75
+ str(value)))
76
+ else:
77
+ log("[ERROR] Invalid type for constant {}: {}".format(constant, str(value)))
78
+
79
+ except ValueError as e:
80
+ log("[ERROR] Attempted to evaluate an expression that I cannot evaluate. Error message: {}".format(
81
+ str(e)))
82
+
83
+ else:
84
+ log(
85
+ "[ERROR] Attempted to initialize constants of a model before the model is available for Scenario {}".format(
86
+ self.name))
87
+
88
+ def setup_points(self):
89
+ """
90
+ Sets up the points of the simulation model upon scenario manager initialization
91
+ :return: None
92
+ """
93
+
94
+ if self.model is not None:
95
+
96
+ for name, value in self.points.items():
97
+ try:
98
+ if type(value) == str:
99
+ self.model.points[name] = eval(value)
100
+ log("[INFO] {}, {}: Changed points {} to {}".format(self.group, self.name, name, str(value)))
101
+ elif type(value) == list:
102
+ self.model.points[name] = value
103
+ log("[INFO] {}, {}: Changed points {} to {}".format(self.group, self.name, name, str(value)))
104
+ else:
105
+ log("[ERROR] Invalid type for points {}: {}".format(name, str(value)))
106
+
107
+ except ValueError as e:
108
+ log("[ERROR] Attempted to evaluate an expression that I cannot evaluate. Error message: {}".format(
109
+ str(e)))
110
+
111
+ else:
112
+ log(
113
+ "[ERROR] Attempted to initialize points of a model before the model is available for Scenario {}".format(
114
+ self.name))