-
Notifications
You must be signed in to change notification settings - Fork 0
/
components.py
executable file
·912 lines (700 loc) · 30.7 KB
/
components.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
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 12 14:56:22 2014
@author: bni
The components module contains model elements that are necessary to implement a
Probabilistic Material Flow Model. To represent the system, the model elements
need to be parametrized to fit the specific system behavior.
"""
import numpy as np
import pdb
import functools
class Compartment(object):
""" A compartment is a distinct area of the investigated system.
Depending on the scientific question to be aswered with the model a
compartment can be an environmental media, a geographic region or a logical
partition in the fate of a material.
To use a Compartment, please instantiate its subclasses FlowComp, Sink, and
Stock.
"""
def __init__(self, name, logInflows, categories):
self.compNumber = 'not defined'
self.name = name
self.logInflows = logInflows
self.categories = categories
"""
inits a matrix to log the material inflows for all simulation runs and
periods
"""
def initFlowLog(self, runs, periods):
"""
if flow record is set, a matrix is initialized to log all flows to the
compartment
"""
if self.logInflows:
self.inflowRecord = np.zeros((runs, periods))
def logFlow(self, run, period, amt):
"""
logs the inflow to the compartment
"""
if self.logInflows:
self.inflowRecord[run, period]= amt
# def setSimulator(self, simulator):
# self.simulator = simulator
class FlowCompartment(Compartment):
""" A FlowComp represents a system Compartment without residence time of
observed material. The further transfer of material to subsequent
compartments is defined using Transfer objects.
Parameters:
----------------
name: string
compartment name
transfers: list<components.compartment>
all outgoing transfers from the Flow Compartment
logInflows: Boolean
defines if incoming flows are logged for later evaluation
logOutflows: Boolean
defines if outgoing flows are logged for later evaluation
categories: list
defined a list of categories the stock is part of (for later evaluation)
"""
def __init__(self, name, transfers= [], logInflows = False, logOutflows = False, adjustOutgoingTCs = True, categories = []):
super(FlowCompartment, self).__init__(name, logInflows, categories)
self.transfers = transfers
self.adjustOutTCs = adjustOutgoingTCs
self.logOutflows = logOutflows
self.immediateReleaseRate = 1
def updateTCs(self, period):
""" used to set current period TCs for time dependent transfers
"""
for t in self.transfers:
t.updateTC(period)
""" TODO: set flag TRUE/FALSE for TC normalize"""
self.adjustTCs()
def determineTCs(self, useGlobalTCsettings, globalSettingsAdjust):
"""
Samples transfer from the underlying probability distribution, may \
adjust to a sum of one over all outgoing transfers.
"""
for t in self.transfers:
t.sampleTC()
if (not useGlobalTCsettings) & self.adjustOutTCs:
self.adjustTCs()
elif useGlobalTCsettings & globalSettingsAdjust:
self.adjustTCs()
def initFlowLog(self, runs, periods):
"""
if flow record is set, a matrix is initialized to log all flows to the
compartment
if outFlows are logged a dictionary is initialized to log the outflows
"""
if self.logInflows:
self.inflowRecord = np.zeros((runs, periods))
if self.logOutflows:
self.outflowRecord = {}
for t in self.transfers:
self.outflowRecord[t.target.name] = np.zeros((runs, periods))
def initInventory(self, runs, periods):
self.inventory = np.zeros((runs, periods))
self.releaseList = np.zeros((runs, periods))
self.localRelease.releaseList = np.zeros((runs, periods))
def logFlow(self, run, period, amt):
"""
logs the inflow to the compartment
"""
if self.logInflows:
self.inflowRecord[run, period]= amt
if self.logOutflows:
for t in self.transfers:
self.outflowRecord[t.target.name][run, period] = t.getCurrentTC()*amt
def adjustTCs(self):
""" Adjusts TCs outgoing from one compartment to sum up to one.
Applies adjustment factor on TCs with the lowest priority first. \
If that is insufficient (negativ TCs are not allowed), adjustment of \
the TC with next higher priority and so on...
"""
# if self.name == 'WEEE':
# pdb.set_trace()
tcSum = sum(t.currentTC for t in self.transfers)
currentPriority = min(t.priority for t in self.transfers)
while np.round(tcSum,6)!=1:
adjustableTransfers = [t for t in self.transfers if t.priority == currentPriority]
adjustableTCs = [t.currentTC for t in adjustableTransfers]
# added by Sana because of 'ZeroDivisionError: float division by zero'
# if self.name == 'WEEE':
# pdb.set_trace()
currentAdjustSum = sum(adjustableTCs)
normToValue = max(currentAdjustSum - (tcSum - 1), 0)
changedTCs = self.__normListSumTo(adjustableTCs, normToValue)
for i in range(len(changedTCs)):
adjustableTransfers[i].currentTC = changedTCs[i]
tcSum = sum(t.currentTC for t in self.transfers)
tcSum = np.round(tcSum, 6)
currentPriority = currentPriority + 1
def __normListSumTo(self, L, sumTo=1):
'''normalize values of a list to a certain value'''
# if sum(L) ==0:
# L = [ 1 for l in L]
if L == []:
pdb.set_trace()
pass
pdb.set_trace()
sum = functools.reduce(lambda x,y:x+y, L)
if sum == 0:
return [0 for x in L]
# if sum=0:
# return [x=0 for x in L]
return [ x/(sum*1.0)*sumTo for x in L]
## added by Sana because of 'ZeroDivisionError: float division by zero'
# if L == [0]:
## pdb.set_trace()
# return [0 for x in L]
#
# elif L == []:
## pdb.set_trace()
# return [0 for x in L]
#
# else:
# sum = reduce(lambda x,y:x+y, L)
# return [ x/(sum*1.0)*sumTo for x in L]
class Sink(Compartment):
""" A model compartment where inflowing material accumulates
Parameters:
----------------
name: string
compartment name
logInflows: Boolean
defines if incoming flows are logged for later evaluation
categories: list
defined a list of categories the stock is part of (for later evaluation)
"""
def __init__(self, name, logInflows = False, categories = []):
super(Sink, self).__init__(name, logInflows, categories)
def initInventory(self, runs, periods):
self.inventory = np.zeros((runs, periods))
def updateInventory(self, run, period):
""" transfers the stored amount from the end of a period to the
beginning of the next one.
"""
if (period != 0):
self.inventory[run, period] = self.inventory[run, period -1]
def storeMaterial(self, run, period, amount):
""" increases the stored amount by an accumulated inflow"""
self.inventory[run, period] = self.inventory[run, period] + amount
class Stock(FlowCompartment, Sink):
""" A Stock is a Sink that releases a part of the stored material in later
periods.
Parameters:
----------------
name: string
compartment name
transfers: list<components.Transfer>
transfers of the material released from stock to other compartments
localRelease: components.LocalRelease
definition which proportions of the amount of material stored in a \
period are released in which of the subsequent periods
logInflows: Boolean
defines if incoming flows are logged for later evaluation
logOutflows: Boolean
defines if outgoing flows are logged for later evaluation
categories: list
defined a list of categories the stock is part of (for later evaluation)
"""
def __init__(self, name, transfers=[], localRelease = 0, logInflows = False, logOutflows = False, logImmediateFlows = False, categories = []):
super(Stock, self).__init__(name, transfers, logInflows, categories)
self.localRelease = localRelease
self.logOutflows = logOutflows
self.logImmediateFlows = logImmediateFlows
self.immediateReleaseRate = 1
self.categories = categories
def initInventory(self, runs, periods):
self.inventory = np.zeros((runs, periods))
self.releaseList = np.zeros((runs, periods))
self.localRelease.releaseList = np.zeros((runs, periods))
if self.logImmediateFlows:
self.immediateFlowRecord = {}
for t in self.transfers:
self.immediateFlowRecord[t.target.name] = np.zeros((runs, periods))
def updateImmediateReleaseRate(self):
self.immediateReleaseRate = self.localRelease.getImmediateReleaseRate()
def logFlow(self, run, period, amt):
"""
logs the inflow to the compartment
"""
if self.logInflows:
self.inflowRecord[run, period]= amt
if self.logOutflows:
for t in self.transfers:
self.outflowRecord[t.target.name][run, period] = \
self.outflowRecord[t.target.name][run, period] + t.getCurrentTC()*amt * self.immediateReleaseRate
if self.logImmediateFlows:
for t in self.transfers:
self.immediateFlowRecord[t.target.name][run, period] = t.getCurrentTC()*amt * self.immediateReleaseRate
def storeMaterial(self, run, period, amount):
""" stores material and schedules future release according to the
release strategy of the stock
"""
self.inventory[run, period] = self.inventory[run, period] + amount*(1-self.immediateReleaseRate)
self.localRelease.scheduleFutureRelease(run, period, amount)
def releaseMaterial(self, run, period):
""" takes the release scheduled for the current period distributes it
to the different target Compartments
------------
returns: Dict {Compartment: amt}
"""
releaseAmt = self.localRelease.releaseList[run, period]
self.inventory[run, period] = self.inventory[run, period] - releaseAmt
releases = {}
for trans in self.transfers:
releases[trans.target]=trans.getCurrentTC()*releaseAmt
if self.logOutflows:
self.outflowRecord[trans.target.name][run, period] = releases[trans.target]
return releases
class LocalRelease(object):
""" Describes after what period how much of the material stored is released
from stock. To use, implement subclasses.
"""
def __init__(self):
self.releaseList = 0
def getImmediateReleaseRate(self):
return self.releaseRatesList[0]
def scheduleFutureRelease(self, currentRun, currentPeriod, storedAmt):
remainder = 1- self.releaseRatesList[0]
per = currentPeriod + 1
i = 1
while per < len(self.releaseList[currentRun]) and i < len(self.releaseRatesList):
self.releaseList[currentRun, per] = \
self.releaseList[currentRun, per] + storedAmt*min(self.releaseRatesList[i], remainder)
remainder = remainder - min(self.releaseRatesList[i], remainder)
i+=1
per+=1
# anpassen!!!!
class FixedRateRelease(LocalRelease):
""" A material release plan with constant rate after a delay period. \
Values are rounded to full periods.
Parameters:
----------------
releaseRate: float
periodic release rate
delay: Integer
delay time in periods, befor the release starts.
"""
def __init__(self, releaseRate = 1, delay = 0):
super(FixedRateRelease, self).__init__()
self.releaseRatesList = []
remainder = 1
while (remainder > 0):
if releaseRate < remainder:
self.releaseRatesList.append(releaseRate)
else:
self.releaseRatesList.append(remainder)
remainder = remainder - releaseRate
delayArray = np.zeros(delay)
self.releaseRatesList = np.concatenate((delayArray, self.releaseRatesList))
class ListRelease(LocalRelease):
""" A material release plan with a defined list of partial release rates
after a delay period
Parameters:
----------------
releaseRatesList: list<float>
list of release rates of a stored material in future periods.
delay: Integer
delay time in periods, befor the release starts.
"""
def __init__(self, releaseRatesList = [1], delay = 0):
super(ListRelease, self).__init__()
delayArray = np.zeros(delay)
self.releaseRatesList = np.concatenate((delayArray, releaseRatesList))
class FunctionRelease(LocalRelease):
""" A material release plan based on a distribution function that returns\
a release rate for every period. The time instant of the relese is\
relative to the time of material storage in the stock.
Parameters:
----------------
releaseFunction: function
function that return the relative release rate for a period
delay: Integer
delay time in periods, befor the release starts.
"""
def __init__(self, releaseFunction, delay = 0):
super(FunctionRelease, self).__init__()
self.releaseRatesList = []
self.totRelease = 0
self.currentPeriod = 0
self.lastNonZero = 0
delayArray = np.zeros(delay)
while self.totRelease < 1 and self.currentPeriod < 500: # MAX period if no total release
currentRelease = releaseFunction(self.currentPeriod)
self.releaseRatesList.append(currentRelease)
if currentRelease != 0:
self.lastNonZero = self.currentPeriod
self.totRelease += currentRelease
self.currentPeriod +=1
if self.currentPeriod-1 != self.lastNonZero:
self.releaseRatesList = self.releaseRatesList[:self.lastNonZero+1]
if self.totRelease > 1:
self.releaseRatesList[-1] += 1-self.totRelease
self.releaseList = np.concatenate((delayArray, self.releaseRatesList))
class Transfer(object):
""" A transfer object determines the relative rate of a total material flow
that is transfered from one Compartment to another. The priority denotes
the relative credibility of the assumed values and can be used for the
adjustment of contradictory dependent TCs.
To implement, use subclass.
"""
def __init__(self, target, priority):
self.target = target
self.priority = priority
self.currentTC = 0
def sampleTC(self):
print('To be implemented in Subclass')
def getCurrentTC(self):
return self.currentTC
''' To be overwritten by time dependent transfers'''
def updateTC(self, period):
pass
class ConstTransfer(Transfer):
""" A Transfer with a deterministic TC.
Parameters:
----------------
value: float
determinstic value for the transfer coefficient
target: components.Compartment
specifies the target compartment of the transfer
priority: integer
if the sum of the transfer coefficients from a compartment are normalized, \
a higher priority excludes the value from adjustment
"""
def __init__(self, value, target, priority=1):
super(ConstTransfer, self).__init__(target, priority)
self.value = value
self.currentTC = value
def sampleTC(self):
""" assign the constant value as current TC """
self.currentTC = self.value
"""def __repr__(self):
return "ConstTransfer: %s" % self.value"""
class StochasticTransfer(Transfer):
""" A Transfer Coefficient determined by an underlying probability \
distribution
Parameters:
----------------
function: probability density function
probability distribution function (e.g. from scipy.stats) to sample \
random values for the transfer coefficient
parameters: list<float>
parameter list of the probability distribution function
target: components.Compartment
specifies the target compartment of the transfer
priority: integer
if the sum of the transfer coefficients from a compartment are normalized, \
a higher priority excludes the value from adjustment
"""
def __init__(self, function, parameters, target, priority=1):
super(StochasticTransfer, self).__init__(target, priority)
self.function = function
self.parameters = parameters
def sampleTC(self):
""" samples a random value from the probability distribution as current
TC
"""
self.currentTC = self.function(*self.parameters)
############################### Time 'dependent' classes ########################
class TransferDistribution():
""" A Transfer Coefficient determined by an underlying probability \
distribution. Only to be used with TimeDependentDistributionTransfer
Parameters:
----------------
function: probability density function
probability distribution function (e.g. from scipy.stats) to sample \
random values for the transfer coefficient
parameters: list<float>
parameter list of the probability distribution function
"""
def __init__(self, function, parameters):
self.function = function
self.parameters = parameters
def sampleTC(self):
""" samples a random value from the probability distribution as current
TC
"""
return self.function(*self.parameters)
class TransferConstant():
""" A Transfer with a deterministic TC. To be used within
TimeDependentDistributionTransfer.
Parameters:
----------------
value: float
determinstic value for the transfer coefficient
"""
def __init__(self, value):
self.value = value
def sampleTC(self):
""" assign the constant value as current TC """
return self.value
class TimeDependendDistributionTransfer(Transfer):
""" A Transfer Coefficient determined by a given sample.
Parameters:
----------------
transfer_distribution_list: list<component.TransferDistributions>
list of TransferDistributions for each period
sample: list<float>
a given sample of values from which is randomly drawn
target: components.Compartment
specifies the target compartment of the transfer
priority: integer
if random values for the transfer coefficients are normalized, \
a higher priority excludes the value from adjustment
"""
def __init__(self, transfer_distribution_list, target, owning_comp, priority=1):
super(TimeDependendDistributionTransfer, self).__init__(target, priority)
self.transfer_distribution_list = transfer_distribution_list
self.transfer_list=[]
self.owning_comp = owning_comp
def sampleTC(self):
self.transfer_list=[]
# pdb.set_trace()
""" Randomly assigns one value from the sample as current TC"""
for d in self.transfer_distribution_list:
self.transfer_list.append(d.sampleTC()) # creates a list of sampeled values which will be attributed to each period
def updateTC(self, period):
# if period ==21:
# if self.target.name == 'NoSewageSystem':
# pdb.set_trace()
self.currentTC = self.transfer_list[period]
class TimeDependendListTransfer(Transfer):
""" A Transfer Coefficient determined by a given sample.
Parameters:
----------------
sample: list<float>
a given sample of values from which is randomly drawn
transfer_list: list<PeriodTransfer>
list of Single transfer elements for each period
target: components.Compartment
specifies the target compartment of the transfer
owning_comp: components.Compartment
specifies from which compartment the transfer comes from
priority: integer
if random values for the transfer coefficients are normalized, \
a higher priority excludes the value from adjustment
"""
def __init__(self, transfer_list, target, owning_comp, priority=1):
super(TimeDependendListTransfer, self).__init__(target, priority)
self.transfer_list = transfer_list
self.owning_comp = owning_comp
def sampleTC(self):
""" Randomly assigns one value from the sample as current TC"""
def updateTC(self, period):
self.currentTC = self.transfer_list[period]
################################################################################################3
class RandomChoiceTransfer(Transfer):
""" A Transfer Coefficient determined by a given sample.
Parameters:
----------------
sample: list<float>
a given sample of values from which is randomly drawn
target: components.Compartment
specifies the target compartment of the transfer
priority: integer
if random values for the transfer coefficients are normalized, \
a higher priority excludes the value from adjustment
"""
def __init__(self, sample, target, priority=1):
super(RandomChoiceTransfer, self).__init__(target, priority)
self.sample = sample
def sampleTC(self):
""" Randomly assigns one value from the sample as current TC"""
self.currentTC = np.random.choice(self.sample)
class AggregatedTransfer(Transfer):
""" A Transfer Coefficient from a combined set of several given samples \
and or probability distributin functions. A weighting factor for the \
partial samples can be defined.
Parameters:
----------------
partialDistributions: list<Transfer>
a list of SochasticTransfers and/or RandomChoiceTransfers to be \
considered in the combined distribution
weightingFactors: list<float>
list of weighting factors
target: components.Compartment
specifies the target compartment of the transfer
priority: integer
if random values for the transfer coefficients are normalized, \
a higher priority excludes the value from adjustment
"""
def __init__(self, target, singleTransfers, weights = None, priority=1):
super(AggregatedTransfer, self).__init__(target, priority)
self.singleTransfers = singleTransfers
if weights != None:
self.weights = weights
else:
self.weights = [1]*len(singleTransfers)
def sampleTC(self):
cs = np.cumsum(self.weights) #An array of the weights, cumulatively summed.
total = sum(self.weights)
ind = sum(cs < np.random.uniform(0, total)) #Find the index of the first weight over a random value.
transfer = self.singleTransfers[ind]
transfer.sampleTC()
self.currentTC = transfer.getCurrentTC()
class SinglePeriodInflow(object):
""" A single inflow represents the inflow of material to the model in \
one single period. To implement material inflows to the system over the\
entire simulated time implement ExternalListInflow or ExternalFunctionInflow
To implement use subclass
"""
def __init__(self):
self.currentValue = None
def sampleValue(self):
pass
def getValue(self):
return self.currentValue
class StochasticFunctionInflow(SinglePeriodInflow):
""" External inflow to a compartment of one Period. Uncertatinty about\
the true value of this inflow is represented as probability distribution\
function.
Parameters:
----------------
ProbabilityDistribution: probability density function
probability distribution (e.g. from scipy.stats) to represent uncertain\
knowledge about the true value of the inflow
values: list<float>
parameter list of the distribution function.
"""
def __init__(self, probabilityDistribution, parameters):
super(StochasticFunctionInflow, self).__init__()
self.pdf = probabilityDistribution
self.parameterValues = parameters
def sampleValue(self):
self.currentValue = self.pdf(*self.parameterValues)
class RandomChoiceInflow(SinglePeriodInflow):
""" External inflow to a compartment in one Period. Uncertatinty about\
the true value of this inflow is represented as a sample representing the\
the assumptions about the true value.
Parameter:
----------------
sample: list<float>
sample to draw random value from
"""
def __init__(self, sample):
super(RandomChoiceInflow, self).__init__()
self.sample = sample
def sampleValue(self):
# np.random.seed(1)
self.currentValue = np.random.choice(self.sample)
class FixedValueInflow(SinglePeriodInflow):
""" External inflow amount to a compartment in one Period.
Parameter:
----------------
value: float
the inflow vlaue
"""
def __init__(self, value):
super(FixedValueInflow, self).__init__()
self.currentValue = value
class ExternalInflow(object):
""" Represents the external material inflow to the observed system.
To implement, please use subclass
"""
def __init__(self, target, derivationDistribution, derivationParameters, startDelay):
self.target = target
self.startDelay = startDelay
self.derivationDistribution = derivationDistribution
self.derivationParameters = derivationParameters
self.derivationFactor = 1
def getCurrentInflow(self, period):
pass
class ExternalListInflow(ExternalInflow):
""" Source of external inflows as a list of material amounts for each period \
considered in the model.
Parameters:
----------------
target: components.Compartment
target compartment of the external inflow.
valueList: list<SingleInflow>
list of Single Inflow elements for each period
derivationDistribution: probability density function
probability distribution (e.g. from scipy.stats) to represent uncertain\
knowledge about the true value of the model inflows. The derivation \
is calculated once per simulation rund and applied to the whole inflow list
derivationParameters: list<float>
parameter list of the probability distribution function of the \
derivation
startDelay: integer
time lag between the simulation start and the first release from the source.
"""
def __init__(self, target, inflowList, derivationDistribution= None, derivationParameters=[], startDelay = 0):
super(ExternalListInflow, self).__init__(target, derivationDistribution, derivationParameters, startDelay)
self.inflowList = inflowList
for i in range(len(self.inflowList)):
if isinstance(self.inflowList[i], (int, float, list)):
self.inflowList[i] = StochasticFunctionInflow(self.inflowList[i])
#self.inflowList[i] = FixedValueInflow(self.inflowList[i])
def getCurrentInflow(self, period = 0):
""" determines the inflow for a given period"""
if period - self.startDelay < 0:
return 0
else:
if (period-self.startDelay) < len(self.inflowList):
returnValue = self.inflowList[(period-self.startDelay)].getValue()*self.derivationFactor
if returnValue >=0:
return returnValue
else:
return 0
else:
return 0
def sampleValues(self):
for inf in self.inflowList:
inf.sampleValue()
if self.derivationDistribution != None:
self.derivationFactor = self.derivationDistribution(*self.derivationParameters)
class ExternalFunctionInflow(ExternalInflow):
""" External source; mean inflow amounts as function of time, relative \
derivation from stochastic distribution. delay function.
Parameters:
--------------
target: components.Compartment
target compartment of the external inflow.
basicInflow: components.SingleInflow
initial inflow to the system in the first period
inflowFunction: function
returns a material amount as inflow for a specific period; gets basic\
Value and period number as input. If no input function is defined, the \
basic value is used for all periods.
derivationDistribution: probability density function
probability distribution (e.g. from scipy.stats) to represent uncertain\
knowledge about the true value of the model inflows. The derivation \
is calculated once per simulation rund and applied to the whole inflow list
derivationParameters: list<float>
parameter list of the probability distribution function of the \
derivation
startDelay: integer
time lag between the simulation start and the first release from the source.
"""
def __init__(self, target, basicInflow, inflowFunction = None, defaultInflowFunction= 0, derivationDistribution = None,
derivationParameters=[], startDelay=0):
super(ExternalFunctionInflow, self).__init__(target, derivationDistribution, derivationParameters, startDelay)
if inflowFunction == None:
self.inflowFunction = self.defaultInflowFunction
else:
self.inflowFunction = inflowFunction
if isinstance(basicInflow, (int, long, float, list)):
self.basicInflow = SinglePeriodInflow(basicInflow)
else:
self.basicInflow = basicInflow
def getCurrentInflow(self, period= 0):
if period - self.startDelay < 0:
return 0
else:
# return self.inflowFunction(self.baseValue, period-self.startDelay)*self.derivationFactor
returnValue = self.inflowFunction(self.baseValue, period-self.startDelay)*self.derivationFactor
if returnValue >= 0:
return returnValue
else:
return 0
def sampleValues(self):
self.basicInflow.sampleValue()
self.baseValue = self.basicInflow.getValue()
if self.derivationDistribution != None:
self.derivationFactor = self.derivationDistribution(*self.derivationParameters)
def defaultInflowFunction(self, base, period):
return base