-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheom_funcs.py
1676 lines (1410 loc) · 61.4 KB
/
eom_funcs.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 os, sys, csv, pickle, requests, types, zipfile
import numpy as np
from datetime import timedelta,datetime
from functools import lru_cache
from pprint import pprint
requests.Session()
from timeit import default_timer as timer
from collections import OrderedDict as odict
from bunch import Bunch
import xml.etree.ElementTree as ET
from importlib import reload
from copy import deepcopy
from scipy import sparse
import quantecon as qe
from dateutil.tz import gettz
from pytz import country_timezones
from eom_utils import repl_list, fn_root, data2csv, structDict, sctXt,\
tDict2stamps, boxplotqntls, nanlt, nangt, plotEdf, cdf2qntls, rerr
exec(repl_list)
from entsoe_py_data import BIDDING_ZONES, PSRTYPE_MAPPINGS, \
PSRTYPE_MAPPINGS_INTER
from progress.bar import Bar
from numpy.random import MT19937, Generator, SeedSequence
def rngSeed(seed=0,):
"""Seed a random number generator at seed.
Used seed = None for a random state.
"""
if seed is not None:
return Generator(MT19937(SeedSequence(seed)))
else:
return Generator(MT19937())
rng = rngSeed()
# For the list of attributes, see 'ENTSO-E TRANSPARENCY PLATFORM
# DATA EXTRACTION PROCESS IMPLEMENTATION GUIDE'.
# # For debugging XML structures:
# for child in ts:
# print(child.tag,child.attrib,child.tail,child.text)
# These domain codes for each country/zone are found within
# 'Transparency Platform restful API - user guide'. (Also
# this has been copied into the appendixA.xlsx spreadsheet.)
if '__file__' in dir():
with open(os.path.join(os.path.dirname(__file__),
'apiDoc','bzAreas.csv'),'r') as file:
bzs = list(csv.reader(file,delimiter='\t'))
else:
with open(os.path.join(sys.path[0],'apiDoc','bzAreas.csv'),'r') as file:
bzs = list(csv.reader(file,delimiter='\t'))
from download_config import token
url0 = r'https://transparency.entsoe.eu/api?securityToken='+token
# B0630_BTA60, B0630_BTA61 are to be read as '*_BT*'; e.g., the business
# type of 'B0630_BTA61' being A61 (see processXml).
reqInfo = {
'dap':{
'id':0,
'reqOpts':[None],
'dataName':'price.amount',
'unitHead':'currency_Unit.name'
},
'actlTotLd':{
'id':1,
'reqOpts':[None],
'dataName':'quantity',
'unitHead':'quantity_Measure_Unit.name'
},
'fcstTotLd':{
'id':2,
'reqOpts':[None],
'dataName':'quantity',
'unitHead':'quantity_Measure_Unit.name'
},
'wNsF':{
'id':3,
'reqOpts':['PsrType=B16','PsrType=B18','PsrType=B19'],
'dataName':'quantity',
'unitHead':'quantity_Measure_Unit.name'
},
'B0630_BTA60':{
'id':4,
'reqOpts':[None],
'dataName':'quantity',
'unitHead':'quantity_Measure_Unit.name'
},
'B0630_BTA61':{
'id':5,
'reqOpts':[None],
'dataName':'quantity',
'unitHead':'quantity_Measure_Unit.name'
},
'wNs':{
'id':6,
'reqOpts':['PsrType=B16','PsrType=B18','PsrType=B19'],
'dataName':'quantity',
'unitHead':'quantity_Measure_Unit.name'
},
'unvblGp':{
'id':7,
'reqOpts':[None],
'dataName':'',
'unitHead':''
},
'icppu':{
'id':8,
'reqOpts':[None],
'dataName':'',
'unitHead':''
},
'png':{
'id':9,
'reqOpts':[None],
'dataName':'',
'unitHead':''
},
}
#key/value pairs for availability data.
APs0 = 'production_RegisteredResource.pSRType.powerSystemResources.mRID'
mridData = {
'nomP':'production_RegisteredResource.pSRType.powerSystemResources.nominalP',
'mu':'quantity_Measure_Unit.name',
'psrName':'production_RegisteredResource.pSRType.powerSystemResources.name',
'psrType':'production_RegisteredResource.pSRType.psrType',
'locName':'production_RegisteredResource.location.name',
'prrName':'production_RegisteredResource.name',
'prrMrid':'production_RegisteredResource.mRID',
}
APschema = """Availability Periods data schema:
[1]changes
-[1]createdDateTime
-[1]docStatus
-[1]businessType
-[1]revisionNumber
- TimeSeries/
--[0]production_RegisteredResource.pSRType.powerSystemResources.mRID
--[m]production_RegisteredResource.pSRType.powerSystemResources.nominalP
--[m]quantity_Measure_Unit.name
--[m]production_RegisteredResource.pSRType.powerSystemResources.name
--[m]production_RegisteredResource.pSRType.psrType
--[m]production_RegisteredResource.location.name
--[m]production_RegisteredResource.name
--[m]production_RegisteredResource.mRID
-- Available_Period/
--- timeInterval/
----[2]start
----[2]end
--- Point/
----[2]quantity
"""
genXmlData = {
'mrid':['registeredResource.mRID',],
'name':['registeredResource.name'],
'gType':['MktPSRType','psrType'], # generation type
'cap':['Period','Point','quantity',],
'unit':['quantity_Measure_Unit.name',],
'tStt':['Period','timeInterval','start',],
'tEnd':['Period','timeInterval','end',],
}
def getCodes(cds=None):
"""Get the key:value bidding codes for cds.
Inputs
---
cds - the country codes. If None, uses a nominal set; ir 'CH'
"""
if cds is None:
# I0 required as SEM and IE only do different stuff for some data types
cds = ['NO-2','DK-1','NL','FR','BE','IE','GB','I0']
elif cds=='CH':
cds = ['NO-1','NO-2','NO-3','NO-4','NO-5',
'DK-1','DK-2','NL','FR','BE','IE','GB','I0','DE','DE18','ES',]
codes = {key:BIDDING_ZONES[key] for key in cds}
return codes
def getUrl(reqType,code,yr,opts=None):
"""Create the URL to request from the ENTSO-e API.
Inputs
---
reqType - request type
code - BZ code for the country
yr - the year to use
opts - options to pass into getUrlBase
"""
t0 = 'periodStart='+str(yr)+'01010000'
t1 = 'periodEnd='+str(yr+1)+'01010000'
urlBase = getUrlBase(reqType,code,opts)
url = urlBase if reqType=='png' else '&'.join([urlBase,t0,t1])
return url
def getUrlBase(reqType,code,opts):
"""Build a url based on req type, country code and opt params.
opts should be input as a list of strings, to be
appended to the url one by one. For example, it could be
the psr type for 'wNsF'. Only used by some options though:
- wNsF, wNs
"""
if reqType=='dap':
# day ahead price
urlBase = '&'.join([url0,
'documentType=A44',
'In_Domain='+code,
'Out_Domain='+code,
])
elif reqType=='actlTotLd':
urlBase = '&'.join([url0,
'documentType=A65',
'ProcessType=A16',
'outBiddingZone_Domain='+code
])
elif reqType=='fcstTotLd':
urlBase = '&'.join([url0,
'documentType=A65',
'ProcessType=A01',
'outBiddingZone_Domain='+code
])
elif reqType=='wNsF':
# wind 'n' solar FORECAST
urlBase = '&'.join([url0,
'documentType=A69',
'ProcessType=A01',
'In_Domain='+code,
])
if opts is not None:
urlBase = '&'.join([urlBase]+opts)
elif reqType in ['B0630_BTA60','B0630_BTA61']:
urlBase = '&'.join([url0,
'documentType=A65',
'ProcessType=A31',
'outBiddingZone_Domain='+code
])
elif reqType=='wNs':
# wind 'n' solar OUTTURN
urlBase = '&'.join([url0,
'documentType=A74',
'ProcessType=A16',
'In_Domain='+code,
])
if opts is not None:
urlBase = '&'.join([urlBase]+opts)
elif reqType in ['unvblGp',]:
# generation/production unavailabilities
urlBase = '&'.join([url0,
'documentType=A80', # generation unavailability
'ProcessType=A53', # planned maintenance
'BiddingZone_Domain='+code,
])
if opts is not None:
urlBase = '&'.join([urlBase]+opts)
elif reqType in ['icppu',]:
urlBase = '&'.join([url0,
'documentType=A71', # generation unavailability
'ProcessType=A33',
'In_Domain='+code,
])
elif reqType in ['png',]: # see 4.5. Master Data in web api guide.
urlBase = '&'.join([url0,
'documentType=A95',
'businessType=B11',
'BiddingZone_Domain='+code,
'implementation_DateAndOrTime=__datehere__',
])
return urlBase
@lru_cache(maxsize=64)
def reqData(url):
"""lru_cache (size 64) to avoid multiple unneccessary calls.
If a 400 error is returned, this prints the error.
"""
TIMEOUT=60
print('Request data...')
r = requests.get(url,timeout=TIMEOUT)
if r.status_code==400:
print('HTTP error for url:')
pprint(url.split('&'))
print('\n'+'-'*12+'\n'+r.content.decode('utf-8')+'\n'+'-'*12)
print('\t\t...returned:',r)
return r
def processXml(root,reqType):
"""A basic method to process the XML data from entso-e.
Note that, for now, it is MOSTLY suitable to be used
with xmls that have a single data point per timestamp
(so, for example, wNsF should choose one psr type).
Use a name with *_BTA60 to choose a business type.
Inputs
---
root - an ETnse XML root (NOT a simple root)
reqType - the required data type string
Returns
---
(tsOut, curve) - a clock (with uniform timesteps) and curve (with nans)
unit - the units
"""
timeSeries = root.findall('TimeSeries')
# First, return if no data (print to console if this happens)
if len(timeSeries)==0:
print('Empty time series, returning empty values.')
return (np.empty((0),dtype=np.datetime64),np.empty((0))), None
# If looking at a specific business type, filter on those time series
if len(reqType.split('_'))>1:
reqT0,bt = reqType.split('_BT')
timeSeries = [ts for ts in timeSeries \
if ts.find('businessType').text==bt]
# Util function to determine the time
trt2dt = lambda trt: timedelta(1,) if trt[1]=='D' else \
timedelta(0,60*int(''.join(filter(str.isdigit,trt,))))
crvs, tss, units, timeRes = mtList(4)
for ts in timeSeries:
prd = ts.find('Period')
# Pull out the fixed data for the whole period
units.append(ts.find(reqInfo[reqType]['unitHead']).text)
tr = trt2dt( prd.find('resolution').text )
ti_str = prd.find('timeInterval').find('start').text
# Check times are in UTC and get time
assert(ti_str[-1]=='Z')
ti = datetime.fromisoformat(ti_str[:-1])
# Build the curves
for pt in prd.findall('Point'):
timeRes.append(tr)
ii = int(pt.find('position').text) - 1
crvs.append(float(pt.find(reqInfo[reqType]['dataName']).text))
tss.append(ti+ii*timeRes[-1])
# Check there is only one type of unit
assert(len(set(units))==1)
# Check that we only have up to two time resolutions
assert(len(set(timeRes))<=2)
if len(set(timeRes))==2:
assert((max(timeRes)/min(timeRes)).is_integer)
print(f'Min/max resolutions: {min(timeRes)}, {max(timeRes)}')
# Build a clock
dt = min(timeRes)
tsOut = np.arange(min(tss),max(tss)+timeRes[tss.index(max(tss))],dt,
dtype=datetime)
# Build the time series curve to match
curve = np.nan*np.zeros(len(tsOut))
for i,(t,tr,) in enumerate(zip(tss,timeRes)):
i0 = (t - tsOut[0])//dt
curve[slice(i0,i0+(tr//dt))]=crvs[i]
return (tsOut,curve),set(units).pop()
class ETnse(ET.Element,):
"""Overloaded version of Element Tree ET to avoid having to use xmlns.
"""
def __init__(self,root,):
self._xmlns = (root.tag).split('}')[0]+'}' # xmlns
self._root = root
self.set_data_descriptors()
def set_data_descriptors(self,):
"""Set text, tag, etc from self._root"""
for k,v in type(self._root).__dict__.items():
if type(v) is types.GetSetDescriptorType:
self.__setattr__(k,self._root.__getattribute__(k),)
def __repr__(self,):
return self._root.__repr__()
def getchildren(self,):
"""ETnse overload of getchildren(root)."""
return [r.tag.replace(self._xmlns,'')
for r in self._root.getchildren()]
def findall(self,ss):
"""ETnse overload of findall(ss) with _xmlns."""
return [ETnse(r) for r in self._root.findall(self._xmlns+ss)]
def find(self,ss):
"""ETnse overload of find(ss) with _xmlns."""
rootfind = self._root.find(self._xmlns+ss)
if rootfind is None:
return None
else:
return ETnse(rootfind)
def check_ssend_flg(stts,ends):
"""Check the starts are aligned, then if the starts/ends overlap."""
if not all([s0<=s1 for s0,s1 in zip(stts[:-1],stts[1:])]):
return False
else:
return all([e<=s for s,e in zip(stts[1:],ends[:-1])])
def contiguous_duplicates(stts,ends,vals,nomps,dlo,dhi,):
"""Create a contiguous equivalent outage when there is a stepped curve.
Stts, ends must be such that we can just take the difference of these
and multiply by 'val' to get the output.
Inputs
---
stts, ends - start & end times
vals - the power values between start and end times
nomps - the nominal power of the device
Returns
---
vvl - the equivalent loading level, in units of vals/nomps (MW likely)
"""
if not check_ssend_flg(stts,ends):
print('A clash in the non-unique APs in contiguous duplicates!')
return np.nan, np.nan
dt = dhi - dlo
ends_ = npa([min(e,dhi) for e in ends])
stts_ = npa([max(e,dlo) for e in stts])
return ((ends_-stts_)/dt).dot(vals)
def minmax_reconciliation(stts,ends,vals,nomps,dlo,dhi,):
"""Find the maximum and minimum possible availabilities of generators.
Used when other methods have failed.
NB: assumes one minute time resolution.
"""
dt = timedelta(0,60,)
nt = (dhi-dlo)//dt
vmat = np.nan*np.ones((len(stts),nt,))
i0s = [max(0, (s-dlo)//dt) for s in stts]
i1s = [min((dhi-dlo)//dt,(s-dlo)//dt) for s in ends]
# Assign the values to vmat
_ = [vmat[ii].__setitem__(slice(i0,i1),v)
for ii,(i0,i1,v) in enumerate(zip(i0s,i1s,vals))]
# Create the max and min versions of the output
vmax, vmin = [np.nanmin(np.c_[np.ones(nt)*nomps, mnmx(vmat,axis=0)],axis=1)
for mnmx in [np.nanmax,np.nanmin]]
return np.mean(vmax), np.mean(vmin)
def load_aps(cc,sd,rerun=True,save=False,):
"""Load the availability periods list APs for country cc.
Method:
- Initialise a dict for storing the information (APs)
- Read each entry of the zipped XML data
- Append each generator with an outage at the relevant datetime kk
Note that the keys for the dict kk are in UTC, where the dates that are
saved in the outage files are in local time; so, the datetime of the keys
do NOT match up with the datetimes of the saved zip files.
Inputs
---
cc - country to load
sd - save directory
rerun - if False, then simply load the data from
Returns
---
APs - the availability period dict-of-dicts for reports
mm - dict of all mmRids of the generators
kks - string format of kksD as a key for APs
kksD - the sorted start datetimes of all of the APs keys
"""
ld_ = os.path.join(sd,'outage_data')
sd_ = os.path.join(sd,'output_cache','APs',)
_ = os.mkdir(sd_) if not os.path.exists(sd_) else None
fn_ = os.path.join(sd_,f'{cc}_APs.pkl')
# If not rerun, reload the cached data and return
if not rerun:
with open(fn_,'rb') as file:
data = pickle.load(file)
print(data['readme'])
return data['APs'], data['mm'], data['kks'], data['kksD']
t0 = timer()
ap2clk = lambda ap,ss: datetime.fromisoformat(
ap.find('timeInterval').find(ss).text.replace('Z',':00'))
# Approach: a day has a list of mRIDs. If a mRID does not have it's key
# information in mRIDdict, then this is added. Then, for each availability
# period, the data is saved.
mm = {} # mRIDmaster dict
print(f'Loading {cc} APs...')
fns = get_path_files(os.path.join(ld_,cc))
APs = {} # each file
with Bar('Load APs', suffix='%(percent).1f%% - %(eta)ds',
max=len(fns)) as bar:
for fn in fns:
# First check the zip file is a zip file and not an error .txt
if not zipfile.is_zipfile(fn):
# Double check this is an xml text file, as expected
with open(fn,'r') as ff:
ET.XML(ff.read())
bar.next()
continue
# This finds the dict key as the date
kk_ = fn.split('_')[-3]
kk = get_utc_kk(kk_,cc,)
# If not existing yet, add new one.
if kk not in APs.keys():
APs[kk] = {}
with zipfile.ZipFile(fn, 'r') as zip_ref:
for zr in zip_ref.infolist():
# Get an XML representation of the entry
root = ET.XML(zip_ref.read(zr))
rr = ETnse(root)
ts = rr.find('TimeSeries')
aps = ts.findall('Available_Period')
# Update mm
id = ts.find(APs0).text
if id not in mm.keys():
mm[id] = {}
for k,v in mridData.items():
try:
mm[id][k] = ts.find(v).text
except:
mm[id][k] = None
if not (id in APs[kk].keys()):
APs[kk][id] = []
ds = None if rr.find('docStatus') is None \
else rr.find('docStatus').find('value').text
APs[kk][id].append(
{
'createdDateTime':datetime.fromisoformat(
rr.find('createdDateTime').text[:-1]),
'docStatus':ds,
'businessType':ts.find('businessType').text,
'revisionNumber':int(rr.find('revisionNumber').text),
'changes':'CHANGES' in zr.filename,
'data':[{
'start':ap2clk(ap,'start'),
'end':ap2clk(ap,'end'),
'val':float(ap.find('Point').find('quantity').text),
} for ap in aps]
}
)
bar.next()
print(f'APs for {cc} loaded.')
# Build a linearly increasing clock and dates
kksD = np.sort(np.array([s2d(kk) for kk in APs.keys()]))
kks = [d2s(kk) for kk in kksD]
# Finally, if we are saving the data, put in a dict and save
if save:
nl = '\n'
readme = f'{cc} APs created at {datetime.today().isoformat()}{nl}'\
+ f'- Start date: {min(APs.keys())}{nl}'\
+ f'- End date: {max(APs.keys())}{nl}'\
+ f'- Time taken to build: {timer() - t0:1g}s{nl}{nl}'\
+ f'See help(eomf.load_aps) for description of contents.{nl}'
with open(fn_,'wb') as file:
pickle.dump({'APs':APs,'mm':mm,'kks':kks,
'kksD':kksD,'readme':readme},file)
return APs, mm, kks, kksD
def load_dps(dstart,dend,cc,sd,rerun=True,save=False,ei=True,):
"""Block process the APs to find the dps values for each country.
Inputs: see help(eomf.load_aps) for inputs / help(eomf.block_process_aps)
The bulk of the work is done by "block_process_aps" which, in-turn,
calls "process_aps" for each of the hourly time periods.
This also saves moX, moXx. Load these with using load_mouts.
Returns
---
drange - the clock
dpsX - the forced / planned / total outages min additional outages
dpsXx - the forced / planned / total outages max additional outages
dpsXr - the 'real' forced / planned / total outages (as in PMAPS)
"""
sd_ = os.path.join(sd,'output_cache','DPs',)
_ = os.mkdir(sd_) if not os.path.exists(sd_) else None
fn_ = os.path.join(sd_,f'{cc}_APs{d2s(dstart)}-{d2s(dend)}.pkl')
dps2dpsXr = lambda dpsX, dpsXx: {k:dpsX[k] + 0.5*dpsXx[k] \
for k in ['p','f','t',]}
# If not rerun, reload the cached data and return
if not rerun:
with open(fn_,'rb') as file:
data = pickle.load(file)
print(data['readme'])
rtns = [data[k] for k in ['drange','dpsX','dpsXx',]]
return rtns + [dps2dpsXr(data['dpsX'],data['dpsXx'],),]
print(f'========== Processing {cc} APs...')
APs, mm, kks, kksD = load_aps(cc,sd,rerun=False,save=False)
# Load in the PNG dict for more up-to-date generator data
fns = [fn for fn in get_path_files(os.path.join(sd,'png',cc,))
if '2020-12-01.csv' in fn]
heads, datas = listT([csvIn(fn) for fn in fns])
assert(all([heads[0]==h for h in heads]))
idxM,idxP = [heads[0].index(h) for h in ['mRID','nomP']]
pngNomP = {d[idxM]:float(d[idxP]) for data in datas for d in data}
# Checksum if wanted; then, update mm nomP to the new values
neqs = [(mm[k]['nomP'],pngNomP.get(k,-1)) for k in mm.keys() \
if mm[k]['nomP']!=str(int(pngNomP.get(k,-1)))]
_ = [mm[k].__setitem__('nomP',pngNomP.get(k,mm[k]['nomP']))
for k in mm.keys()]
# Run!
t0 = timer()
drange,dpsX,dpsXx,moX,moXx \
= block_process_aps(dstart,dend,kksD,APs,mm,kks,ei=ei,)
if save:
nl = '\n'
readme = f'{cc} DPS created at {datetime.today().isoformat()}{nl}'\
+ f'- Exclude intermittent generation: {ei}{nl}'\
+ f'- Start date: {dstart}{nl}'\
+ f'- End date: {dend}{nl}'\
+ f'- Time taken to build: {timer() - t0:1g}s{nl}'
with open(fn_,'wb') as file:
pickle.dump({'drange':drange,'dpsX':dpsX,'dpsXx':dpsXx,
'readme':readme},file)
with open(fn_.replace('.pkl','_ivdl.pkl'),'wb') as file:
pickle.dump({'drange':drange,'moX':moX,'moXx':moXx,
'readme':readme},file)
return drange, dpsX, dpsXx, dps2dpsXr(dpsX,dpsXx,)
def load_mouts(dstart,dend,cc,sd,):
"""Load the individual generator outputs moF, moP.
The data for this is saved in eomf.load_dps (with 'rerun' & 'save' on).
NB: the order returned is Planned THEN Forced.
Returns
---
drange - the datetimes in moF, moP
moX - the planned/forced/total outages
moXx - the planned/forced/total possible additional outages
mo2x - util func for converting moX, moXx to time series
mo2x_real - as mo2x except only has the definition in the pmaps paper.
"""
sd_ = os.path.join(sd,'output_cache','DPs',)
fn_ = os.path.join(sd_,f'{cc}_APs{d2s(dstart)}-{d2s(dend)}_ivdl.pkl')
with open(fn_,'rb') as file:
data = pickle.load(file)
print(data['readme'])
dout = [data[k] for k in ['drange','moX','moXx',]]
def mo2x(k):
"""Convert the sparse moP, moF representation to a full time series.
Defined in the eomf.load_mouts function to use the correct dict/drange.
Note - uses the earlier definition, where 'the' outages in the first
three columns are the minimum value
Input:
mmrid - generator key for moF/moP/moT.
Returns:
xx - (nt,6)-sized np array, with ith row as [p,f,t,pX,fX,tX]
"""
xx = np.zeros((len(dout[0]),6))
xvals = [dout[ii][j] for ii in [1,2] for j in ['p','f','t',]]
_ = [[xx[:,ii].__setitem__(v[0],v[1]) for v in mo[k]]
for ii,mo in enumerate(xvals)]
return xx
def mo2x_real(k):
"""Return the (nt,3) matrix of outages for generator k using mo2x.
See help mo2x for main help on this; returns xx[:,:3] + 0.5*xx[:,3:]
"""
xx = mo2x(k)
return npa(xx[:,:3]) + 0.5*xx[:,3:]
return dout + [mo2x,mo2x_real]
def process_aps(APsK,dlo,dhi,mm,excl_intermittent=True,):
"""Use APs to find the forced and unforced outages.
This is the core of the method for determining country-level outages.
Approach.
---
-> First, remove any reports which do not have good doc status ('A09' -
see [1], 'A.8. DocStatus'),
-> All other reports are put into a single list of triplets, containing
info on (mrid, APs report no, data no).
-> All generators which only have a single report in the given time period
are first processed, with the outage value calculated by taking the
difference between the mrid's nominal power and the power at that time.
-> Note: in these cases, the outage value is taken as an average (see
get_vm0) - e.g., if the outage is at 0% for 15 mins of an hour, but
is otherwise available, then this is counted as 75%.
-> Generators which do not have just one outage are then processed:
-> Where the time periods do not overlap, the outage is simply a
weighted average, with no ambiguity.
-> For those outages which are ambiguous, the maximum and minimum
possible outages are calculated; the minimum outage is saved with
the maximum additional outage going into vvx.
Inputs
---
APsK - availabilities dict value that will be used from dlo to dhi. Is
the 'kth' item of an APs dict [which, may have only planned or
forced outages, dependent on usage].
dlo - the start time
dhi - the end time
mm - the dict of generator data
excl_intermittent - bool (to exclude intermittent in PSRTYPE_MAPPINGS_INTER)
Outputs [I think these are not independent...?]
---
vvmult - a list of multipliers (1 if outage during whole period)
vvals - the value reported in the entsoe files
nomps - the corresponding nominal power
vvx - additional outages when there are clashes.
[1] https://transparency.entsoe.eu/content/static_content/Static%20content/web%20api/Guide.html . Accessed 18/10/21
"""
# dhi = dlo+timedelta(0,1800) if dhi is None else dhi
mmRdr = list(APsK.keys())
# Util funcs - m,j,k: mRID, aps item no., report data idx
aps_mj = lambda m,j: APsK[m][j]
get_data = lambda m,j,k: APsK[m][j]['data'][k]
get_vm0 = lambda m,j,k: ( min(get_data(m,j,k)['end'],dhi) -
max(get_data(m,j,k)['start'],dlo))/(dhi - dlo)
nom2float = lambda nomP: np.nan if nomP is None else float(nomP)
# First, pull out all of data into a list (if the docStatus + dates are ok)
ap_out = []
for m in mmRdr:
# Only use generators that are not wind/solar/hydro ror
if mm[m]['psrType'] in PSRTYPE_MAPPINGS_INTER.keys()\
and excl_intermittent:
continue
for j,aps in enumerate(APsK[m]):
if aps['docStatus']!='A09':
for k,dd in enumerate(aps['data']):
if (dhi>dd['start'] and dlo<dd['end']):
if get_data(m,j,k)['val']>1.333*float(mm[m]['nomP']):
print(f'\nIgnoring {m} at {dlo} - output too high.')
continue
ap_out.append([m,j,k,])
# Find simple (unique) values records, and then duplicates
mmsel = [a[0] for a in ap_out]
unq_idxs = [i for i,m_ in enumerate(mmsel) if mmsel.count(m_)==1]
mm_nunq = list(set([m_ for m_ in mmsel if mmsel.count(m_)!=1]))
mout = [mmsel[i] for i in unq_idxs] + mm_nunq
# Build a dict of indexes for use with the non-unique generators
mm_idx_dict = mtDict(mmsel)
_ = [mm_idx_dict[a_[0]].append(i) for i,a_ in enumerate(ap_out)]
# Get the time multiplier, nom power, and AP value
vvmult = [get_vm0(*ap_out[i]) for i in unq_idxs]
vvals = [get_data(*ap_out[i])['val'] for i in unq_idxs]
nomps = [nom2float(mm[mmsel[i]]['nomP']) for i in unq_idxs]
vvx = [0]*len(unq_idxs)
# Deal with any duplicates
for nunq in mm_nunq:
# First, pull out the indexes in ap_out and nominal power
idxs = mm_idx_dict[nunq]
nomps.append(nom2float(mm[mmsel[idxs[0]]]['nomP']))
# Then, create lists of the data used to create the value:
vals, stts, ends = [[get_data(*ap_out[i])[kk] for i in idxs]
for kk in ['val','start','end']]
mults = [get_vm0(*ap_out[i]) for i in idxs]
cds = [aps_mj(*ap_out[i][:2])['createdDateTime'] for i in idxs]
chgs = [aps_mj(*ap_out[i][:2])['changes'] for i in idxs]
# Check if the starts and ends 'line up'
ssend_flg = check_ssend_flg(stts,ends)
if len(set(vals))==1 and len(set(mults))==1:
# First, if all values the same and length no ambiguity
idx = 0
vvmult.append(get_vm0(*ap_out[idxs[idx]]))
vvals.append(get_data(*ap_out[idxs[idx]])['val'])
vvx.append(0)
elif ssend_flg:
# If the starts & ends are contiguous, no ambiguity:
vvl = contiguous_duplicates(stts,ends,vals,nomps[-1],dlo,dhi)
vvmult.append(1)
vvals.append(vvl)
vvx.append(0)
else:
# Finally, if still no good, then find max / min outage rates
mx, mn = minmax_reconciliation(stts,ends,vals,nomps[-1],dlo,dhi)
vvmult.append(1)
vvals.append(mx)
vvx.append(mx-mn)
return vvmult,vvals,nomps,vvx,mout
def block_process_aps(dstart,dend,kksD,APs,mm,kks,ei=True,):
"""Block process the APs for a range of dates at half-hourly timesteps.
Inputs
---
dstart, dend - start/end dates to process
kks, kksD, APs, mm - see help(eomf.load_aps)
ei - exclude_intermittent, help(eomf.process_aps)
Returns
---
- drange - datetimes
- dpsX - the p/f/t aggregated outages
- dpsXx - the p/f/t additional potential outages
- moX - the p/f/t individual generator outages
- moXx - the p/f/t additional potential individual generator outage
"""
# Build the clocks
drange = np.arange(dstart,dend,timedelta(0,3600),dtype=object)
dr_pair = np.c_[drange,np.r_[drange[1:],dend]]
# Get forced and planned outages,
APsP = {kk:{k:[v for v in d if v['businessType']=='A53']
for k,d in dd.items()} for kk,dd in APs.items()}
APsF = {kk:{k:[v for v in d if v['businessType']=='A54']
for k,d in dd.items()} for kk,dd in APs.items()}
APsX = {'p':APsP,'f':APsF,'t':APs}
pft = ['p','f','t',]
with Bar('Process APs', suffix='%(percent).1f%% - %(eta)ds',
max=len(dr_pair)) as bar:
dpsX,dpsXx = [{k:np.zeros(len(drange)) for k in pft} for i in range(2)]
moX, moXx = [{k:mtDict(mm,) for k in pft} for i in range(2)]
for i,(dlo,dhi) in enumerate(dr_pair):
# First check there is data for the period
clk_i = np.abs((dlo-kksD)//timedelta(1))
if sum(clk_i==0)<1:
if sum((clk_i==1))==2:
print(f'\nAmbiguous datetime {dlo} (i = {i}). Using earlier date.\n')
else:
print(f'No data for {dlo} (i = {i}). leaving as zero.\n')
continue
# If there is, pull out the data for that date.
isel_kk = np.argmin(clk_i)
for fpt in pft:
vvmult,vvals,nomps,vvx,mout = \
process_aps(APsX[fpt][kks[isel_kk]],dlo,dhi,mm,ei,)
# Update the dict of generator outages
dout = npa(vvmult)*(npa(nomps) - npa(vvals))
_ = [moX[fpt][m].append([i,d]) for m,d in zip(mout,dout)]
_ = [moXx[fpt][m].append([i,vx]) for m,vx in zip(mout,vvx)
if vx!=0]
# Calculate the output
dpsX[fpt][i] = sum(dout)
dpsXx[fpt][i] = sum(vvx) # vvmult=1 for times by construction
bar.next()
return drange, dpsX, dpsXx, moX, moXx
# Force the dict order
genXmlData = odict({
'mrid':['registeredResource.mRID',],
'name':['registeredResource.name'],
'gType':['MktPSRType','psrType'], # generation type
'cap':['Period','Point','quantity',],
'unit':['quantity_Measure_Unit.name',],
'tStt':['Period','timeInterval','start',],
'tEnd':['Period','timeInterval','end',],
})
def find_recur(ts,flist):
"""Recursively go through xml element ts using 'find' on flist list."""
if len(flist)==1:
# If final element, return data
return ts.find(flist[0]).text
else:
# Otherwise call again
return find_recur(ts.find(flist[0]),flist[1:])
def process_icppu(r):
"""Process the ICPPU data to create a table for a given year."""
root = ETnse(ET.XML(r.content.decode('utf-8')))
data = []
tss = root.findall('TimeSeries')
for ts in root.findall('TimeSeries'):
data.append([find_recur(ts,v) for v in genXmlData.values()])
head = list(genXmlData.keys())
return head,data
# getOutageUrl and getOutageData for entsoeOutageDownload
def getOutageUrl(code,d0,d1,offset_flag_i,):
"""Get the url for outage data from d0 to d1.
If offset_flag_i is None, then no offset, else offset of 200*offset_flag_i
"""
if offset_flag_i is None:
url = getUrl('unvblGp',code,2018,opts=None)
else:
url = getUrl('unvblGp',code,2018,opts=[f'offset={200*offset_flag_i}'])
url = url.replace('2018010100',d2s(d0),)
url = url.replace('2019010100',d2s(d1),)
return url
def getOutageData(code,d,dT,N=1,allow_retry=True,):
"""Get the dates, urls, results and status codes for day d and N splits."""
urls, rs, scs = mtList(3)
for i in range(N):
offset_flag_i = i if N>1 else None
urls.append(getOutageUrl( code,d,d+dT,offset_flag_i ))
rs.append(reqData(urls[i]))
scs.append(rs[i].status_code)
# Have one timeout retry
if any([sc==401 for sc in scs]) and allow_retry:
print('401 returned, try again in 5 seconds.')
time.sleep(5)
urls,rs,scs = getOutageData(code,d,dT,N,allow_retry=False)
return urls,rs,scs
# FUNCTIONS for entsoeProductionDownload.py
# First get the data common to all units
common_set = odict({
'bz':['biddingZone_Domain.mRID'],
'impl_date':['implementation_DateAndOrTime.date'],
'rr_mrid':['registeredResource.mRID'],
'rr_name':['registeredResource.name'],
'rr_loc':['registeredResource.location.name'],
'rr_psrType':['MktPSRType','psrType',],
})
unit_set = odict({
'mRID':['mRID'],
'name':['name'],
'loc':['generatingUnit_Location.name'],
'psrType':['generatingUnit_PSRType.psrType'],
'nomP':['nominalP'],
# 'unit':'nominalP', # is an attrib rather than text
})
unit_head = list(unit_set.keys()) + ['unit'] + list(common_set.keys())