-
Notifications
You must be signed in to change notification settings - Fork 0
/
system.py
2278 lines (1765 loc) · 75.5 KB
/
system.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
import warnings
import numpy as np
import pickle
from recordclass import recordclass
import logging
from pandas import DataFrame, Series
import networkx as nx
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
np.set_printoptions(precision=3)
from scipy.signal import gaussian
import matplotlib.pyplot as plt
from cython_utils import calcDemandCython, randomWalk, calcProfiles
from recorder import Recorder
LENGTH_OF_DAY = 24 * 60
ERROR_SCALE = 0.01
_MATCHER = "METRO"
_PROD_SURPLUS = True
_LOG_MATCHER = False
_ANNEAL_TEMP = 10000
_MATCHER_CMP_ALL = False
MAX_DEMAND_DIFF = 1 # MWh in 15 minutes
OVERCAPACITY_FACTOR = 1.1
USER_OPTIMIZE_PROB = 0.95
DEMAND_HISTORY_LEN = 30
CONSUMER_SPOT_DECAY = 1 # 0 - 1, where 0 means consider all 30 days equal,
# 1 means consider only the latest entry
UTILITY_DEMAND_DECAY = 0.5
OPTIMIZERS = 0.2 # percentage of optimizing consumer agents
REMOTE_CONTROLLED = 1.0 # percentage of optimizing users that the utility controlls
CAPACITY_LIMIT = 500
SOLAR_ERROR = 0.1
WIND_ERROR = 0.1
RENEWABLE_SAFETY_MARGIN = 1
RENEWABLE_REG_FACTOR = 0
RENEWABLE_ERROR_1 = 0.03
RENEWABLE_ERROR_2 = 0.03
RENEWABLE_CORRELATION = 1.0
SPOT_MARKET_RESOLUTION = 60
BALANCING_INTERVALL = 15
BALANCING_MIN_OFFER = 0.5
REGULATION_FACTOR = 0.5
REGULATION_PRICE_FACTOR = 0.2
MIN_RUN_FACTOR = 0
MAX_SPOT_BID = 0.95
USE_CACHE_AGENTS = False
LOG_DEMAND = False
_MPI = False
# TODO: these need to be updated automatically
_SLICES = int(LENGTH_OF_DAY / SPOT_MARKET_RESOLUTION)
_B_SLICES = int(SPOT_MARKET_RESOLUTION / BALANCING_INTERVALL)
# A word about units: powerplants are all full MW. demand is in kW.
# Since the market deals only in full MW the utility also deals in full MW.
# Therefore the utility does most of the conversion
# a slice is the part of the day given by SPOT_MARKET_RESOLUTION
# a subslice is the part of a slice given by BALANCING_INTERVALL
Offer = recordclass('Offer', 'max min price idx t node')
Profile = recordclass('Profile', 'profile price idx id base')
ScheduleItem = recordclass('ScheduleItem', 'accepted min max price idx t')
AgentCache = recordclass('AgentCache', 'normal optimizing')
RegulationOffer = recordclass(
"RegulationOffer", "up down priceUp priceDown idx t")
Correction = recordclass("Correction", "capacity power idx t")
def slice2T(slc, blcSlc=None, full=False):
if blcSlc is None:
t_start = slc * SPOT_MARKET_RESOLUTION
return np.arange(t_start, t_start+SPOT_MARKET_RESOLUTION)
else:
if full:
t_start = slc * SPOT_MARKET_RESOLUTION + blcSlc * BALANCING_INTERVALL
return np.arange(t_start, t_start+BALANCING_INTERVALL * (_B_SLICES - blcSlc))
else:
t_start = slc * SPOT_MARKET_RESOLUTION + blcSlc * BALANCING_INTERVALL
return np.arange(t_start, t_start+BALANCING_INTERVALL)
def HtoMin(H):
t_len = LENGTH_OF_DAY/24
t_start = H * t_len
t_end = t_start + t_len
t = np.arange(t_start, t_end, dtype=int)
return t
def HqToMin(H, q):
if q not in [0, 1, 2, 3]:
raise ValueError("the quarter must be: 0 <= q <= 3.")
t = HtoMin(H).reshape(4, 15)
return t[q]
def integrateDay15min(values):
return np.sum(values.reshape(96, 15), axis=1)
def integrateDayH(values):
return np.sum(values.reshape(24, 60), axis=1)
def integrateDayQtoH(values):
return np.sum(values.reshape(24, 4), axis=1)
def integrateDayToSlice(values):
return np.sum(values.reshape(_SLICES, SPOT_MARKET_RESOLUTION), axis=1)
def integrateDayToSubslice(values):
return np.sum(values.reshape(_SLICES*_B_SLICES, BALANCING_INTERVALL), axis=1)
class System(Recorder):
"""the class that controls the whole system, timing loop and everything,
"""
def __init__(self):
super().__init__()
self.users = []
self.utilities = []
self.producers = []
self.spot = MarketAgent(self)
self._dailyDemand = None
self._dailyForecastedDemand = None
self._minuteDailyDemand = None
self._minutesProdSchedule = None
self._t0_history = []
self._demandHistory = []
self._diffHistory = []
self._spotPriceHistory = []
self._spotPriceAverageCache = None
self._balancingPriceHistory = []
self._regulationPriceHistory = []
self._regulationTypeHistory = []
self._renewableCorrelation = randomWalk(
LENGTH_OF_DAY, 1, RENEWABLE_ERROR_1, RENEWABLE_ERROR_2)
self.solarTime = np.random.randint(3*60)
self.zones_dict = {0:0}
self.network = nx.Graph()
self.network.add_node(0)
def node2zone(self,node):
if node in zones_dict:
return self.zones_dict[node]
else:
raise ValueError("No zone defined for node {}".format(node))
def cycle_matrix(self):
cycles = nx.cycle_basis(self.network)
edges = [e for e in self.network.edges]
nodes = [n for n in self.network.nodes]
cycle_matrix = np.zeros((len(edges),len(cycles)))
for c_idx,c in enumerate(cycles):
c_edges = cycle2edgeList(c)
for e_idx,e in enumerate(edges):
if e in c_edges:
cycle_matrix[e_idx,c_idx] = 1
if e[::-1] in c_edges:
cycle_matrix[e_idx,c_idx] = -1
return cycle_matrix
def incidence_matrix(self,nodes,edges):
i_mat = nx.incidence_matrix(
self.network,
nodelist=nodes,
edgelist=edges,
oriented=True)
return -i_mat.toarray()
@property
def spotPrice(self):
return self._spotPriceHistory[-1]
@spotPrice.setter
def spotPrice(self, value):
# todo: this should not have a setter
self._spotPriceAverageCache = None
self._spotPriceHistory.append(value)
def spotPriceHAverage(self, c=0, l=30):
if len(self._spotPriceHistory) > 1:
if self._spotPriceAverageCache is None:
self._spotPriceAverageCache = dict()
if c in self._spotPriceAverageCache:
return self._spotPriceAverageCache[c]
else:
x = np.array(self._spotPriceHistory[-l:])
w = (np.ones(x.shape)-c) ** (np.repeat(
np.arange(x.shape[0]-1, -1, -1), x.shape[1]
)
.reshape(x.shape))
w /= np.sum(w, axis=0)
self._spotPriceAverageCache[c] = np.sum(x*w, axis=0)
return self._spotPriceAverageCache[c]
else:
return self._spotPriceHistory[0]
def nodalPriceForBus(self, bus):
if hasattr(self, 'nodalPrices'):
return self.nodalPrices[:, bus]
else:
raise ValueError("Nodal prices not found! Check setup.")
@property
def daysRun(self):
return len(self._spotPriceHistory)
@property
def dailyForecastedDemand(self):
if self._dailyForecastedDemand is None:
demand = np.zeros(_SLICES)
for util in self.utilities:
D = util.forecastDailyDemand()
demand += D
logger.debug("util {} forecasted:{}".format(util.idx, str(D)))
self._dailyForecastedDemand = demand
return self._dailyForecastedDemand
@property
def dailyDemand(self):
if self._dailyDemand is None:
demand = np.zeros(_SLICES)
for util in self.utilities:
demand += util.dailyDemand
self._dailyDemand = demand
return self._dailyDemand
@property
def minuteDailyDemand(self):
if self._minuteDailyDemand is None:
demand = np.zeros(LENGTH_OF_DAY)
t = np.arange(LENGTH_OF_DAY)
for util in self.utilities:
demand += sum(util.minuteDemandSplit(current=True))
self._minuteDailyDemand = demand
return self._minuteDailyDemand
def plotPriceMW(self):
H = 0
supply = [[p.priceForH(H), p.upCapacityForH(H)]
for p in self.producers]
supply.sort()
price, cap = zip(*supply)
sum_cap = np.cumsum(cap)
plt.figure()
plt.plot(sum_cap, price)
plt.show()
def plotPriceDay(self):
if not(self.spotPrice is None):
plt.figure()
plt.plot(self.spotPrice)
else:
logger.warning("No price for the day, yet.")
def runSpotMarket(self):
prices = np.zeros(_SLICES)
producerSchedule = {}
if _MATCHER == "METRO":
selectedProfiles, profile, accepted, prices = self.spot.matchDemandForDayR()
elif _MATCHER == "MIP":
selectedProfiles, profile, accepted, prices = self.spot.matchDemandForDayMIP()
else:
raise ValueError("No _MATCHER defined")
for slc_sItems in accepted:
for sItem in slc_sItems:
if sItem.idx in producerSchedule:
producerSchedule[sItem.idx][sItem.t] = sItem.accepted
else:
producerSchedule[sItem.idx] = np.zeros(LENGTH_OF_DAY)
producerSchedule[sItem.idx][sItem.t] = sItem.accepted
return prices, producerSchedule, selectedProfiles
def calculateBalancingCosts(self, balacingPrices, balancingType, allCorrections):
producerRev = np.zeros(_SLICES*_B_SLICES)
# producer Rev due to corrections
for num, corrections in enumerate(allCorrections):
slc = num // _B_SLICES
blcSlc = num % _B_SLICES
for c in corrections:
diff = c.power
if balancingType[slc] == 'd':
if diff <= 0: # actual down regulation
price = balacingPrices[slc][1]
elif diff > 0: # up regulation in down hour
price = self.spotPrice["sys"][slc]
elif balancingType[slc] == 'u':
if diff >= 0: # actual up regulation
price = balacingPrices[slc][0]
elif diff < 0: # down regulation in up hour
price = self.spotPrice["sys"][slc]
else:
price = self.spotPrice["sys"][slc]
self.producers[c.idx].balancingRev += price * diff
producerRev[num] += price * diff
logger.debug(
"producer revenues for every quarter:\n{}".format(str(producerRev)))
# util cost
allDiff = np.zeros(_SLICES*_B_SLICES)
utilRev = np.zeros(_SLICES*_B_SLICES)
for util in self.utilities:
forecast = np.repeat(util.forecastDailyDemand(
)/SPOT_MARKET_RESOLUTION, SPOT_MARKET_RESOLUTION)
demand = sum(util.minuteDemandSplit(
current=True)) / 60 # MWm to MWh
logger.debug("balancing for {}".format(util.idx))
diff = integrateDayToSubslice(demand - forecast)
allDiff += diff
cost = 0
for num, d in enumerate(diff):
slc = num // _B_SLICES
blcSlc = num % _B_SLICES
if balancingType[slc] == 'd':
price = balacingPrices[slc][1]
elif balancingType[slc] == 'u':
price = balacingPrices[slc][0]
else:
price = self.spotPrice["sys"][slc]
cost += price * d
utilRev[num] += price * d
logger.debug(
"\tin {}/{}: {:7.3f}MWh * {:7.3f}€/MWh = {:7.3f}€".format(slc, blcSlc, d, price, price*d))
util.balancingCost += cost
# print("balancingCost {}".format(cost))
logger.debug("sum of diff:{}".format(str(allDiff)))
logger.debug(
"util cost for every quarter:\n{}".format(str(utilRev)))
logger.debug("sum of util cost:{}".format(sum(utilRev)))
# producer cost
for p in self.producers:
schedule = p.minuteSchedule()
production = p.minuteProduction()
diff = integrateDayToSubslice(
production - schedule)/60 # MWm to MWh
rev = 0
for num, d in enumerate(diff):
slc = num // _B_SLICES
blcSlc = num % _B_SLICES
if balancingType[slc] == 'd':
if d <= 0: # under produciton in down hour
price = self.spotPrice["sys"][slc]
elif d > 0: # over production in down hour
price = balacingPrices[slc][1]
elif balancingType[slc] == 'u':
if d >= 0: # over produciton in up hour
price = self.spotPrice["sys"][slc]
elif d < 0: # under produciton in up hour
price = balacingPrices[slc][0]
else:
price = self.spotPrice["sys"][slc]
rev += price * d
p.balancingRev += rev
def calculateUtilityCost(self, hourlyPrices):
for util in self.utilities:
demand = util.forecastDailyDemand()
demand = np.round(demand, 4) # we round to the 4 decimal ...
# to be consitend with users paying their kWh to the first decimal
logger.debug("demand of utility {} is {}".format(
util.idx, str(demand)))
logger.debug("cost per H:{}".format(str(demand*hourlyPrices[util.node])))
logger.debug("sum: {}".format(
np.sum(np.round(demand*hourlyPrices[util.node], 2))))
util.purchaseCost += np.sum(np.round(demand*hourlyPrices[util.node], 2))
def calculateProducerRevenues(self, hourlyPrices, producerSchedule):
for p in self.producers:
if p.idx in producerSchedule:
# we sum up for every minute so we devide by the number
# of minutes per slice again
schedule = integrateDayToSlice(
producerSchedule[p.idx]/(LENGTH_OF_DAY/_SLICES))
p.revenues += np.sum(schedule*hourlyPrices[p.node])
def performBalancing(self):
day_diff = self.forecastDemandDiff()
# diff in subslices
day_diffBlc = np.round(
integrateDayToSubslice(day_diff)/60) # MWm to MWh
# diff in slices
day_diffSlice = np.round(
integrateDayToSlice(day_diff)/60) # MWm to MWh
max_diff = MAX_DEMAND_DIFF / 15 * BALANCING_INTERVALL
logger.debug(
"balancing needed per subslice:{}".format(str(day_diffBlc)))
demand = self.minuteDailyDemand
balancingType = []
pricePerH = []
allCorrections = [[]
for i in range(int(LENGTH_OF_DAY/BALANCING_INTERVALL))]
for slc in range(_SLICES):
t_slc = slice2T(slc)
# offers = [p.regulationOfferForT(t_slc) for p in self.producers]
# offers = list(filter(lambda x: x, offers)) # removes all None
priceUp = self.spotPrice["sys"][slc]
priceDown = self.spotPrice["sys"][slc]
matched = 0
for blcSlc in range(_B_SLICES):
diff = day_diffBlc[_B_SLICES*slc+blcSlc]
accepted = []
t_blc = slice2T(slc, blcSlc, full=True)
offers = [p.regulationOfferForT(t_blc) for p in self.producers]
offers = list(filter(lambda x: x, offers)) # removes all None
if diff - matched > max_diff:
# up regulation needed
# print "up regulation {} in {}/{}".format(diff,H,q)
while matched < diff:
if len(offers) == 0:
raise ValueError(
"system could not be up balanced! {} MWh diff {} MWh matched".format(diff,matched))
offers.sort(key=lambda x: x.priceUp)
# find lowest up offer with value bigger 0
idx = 0
while True:
if offers[idx].up > 0:
offer = offers.pop(idx)
break
else:
idx += 1
if idx >= len(offers):
logger.error(offers)
raise ValueError(
"system could not be up balanced! {} missing".format(diff-matched))
priceUp = max((offer.priceUp, priceUp))
power = offer.up * BALANCING_INTERVALL / 60 # MWm to MWh
if power > diff-matched:
accepted_capacity = \
(diff-matched) / BALANCING_INTERVALL * 60
matched += diff-matched
else:
matched += power
accepted_capacity = offer.up
accepted_power = accepted_capacity * \
(t_blc[-1] - t_blc[0])
accepted.append(Correction(accepted_capacity,
accepted_power,
offer.idx,
t_blc))
elif diff - matched < -max_diff:
# down regulation needed
# print "down regulation {} in {}/{}".format(diff,H,q)
while matched > diff:
offers.sort(key=lambda x: x.priceDown, reverse=True)
# find highest down offer with value bigger 0
# not that the sort was reversed
idx = 0
while True:
if len(offers) == 0 or idx >= len(offers):
logger.warn(
"system could not be down balanced!")
logger.warn("price set to 0.")
# TODO: negative prices and such
matched = diff
priceDown = 0
break # no more elements in the list
try:
if offers[idx].down > 0: # if it is a down offer
# unpack the offer
offer = offers.pop(idx)
priceDown = min(
(offer.priceDown, priceDown))
# NOTE: it is possible for the offer price to be higher
# then the current down price, since the offer can be
# from a plant that is just in the list because if got
# activated for down regulation
power = -offer.down * BALANCING_INTERVALL / 60 # MWm to MWh
if power <= diff-matched:
accepted_capacity = \
(diff-matched) / \
BALANCING_INTERVALL * 60
matched += diff-matched
break # this offer did match our needs fully we can stop looking
else:
matched += power
accepted_capacity = -offer.down
# append offer to the accepted ones
accepted_power = -accepted_capacity\
* (t_blc[-1] - t_blc[0])
accepted.append(Correction(accepted_capacity,
accepted_power,
offer.idx,
t_blc))
else: # no down offer so advance
idx += 1
except IndexError:
logger.error(len(offers), idx)
raise
for c in accepted:
self.producers[c.idx].applyBlcCorrectionForT(
c.t, c.capacity)
allCorrections[_B_SLICES*slc+blcSlc] = accepted
for p in self.producers:
p.nextSlc()
pricePerH.append([priceUp, priceDown])
if day_diffSlice[slc] > 1:
balancingType.append('u')
elif day_diffSlice[slc] < -1:
balancingType.append('d')
else:
balancingType.append('n')
return pricePerH, balancingType, allCorrections
def setProducerSchedule(self, schedule):
for idx, caps in schedule.items():
# self.producers[idx].setSchedule(caps)
self.producers[idx].setMinuteSchedule(caps)
def setUtilityProfiles(self, profiles):
for idx, profile in profiles.items():
assert idx == self.utilities[idx].idx
# if this does not hold true allways we need to adress it by having
# a dict about the utilities and their indexes
self.utilities[idx].setProfileForDay(profile)
def minuteDailyProduction(self):
if self._minutesProdSchedule is None:
if np.all(np.isnan(self.spotPrice[0])):
raise ValueError("can not get daily production yet.")
schedule = np.zeros(LENGTH_OF_DAY)
for p in self.producers:
schedule += p.minuteProduction()
self._minutesProdSchedule = schedule
return self._minutesProdSchedule
def updateProductionScheduleForT(self, t, value):
# print('update production schedule: {} for {}'.format(value,t))
self._minutesProdSchedule[t] += value
def forecastDemandDiff(self):
return self.minuteDailyDemand - self.minuteDailyProduction()
def runForDays(self, days):
for d in range(days):
logger.info("day {}".format(d))
self.startDay()
# ==== spot market =====
hourlyPrices, producerSchedule, selectedProfiles = self.runSpotMarket()
# print(len(producerSchedule))
# for idx,item in producerSchedule.items():
# print(idx,item)
self.setProducerSchedule(producerSchedule)
self.setUtilityProfiles(selectedProfiles)
# for util in self.utilities:
# print(util._profile)
self.spotPrice = hourlyPrices
self.calculateUtilityCost(hourlyPrices)
self.calculateProducerRevenues(hourlyPrices, producerSchedule)
for util in self.utilities:
util.updatePostMarket()
self._diffHistory.append(self.forecastDemandDiff())
self._minuteDailyDemand = None # this might have changed due to the update
# ====== balancing ========
balacingPrices, balancingType, allCorrections = self.performBalancing()
self.calculateBalancingCosts(
balacingPrices, balancingType, allCorrections)
# ^===== balancing =======
# plt.plot(self.minuteDailyProduction())
# self.plotPriceDay()
bprice = []
for t, p, sp in zip(balancingType, balacingPrices, self.spotPrice):
if t == 'u':
bprice.append(p[0])
elif t == 'd':
bprice.append(p[1])
else:
bprice.append(sp)
self._balancingPriceHistory.append(list(zip(*balacingPrices)))
self._regulationPriceHistory.append(bprice)
self._regulationTypeHistory.append(balancingType)
t0 = np.fromiter((u.t0 for u in self.users),
float, len(self.users))
self._t0_history.append(t0)
self.nextDay()
logger.info('...done')
def startDay(self):
self._renewableCorrelation = randomWalk(
LENGTH_OF_DAY, 1, RENEWABLE_ERROR_1, RENEWABLE_ERROR_2)
self.solarTime = np.random.randint(3*60)
for util in self.utilities:
util.startDay()
def nextDay(self):
if self.daysRun > 0:
self._demandHistory.append(self.minuteDailyDemand)
for util in self.utilities:
util.nextDay()
for p in self.producers:
p.nextDay()
self._dailyDemand = None
self._dailyForecastedDemand = None
self._minuteDailyDemand = None
self._minutesProdSchedule = None
def resetCosts(self):
for util in self.utilities:
util.resetCosts()
for p in self.producers:
p.resetCosts()
for u in self.users:
u.resetCosts()
def costPerMW(self):
userCostV = []
optiUserCostV = []
userCost = []
optiUserCost = []
fcDict = {util.idx: util.fixedCosts() for util in self.utilities}
usageDict = {}
for util in self.utilities:
optUsage = 0
usage = 0
for u in util.users:
if u.isOptimizer:
optUsage += u.usedPower/1000
else:
usage += u.usedPower/1000
usageDict[util] = (usage, optUsage)
cost = util.costs()
userCostV.append(cost['normal_variable'])
optiUserCostV.append(cost['opt_variable'])
fcMW = fcDict[util.idx] / (usage+optUsage)
if usage > 0:
userCost.append((cost['normal_variable'] + fcMW * usage))
if optUsage > 0:
optiUserCost.append((cost['opt_variable'] + fcMW * optUsage))
ret = dict()
ret["usageNormal"] = sum(item[0] for key, item in usageDict.items())
ret["usageOpt"] = sum(item[1] for key, item in usageDict.items())
ret["costNormalVari"] = np.sum(userCostV)
ret["costNormalAll"] = np.sum(userCost)
ret["costOptVari"] = np.sum(optiUserCostV)
ret["costOptAll"] = np.sum(optiUserCost)
ret["costMW"] = (ret["costOptAll"] + ret["costNormalAll"]
)/(ret["usageNormal"]+ret["usageOpt"])
return ret
def saveScenario(self, name):
# users
t0 = []
maxD = []
minD = []
isOptimizer = []
util = []
for u in self.users:
t0.append(u.t0)
maxD.append(u.maxD)
minD.append(u.minD)
isOptimizer.append(u._isOptimizer)
util.append(u.util_idx)
# utilities
# nothin?
# producers
pidx = []
capacity = []
price = []
cost = []
Ptype = []
minRunFactor = []
regulationFactor = []
for p in self.producers:
pidx.append(p.idx)
capacity.append(p.maxCapacity)
price.append(p.priceMW)
cost.append(p.cost)
minRunFactor.append(p.minRunFactor)
regulationFactor.append(p.regulationFactor)
if isinstance(p, SolarAgent):
Ptype.append('solar')
elif isinstance(p, WindAgent):
Ptype.append('wind')
else:
Ptype.append('normal')
out = {
't0': np.array(t0),
'maxD': np.array(maxD),
'minD': np.array(minD),
'isOptimizer': np.array(isOptimizer),
'util': np.array(util),
'pidx': np.array(pidx),
'capacity': np.array(capacity),
'price': np.array(price),
'cost': np.array(cost),
'Ptype': np.array(Ptype),
'minRunFactor': np.array(minRunFactor),
'regulationFactor': np.array(regulationFactor)
}
np.savez(name, **out)
@classmethod
def loadScenario(cls, name):
sys = cls()
scenario = np.load(name)
t0 = scenario['t0']
maxD = scenario['maxD']
minD = scenario['minD']
isOptimizer = scenario['isOptimizer']
util = scenario['util']
userUtilDict = dict()
# create users
for t, maD, miD, opt, util in zip(t0, maxD, minD, isOptimizer, util):
user = DemandAgent(sys, maD, miD, t, opt)
sys.users.append(user)
if util in userUtilDict:
userUtilDict[util].append(user)
else:
userUtilDict[util] = [user]
# create utilities
for idx, users in userUtilDict.items():
sys.utilities.append(UtilityAgent(sys, users, idx))
# create producers
pidx = scenario['pidx']
capacity = scenario['capacity']
price = scenario['price']
cost = scenario['cost'] # ignored further on
Ptype = scenario['Ptype']
if 'minRunFactor' in scenario:
minRun = scenario['minRunFactor']
else:
minRun = np.ones(cost.shape)*MIN_RUN_FACTOR
if 'regulationFactor' in scenario:
regulationFactor = scenario['regulationFactor']
else:
regulationFactor = np.ones(cost.shape)*REGULATION_FACTOR
number = np.arange(len(cost))
for idx, cap, p, c, typ, i in zip(pidx, capacity, price, cost, Ptype, number):
if typ == 'solar':
sys.producers.append(SolarAgent(sys, idx, np.max(cap), p))
elif typ == 'wind':
sys.producers.append(WindAgent(sys, idx, np.max(cap), p))
else:
sys.producers.append(ProductionAgent(sys, idx, np.max(cap), p))
sys.producers[i].minRunFactor = minRun[i]
sys.producers[i].regulationFactor = regulationFactor[i]
return sys
def saveData(self, name):
out = dict()
out['phase'] = np.array(self._t0_history)
out['balancingPower'] = np.array(self._diffHistory)
out['spotPrice'] = np.array(self._spotPriceHistory)
if hasattr(self, "capacity"):
out['capacity'] = self.capacity
out['renewables'] = self.renewable_capacity
out['needed_capacity'] = self.needed_capacity
else:
out['capacity'] =\
sum([p.maxCapacity for p in self.producers if not(p.isRenewable())])
out['renewables'] =\
sum([p.maxCapacity for p in self.producers if p.isRenewable()])
out['needed_capacity'] =\
sum((u.maxD for u in self.users))/1000.0
userCost = []
optiUserCost = []
variUserCost = []
variOptiUserCost = []
fcDict = {util.idx: util.fixedCostPerUser() for util in self.utilities}
for u in self.users:
if u._isOptimizer:
optiUserCost.append((u.cost+fcDict[u.util_idx])/self.daysRun)
variOptiUserCost.append((u.cost)/self.daysRun)
else:
userCost.append((u.cost+fcDict[u.util_idx])/self.daysRun)
variUserCost.append((u.cost)/self.daysRun)
out['normalUserCost'] = np.array(userCost)
out['optiUserCost'] = np.array(optiUserCost)
out['variOptiUserCost'] = np.array(variOptiUserCost)
out['variUserCost'] = np.array(variUserCost)
priceMW = []
for p in self.producers:
if p.isRenewable():
priceMW.append(p.priceMW_all)
out['priceMW'] = np.array(priceMW)
# save all uppercase variables in a dict
out['config'] = {k: v for k, v in globals().items()
if k.isupper() and k[0] != '_'}
with open(name, 'wb') as outfile:
pickle.dump(out, outfile, protocol=pickle.HIGHEST_PROTOCOL)
def renewableError(self):
ret = randomWalk(LENGTH_OF_DAY, 1, RENEWABLE_ERROR_1,
RENEWABLE_ERROR_2)
ret += RENEWABLE_CORRELATION * self._renewableCorrelation
ret /= 1 + RENEWABLE_CORRELATION
return ret
class MarketAgent(object):
# TODO: clean up no longer needed functionality, like matchDemandFor...
def __init__(self, system):
self.system = system
self.selection = None
def pricesForProfile(self, profile, offers):
prices = np.zeros_like(profile)
prod_surplus = 0
for slc, usage in enumerate(profile):
price, accepted = self.priceForUsage(usage, offers[slc])
for item in accepted:
prod_surplus += item.accepted * (price - item.price)
prices[slc] = price
return prices, prod_surplus
def priceForUsage(self, usage, sliceOffers, offers=False):
available = 0
accepted = []
for o in sliceOffers:
power = o.max * SPOT_MARKET_RESOLUTION / 60 # from MWm to MWh
# if offers we keep track of the accepted offers from producers
if offers:
acc_p = power
if power > usage-available:
acc_p = usage-available
acc = acc_p / SPOT_MARKET_RESOLUTION * 60 # to MW
item = ScheduleItem(acc, o.min, o.max,
o.price, o.idx, o.t)
accepted.append(item)
available += power
price = o.price
if available >= usage:
break
return price, accepted
def evaluateProfile(self, base, profile, n, offers):
surplus = 0
prices = []
for slc, usage in enumerate(base):
# iterate every hour and add the base load to the test profile