-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulation.py
616 lines (503 loc) · 17.8 KB
/
simulation.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
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014 Bryant E. McDonnell
#
# Licensed under the terms of the BSD2 License
# See LICENSE.txt for details
# -----------------------------------------------------------------------------
"""Base class for a SWMM Simulation."""
# Local imports
from pyswmm.swmm5 import PySWMM, PYSWMMException
from pyswmm.toolkitapi import SimulationTime, SimulationUnits
class Simulation(object):
"""
Base class for a SWMM Simulation.
The model object provides several options to run a simulation.
User can specified SWMM library path. Uses default lib if not provided.
Initialize the Simulation class.
:param str inpfile: Name of SWMM input file (default '')
:param str rptfile: Report file to generate (default None)
:param str binfile: Optional binary output file (default None)
:param str swmm_lib_path: User-specified SWMM library path (default None).
Examples:
Intialize a simulation and iterate through a simulation. This
approach requires some clean up.
>>> from pyswmm import Simulation
>>>
>>> sim = Simulation('tests/data/TestModel1_weirSetting.inp')
>>> for step in sim:
... pass
>>>
>>> sim.report()
>>> sim.close()
Intialize using with statement. This automatically cleans up
after a simulation
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... for step in sim:
... pass
... sim.report()
Initialize the simulation and execute. This style does not allow
the user to interact with the simulation. However, this approach
tends to be the fastest.
>>> from pyswmm import Simulation
>>>
>>> sim = Simulation('tests/data/TestModel1_weirSetting.inp')
>>> sim.execute()
"""
def __init__(self,
inputfile,
reportfile=None,
outputfile=None,
swmm_lib_path=None):
self._model = PySWMM(inputfile, reportfile, outputfile, swmm_lib_path)
self._model.swmm_open()
self._isOpen = True
self._advance_seconds = None
self._isStarted = False
self._callbacks = {
"before_start": None,
"before_step": None,
"after_step": None,
"before_end": None,
"after_end": None,
"after_close": None
}
def __enter__(self):
"""
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... for step in sim:
... print(sim.current_time)
... sim.report()
>>>
>>> 2015-11-01 14:00:30
>>> 2015-11-01 14:01:00
>>> 2015-11-01 14:01:30
>>> 2015-11-01 14:02:00
"""
return self
def __iter__(self):
"""Iterator over Simulation"""
return self
def start(self):
"""Start Simulation"""
if not self._isStarted:
# Set Model Initial Conditions
# (This Will be Deprecated with Time)
if hasattr(self, "_initial_conditions"):
self._initial_conditions()
# Execute Callback Hooks Before Simulation
self._execute_callback(self.before_start())
self._model.swmm_start(True)
self._isStarted = True
def __next__(self):
"""Next"""
# Start Simulation
self.start()
# Execute Callback Hooks Before Simulation Step
self._execute_callback(self.before_step())
# Simulation Step Amount
if self._advance_seconds is None:
time = self._model.swmm_step()
else:
time = self._model.swmm_stride(self._advance_seconds)
# Execute Callback Hooks After Simulation Step
self._execute_callback(self.after_step())
if time <= 0.0:
self._execute_callback(self.before_end())
raise StopIteration
return self._model
next = __next__ # Python 2
def __exit__(self, *a):
"""close"""
if self._isStarted:
self._model.swmm_end()
self._isStarted = False
# Execute Callback Hooks After Simulation End
self._execute_callback(self.after_end())
if self._isOpen:
self._model.swmm_close()
self._isOpen = False
# Execute Callback Hooks After Simulation Closes
self._execute_callback(self.after_close())
@staticmethod
def _is_callback(callable_object):
"""Checks if arugment is a function/method."""
if not callable(callable_object):
error_msg = 'Requires Callable Object, not {}'.format(
type(callable_object))
raise (PYSWMMException(error_msg))
else:
return True
def _execute_callback(self, callback):
"""Runs the callback."""
if callback:
try:
callback()
except PYSWMMException:
error_msg = "Callback Failed"
raise PYSWMMException((error_msg))
def initial_conditions(self, init_conditions):
"""
Intial Conditions for Hydraulics and Hydrology can be set
from within the api by setting a function to the
initial_conditions property.
>>> from pyswmm import Simulation
>>>
>>> with Simulation('./TestModel1_weirSetting.inp') as sim:
... nodeJ1 = Nodes(sim)["J1"]
...
... def init_conditions():
... nodeJ1.initial_depth = 4
...
... sim.initial_conditions(init_conditions)
...
... for step in sim:
... pass
... sim.report()
"""
if self._is_callback(init_conditions):
self._initial_conditions = init_conditions
def before_start(self):
"""Get Before Start Callback.
:return: Callbacks
"""
return self._callbacks["before_start"]
def add_before_start(self, callback):
"""
Add callback function/method/object to execute before
the simlation starts. Needs to be callable.
:param func callback: Callable Object
>>> from pyswmm import Simulation
>>>
>>> def test_callback():
... print("CALLBACK - Executed")
>>>
>>> with Simulation('./TestModel1_weirSetting.inp') as sim:
...
... sim.before_start(test_callback) #<- pass function handle.
... print("Waiting to Start")
... for ind, step in enumerate(sim):
... print("Step {}".format(ind))
... print("Complete!")
... print("Closed")
>>>
>>> "Waiting to Start"
>>> "CALLBACK - Executed"
>>> "Step 0"
>>> "Step 1"
>>> ...
>>> "Complete!"
>>> "Closed"
"""
if self._is_callback(callback):
self._callbacks["before_start"] = callback
def before_step(self):
"""Get Before Step Callback.
:return: Callbacks
"""
return self._callbacks["before_step"]
def add_before_step(self, callback):
"""
Add callback function/method/object to execute before
a simlation step. Needs to be callable.
:param func callback: Callable Object
(See self.add_before_start() for more details)
"""
if self._is_callback(callback):
self._callbacks["before_step"] = callback
def after_step(self):
"""Get After Step Callback.
:return: Callbacks
"""
return self._callbacks["after_step"]
def add_after_step(self, callback):
"""
Add callback function/method/object to execute after
a simlation step. Needs to be callable.
:param func callback: Callable Object
(See self.add_before_start() for more details)
"""
if self._is_callback(callback):
self._callbacks["after_step"] = callback
def before_end(self):
"""Get Before End Callback.
:return: Callbacks
"""
return self._callbacks["before_end"]
def add_before_end(self, callback):
"""
Add callback function/method/object to execute after
the simulation ends. Needs to be callable.
:param func callback: Callable Object
(See self.add_before_start() for more details)
"""
if self._is_callback(callback):
self._callbacks["before_end"] = callback
def after_end(self):
"""Get After End Callback.
:return: Callbacks
"""
return self._callbacks["after_end"]
def add_after_end(self, callback):
"""
Add callback function/method/object to execute after
the simulation ends. Needs to be callable.
:param func callback: Callable Object
(See self.add_before_start() for more details)
"""
if self._is_callback(callback):
self._callbacks["after_end"] = callback
def after_close(self):
"""Get After Close Callback.
:return: Callbacks
"""
return self._callbacks["after_close"]
def add_after_close(self, callback):
"""
Add callback function/method/object to execute after
the simulation is closed. Needs to be callable.
:param func callback: Callable Object
(See self.add_before_start() for more details)
"""
if self._is_callback(callback):
self._callbacks["after_close"] = callback
def step_advance(self, advance_seconds):
"""
Advances the model by X number of seconds instead of
intervening at every routing step. This does not change
the routing step for the simulation; only lets python take
back control after each advance period.
:param int advance_seconds: Seconds to Advance simulation
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... sim.step_advance(300)
... for step in sim:
... print(step.current_time)
... # or here! sim.step_advance(newvalue)
... sim.report()
>>>
>>> 2015-11-01 14:00:30
>>> 2015-11-01 14:01:00
>>> 2015-11-01 14:01:30
>>> 2015-11-01 14:02:00
"""
self._advance_seconds = advance_seconds
def report(self):
"""
Writes to report file after simulation.
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... for step in sim:
... pass
... sim.report()
"""
self._model.swmm_report()
def close(self):
"""
Intialize a simulation and iterate through a simulation. This
approach requires some clean up.
Examples:
>>> from pyswmm import Simulation
>>>
>>> sim = Simulation('./TestModel1_weirSetting.inp')
>>> for step in sim:
... pass
>>>
>>> sim.report()
>>> sim.close()
"""
self.__exit__()
def execute(self):
"""
Open an input file, run SWMM, then close the file.
Examples:
>>> sim = PYSWMM(r'\\test.inp')
>>> sim.execute()
"""
self._model.swmmExec()
@property
def engine_version(self):
"""
Retrieves the SWMM Engine Version.
:return: Engine Version
:rtype: StrictVersion
Examples:
>>> sim = PYSWMM(r'\\test.inp')
>>> sim.engine_version
StrictVersion("5.1.13")
"""
return self._model.swmm_getVersion()
@property
def runoff_error(self):
"""
Retrieves the Runoff Mass Balance Error.
:return: Runoff Mass Balance Error
:rtype: float
Examples:
>>> sim = PYSWMM(r'\\test.inp')
>>> sim.execute()
>>> sim.runoff_error
0.01
"""
return self._model.swmm_getMassBalErr()[0]
@property
def flow_routing_error(self):
"""
Retrieves the Flow Routing Mass Balance Error.
:return: Flow Routing Mass Balance Error
:rtype: float
Examples:
>>> sim = PYSWMM(r'\\test.inp')
>>> sim.execute()
>>> sim.flow_routing_error
0.01
"""
return self._model.swmm_getMassBalErr()[1]
@property
def quality_error(self):
"""
Retrieves the Quality Routing Mass Balance Error.
:return: Quality Routing Mass Balance Error
:rtype: float
Examples:
>>> sim = PYSWMM(r'\\test.inp')
>>> sim.execute()
>>> sim.quality_error
0.01
"""
return self._model.swmm_getMassBalErr()[2]
@property
def start_time(self):
"""Get/set Simulation start time.
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... print sim.start_time
... sim.start_time = datetime(2015,5,10,15,15,1)
>>>
>>> datetime.datetime(2015,5,10,15,15,1)
"""
return self._model.getSimulationDateTime(
SimulationTime.StartDateTime.value)
@start_time.setter
def start_time(self, dtimeval):
"""Set simulation Start time"""
self._model.setSimulationDateTime(SimulationTime.StartDateTime.value,
dtimeval)
@property
def end_time(self):
"""Get/set Simulation end time.
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... print sim.end_time
... sim.end_time = datetime(2016,5,10,15,15,1)
>>>
>>> datetime.datetime(2016,5,10,15,15,1)
"""
return self._model.getSimulationDateTime(
SimulationTime.EndDateTime.value)
@end_time.setter
def end_time(self, dtimeval):
"""Set simulation End time."""
self._model.setSimulationDateTime(SimulationTime.EndDateTime.value,
dtimeval)
@property
def report_start(self):
"""Get/set Simulation report start time.
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... print sim.report_start
... sim.report_start = datetime(2015,5,10,15,15,1)
>>>
>>> datetime.datetime(2015,5,10,15,15,1)
"""
return self._model.getSimulationDateTime(
SimulationTime.ReportStart.value)
@report_start.setter
def report_start(self, dtimeval):
"""Set simulation report start time."""
self._model.setSimulationDateTime(SimulationTime.ReportStart.value,
dtimeval)
@property
def flow_units(self):
"""
Get Simulation Units (CFS, GPM, MGD, CMS, LPS, MLD).
:return: Flow Unit
:rtype: str
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... print sim.flow_units
>>>
>>> CFS
"""
return self._model.getSimUnit(SimulationUnits.FlowUnits.value)
@property
def system_units(self):
"""Get system units (US, SI).
:return: System Unit
:rtype: str
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... print sim.system_units
>>>
>>> US
"""
return self._model.getSimUnit(SimulationUnits.UnitSystem.value)
@property
def current_time(self):
"""Get Simulation Current Time.
:return: Current Simulation Time
:rtype: Datetime
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... for step in sim:
... print(sim.current_time)
... sim.report()
>>>
>>> 2015-11-01 14:00:30
>>> 2015-11-01 14:01:00
>>> 2015-11-01 14:01:30
>>> 2015-11-01 14:02:00
"""
return self._model.getCurrentSimulationTime()
@property
def percent_complete(self):
"""Get Simulation Percent Complete.
:return: Current Percent Complete
:rtype: Datetime
Examples:
>>> from pyswmm import Simulation
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... for step in sim:
... print(sim.percent_complete)
... sim.report()
>>>
>>> 0.01
>>> 0.25
>>> 0.50
>>> 0.75
"""
dt = self.current_time - self.start_time
total_time = self.end_time - self.start_time
return float(dt.total_seconds()) / total_time.total_seconds()