-
Notifications
You must be signed in to change notification settings - Fork 0
/
Simulator.py
executable file
·368 lines (285 loc) · 11.9 KB
/
Simulator.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
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 04 17:22:50 2014
@author: bni
The Simulator class provides a framework to perform simulation experiments on a
Dynamic Probabilistic Material Flow Model.
"""
import numpy as np
import numpy.linalg as la
import components as cp
import math
import pdb
class Simulator(object):
""" The simulator provides a framework to perform simulaton experiments on
pmfa models.
Parameters:
-------------
runs: integer
the number of simulation runs (the sample size) over which the model \
is evaluated.
periods: integer
the number of periods (e.g. years) over which the system is investigated
seed: integer
The seed value for all probability distributions.
useGlobalTCSettings: boolean
defines, if the settings for the normalization of the outgoing TCs \
from Compartments or Stocks are used that are made in the model \
definition (False) or the global settings defined in the simulator (True)
normalizeTCs: boolean
defines, if outgoing TCs from Model Compartments and Stocks are adjusted to sum\
up to one. This Parameter is only considered, if the global parameter\
for normalization is used.
"""
# ToDo: Model im Konstruktor übergeben?
def __init__(self, runs, periods, seed = None, useGlobalTCSettings = True,
normalizeTCs = True):
self.numRuns = runs
self.numPeriods = periods
self.useGlobalTCSettings = useGlobalTCSettings
self.normalizeTCs = normalizeTCs
if seed is None:
self.seed = np.random.randint(1, 10000)
else:
self.seed = seed
self.flowCompartments = []
self.sinks = []
self.stocks = []
self.checkInflows =None
self.current_period = 0
def setModel(self, model):
self.model = model
self.compartments = model.compartments
self.inflows = model.inflows
self.model.setSeed(self.seed)
self.model.updateCompartmentCategories()
for i in range(len(self.compartments)):
self.compartments[i].compNumber = i
for comp in self.compartments:
# comp.setSimulator(self)
comp.initFlowLog(self.numRuns, self.numPeriods)
if isinstance(comp, cp.FlowCompartment):
self.flowCompartments.append(comp)
if isinstance(comp, cp.Sink):
self.sinks.append(comp)
comp.initInventory(self.numRuns, self.numPeriods)
if type(comp) is cp.Stock:
self.stocks.append(comp)
comp.updateImmediateReleaseRate()
def runSimulation(self):
""" performs the simulation on the model with regard to the given
parameters
"""
print('')
print('Start Simulation')
print('Model: '+ str(self.model.name))
print('Seed Value: '+str(self.model.seed))
print('Number of Simulation Runs: '+str(self.numRuns))
print('Number of Periods: '+str(self.numPeriods))
print('Progress (in percent):')
currentStep = 1
stepSize = math.ceil(self.numRuns/100)
currentStepRun = math.ceil(stepSize)
for run in range(self.numRuns):
for comp in self.flowCompartments:
comp.determineTCs(self.useGlobalTCSettings, self.normalizeTCs)
for infl in self.inflows:
infl.sampleValues()
for stock in self.stocks:
stock.determineTCs(self.useGlobalTCSettings, self.normalizeTCs)
# stock.localRelease.sampleDelay()
allInflows = np.zeros((len(self.compartments), self.numPeriods))
for period in range (self.numPeriods):
# self.current_period = period
''' update current period for time dependent transfers of a compartment'''
for compartment in self.flowCompartments:
compartment.updateTCs(period)
for sink in self.sinks:
sink.updateInventory(run, period)
for inflow in self.inflows:
allInflows[self.compartments.index(inflow.target), period]= \
allInflows[self.compartments.index(inflow.target), period] + inflow.getCurrentInflow(period)
for stock in self.stocks:
localReleases = stock.releaseMaterial(run, period)
for locRel in localReleases.keys():
allInflows [locRel.compNumber, period]= allInflows[locRel.compNumber, period] + localReleases [locRel]
inflowVector = allInflows[:,period]
flowMatrix = np.zeros(shape=(len(self.compartments), len(self.compartments)))
np.fill_diagonal(flowMatrix,1)
for compartment in self.flowCompartments:
for trans in compartment.transfers:
# print compartment.name
# print trans.getCurrentTC()
# print compartment.immediateReleaseRate
# print trans.target.compNumber
# print compartment.compNumber
# if comp.name == 'Sorting_Disposal':
# pdb.set_trace()
flowMatrix[trans.target.compNumber, compartment.compNumber]= -trans.getCurrentTC()*compartment.immediateReleaseRate
solutionVector = la.solve(flowMatrix, inflowVector)
for i in self.compartments:
i.logFlow(run, period, solutionVector[i.compNumber])
for i in self.sinks:
i.storeMaterial(run, period, solutionVector[i.compNumber])
if run == currentStepRun:
print (str(currentStep)+', ')
currentStepRun += stepSize
currentStep +=1
# print ''
print('Simulation complete')
print('')
def getAllStockedMaterial(self):
'''
returns a dictionary of all sinks and stocks and the matrices of the
logged stored material
'''
inventories = {}
for sink in self.sinks:
inventories[sink.name]= sink.inventory
return inventories
def getLoggedInflows(self):
'''
returns a dictionary of all compartments and logged inflow matrices
'''
inflows = {}
for comp in self.compartments:
if comp.logInflows:
inflows[comp.name]= comp.inflowRecord
return inflows
def getLoggedTotalOutflows(self):
'''
gives absolulte outflows from each compartments (if logged)
'''
outflows = {}
for comp in self.flowCompartments:
if comp.logOutflows:
outflowSum = []
for outflow in comp.outflowRecord:
outflowSum.append(comp.outflowRecord[outflow])
outflows[comp.name]=sum(outflowSum)
return outflows
def getLoggedFlows(self):
'''
returns matrices for all flows in between compartments (dictionary of dictionaries)
'''
allFlows = {}
for comp in self.flowCompartments:
if comp.logOutflows:
allFlows[comp.name]= comp.outflowRecord
return allFlows
def getImmediateFlowsFromAllStocks(self):
'''
returns all immediate flows from stocks
'''
immediateStocks = [stock for stock in self.stocks if stock.logImmediateFlows]
allFlows = {}
for stock in immediateStocks:
allFlows[stock]=stock.immediateFlowRecord
return allFlows
def getLoggedCategoryStock(self, category):
'''
return the summed up inventory for all sinks and stocks of a category
'''
catStocks = [c for c in self.sinks if category in c.categories]
combinedInventory = []
for stock in catStocks:
combinedInventory.append(stock.inventory)
return sum(combinedInventory)
def getLoggedCategoryInflows(self, category):
'''
returns the summed up inflow to the compartments of a category
'''
catCompartments = [comp for comp in self.compartments if category in comp.categories and comp.logInflows]
loggedInflows = []
for catComp in catCompartments:
loggedInflows.append(catComp.inflowRecord)
return sum(loggedInflows)
def getLoggedCategoryOutflowSum(self, category):
'''
returns a matrix of the sums of the outflows from all the compartments of the category to all
subsequet compartments
'''
catFlows = [c for c in self.flowCompartments if category in c.categories and c.logOutflows]
allOutflows = []
for catFlow in catFlows:
for name in catFlow.outflowRecord:
allOutflows.append(catFlow.outflowRecord[name])
return sum(allOutflows)
def getLoggedCategoryOutflows(self, category):
'''
returns the outflows of all comparmtents of a category to all subsequent compartments
'''
catFlows = [c for c in self.flowCompartments if category in c.categories and c.logOutflows]
allFlows = {}
for flow in catFlows:
for name in flow.outflowRecord:
if name in allFlows:
allFlows[name] = allFlows[name]+flow.outflowRecord[name]
else:
allFlows[name]= flow.outflowRecord[name]
return allFlows
def getCategoryImmediateFlowFromStockSum(self, category):
'''
returns a matrix of the sum of all immediate outflows from stocks of a category
'''
immediateStocks = [stock for stock in self.stocks if stock.logImmediateFlows and category in stock.categories]
totalImmediateFlow = []
for stock in immediateStocks:
for rec in stock.immediateFlowRecord:
totalImmediateFlow.append(stock.immediateFlowRecord[rec])
return sum(totalImmediateFlow)
def getCompartmentsOfCategory(self, category):
'''
returns all compartments of one category
'''
return [c for c in self.compartments if category in c.categories]
def getCombinedOutflows(self, compartmentList):
"""
returns a combined dictonary of the outflows of a list of compartments
"""
combinedOutflow= {}
for comp in compartmentList:
for name in comp.outflowRecord: # outflowRecord is a dictionary containing a list(outputflows) of keys with value in matrix
if name in combinedOutflow:
combinedOutflow[name] = combinedOutflow[name]+comp.outflowRecord[name]
else:
combinedOutflow[name]= comp.outflowRecord[name]
return combinedOutflow
def getCurrentPeriod(self):
return self.current_period
def getSinks(self):
"""
returns all Sinks of the model.
"""
return self.sinks
def getStocks(self):
"""
returns all Stocks of the model
"""
return self.stocks
def getCompartments(self):
"""
returns a list of all compartments, flow compartments, sinks and stocks
"""
return self.compartments
def getFlowCompartments(self):
"""
returns a list of all flow compartments
"""
return self.flowCompartments
def getLoggedOutflows(self):
"""
returns a list of all flowCompartments that log outflows
"""
loggedOutflows = [comp for comp in self.flowCompartments if comp.logOutflows]
return loggedOutflows
def getCategories(self):
'''
category list of the model
'''
return self.model.categoriesList
def getCompartment(self, name):
'''
return a specific compartment for the given name
'''
return next((comp for comp in self.compartments if comp.name ==name), None)