forked from wri/global-power-plant-database
-
Notifications
You must be signed in to change notification settings - Fork 0
/
powerplant_database.py
1424 lines (1229 loc) · 42.8 KB
/
powerplant_database.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
# This Python file uses the following encoding: utf-8
"""
Global Power Plant Database
A library to support open-source power sector data.
"""
import datetime
import argparse
import requests
import urllib # necessary because requests doesn't handle FTP
import pickle
import csv
import sys
import os
import sqlite3
import re
### PARAMS ###
# Folder directories
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
RAW_DIR = os.path.join(ROOT_DIR, "raw_source_files")
RESOURCES_DIR = os.path.join(ROOT_DIR, "resources")
SOURCE_DB_BIN_DIR = os.path.join(ROOT_DIR, "source_databases")
SOURCE_DB_CSV_DIR = os.path.join(ROOT_DIR, "source_databases_csv")
OUTPUT_DIR = os.path.join(ROOT_DIR, "output_database")
DIRs = {"raw": RAW_DIR, "resource": RESOURCES_DIR, "src_bin": SOURCE_DB_BIN_DIR,
"src_csv": SOURCE_DB_CSV_DIR, "root": ROOT_DIR, "output": OUTPUT_DIR}
# Resource files
FUEL_THESAURUS_DIR = os.path.join(RESOURCES_DIR, "fuel_type_thesaurus")
HEADER_NAMES_THESAURUS_FILE = os.path.join(RESOURCES_DIR, "header_names_thesaurus.csv")
COUNTRY_NAMES_THESAURUS_FILE = os.path.join(RESOURCES_DIR, "country_names_thesaurus.csv")
COUNTRY_INFORMATION_FILE = os.path.join(RESOURCES_DIR, "country_information.csv")
MASTER_PLANT_CONCORDANCE_FILE = os.path.join(RESOURCES_DIR, "master_plant_concordance.csv")
WEPP_CONCORDANCE_FILE = os.path.join(RESOURCES_DIR, "master_wepp_concordance.csv")
SOURCE_THESAURUS_FILE = os.path.join(RESOURCES_DIR, "sources_thesaurus.csv")
GENERATION_FILE = os.path.join(RESOURCES_DIR, "generation_by_country_by_fuel_2014.csv")
# Encoding
UNICODE_ENCODING = "utf-8"
NO_DATA_UNICODE = u"" # used to indicate no data for a Unicode-type attribute in the PowerPlant class
NO_DATA_NUMERIC = None # used to indicate no data for a numeric-type attribute in the PowerPlant class
NO_DATA_OTHER = None # used to indicate no data for object- or list-type attribute in the PowerPlant class
NO_DATA_SET = set([]) # used to indicate no data for set-type attribute in the PowerPlant class
### CLASS DEFINITIONS ###
class PowerPlant(object):
"""Class representing a power plant."""
def __init__(self, plant_idnr, plant_name, plant_country,
plant_owner=NO_DATA_UNICODE,
plant_nat_lang=NO_DATA_UNICODE,
plant_capacity=NO_DATA_NUMERIC,
plant_cap_year=NO_DATA_NUMERIC,
plant_source=NO_DATA_OTHER,
plant_source_url=NO_DATA_UNICODE,
plant_location=NO_DATA_OTHER,
plant_coord_source=NO_DATA_UNICODE,
plant_primary_fuel=NO_DATA_UNICODE,
plant_other_fuel=NO_DATA_SET,
plant_generation=NO_DATA_OTHER,
plant_commissioning_year=NO_DATA_NUMERIC,
plant_estimated_generation_gwh=NO_DATA_NUMERIC,
plant_wepp_id=NO_DATA_UNICODE
):
# check and set data for attributes that should be unicode
unicode_attributes = {
'idnr': plant_idnr, 'name': plant_name, 'country': plant_country,
'owner': plant_owner, 'nat_lang': plant_nat_lang,
'url': plant_source_url, 'coord_source': plant_coord_source,
'primary_fuel': plant_primary_fuel,
'wepp_id': plant_wepp_id
}
for attribute, input_parameter in unicode_attributes.iteritems():
if input_parameter is NO_DATA_UNICODE:
setattr(self, attribute, NO_DATA_UNICODE)
else:
if type(input_parameter) is unicode:
setattr(self, attribute, input_parameter)
else:
try:
setattr(self, attribute, input_parameter.decode(UNICODE_ENCODING))
except:
print("Error trying to create plant with parameter {0} for attribute {1}.".format(input_parameter, attribute))
setattr(self, attribute, NO_DATA_UNICODE)
# check and set data for attributes that should be numeric
numeric_attributes = {
'capacity': plant_capacity, 'cap_year': plant_cap_year,
'commissioning_year': plant_commissioning_year,
'estimated_generation_gwh': plant_estimated_generation_gwh
}
for attribute, input_parameter in numeric_attributes.iteritems():
if input_parameter is NO_DATA_NUMERIC:
setattr(self, attribute, NO_DATA_NUMERIC)
else:
if type(input_parameter) is float or type(input_parameter) is int:
setattr(self, attribute, input_parameter)
else:
try:
setattr(self, attribute, float(input_parameter)) # NOTE: sub-optimal; may want to throw an error here instead
except:
print("Error trying to create plant with parameter {0} for attribute {1}.".format(input_parameter, attribute))
# check and set data for attributes that should be lists
list_attributes = {'generation': plant_generation}
for attribute, input_parameter in list_attributes.iteritems():
if attribute == 'generation':
if input_parameter is NO_DATA_OTHER:
#setattr(self, attribute, [PlantGenerationObject()])
setattr(self, attribute, NO_DATA_OTHER)
elif type(input_parameter) is PlantGenerationObject:
setattr(self, attribute, [input_parameter])
else: # assume list/tuple of PlantGenerationObject
setattr(self, attribute, list(input_parameter))
elif attribute == 'other_names': # Note: Not implemented
if type(input_parameter) is NO_DATA_OTHER:
setattr(self, attribute, NO_DATA_OTHER)
else: # assume list/tuple of strings/unicode - NOTE: may want to check
setattr(self, attribute, input_parameter)
else:
setattr(self, attribute, input_parameter)
# check and set other (non-primary) fuel types
# TODO: check that fuels are valid standardized fuels
# double-check that primary fuel isn't in other fuel (avoid redundancy)
if plant_primary_fuel in plant_other_fuel:
plant_other_fuel.remove(plant_primary_fuel)
if not plant_other_fuel:
setattr(self, 'other_fuel', NO_DATA_SET.copy())
elif type(plant_other_fuel) is set:
setattr(self, 'other_fuel', plant_other_fuel)
else:
print("Error trying to create plant with fuel of type {0}.".format(plant_other_fuel))
setattr(self, 'other_fuel', NO_DATA_SET.copy())
# set data for other attributes
object_attributes = {'source': plant_source, 'location': plant_location}
for attribute, input_parameter in object_attributes.iteritems():
if attribute == 'source' and type(input_parameter) is not SourceObject:
if type(input_parameter) is str:
setattr(self, attribute, format_string(input_parameter))
elif type(input_parameter) is unicode:
setattr(self, attribute, format_string(input_parameter, encoding=None))
else:
setattr(self, attribute, NO_DATA_UNICODE)
elif attribute == 'location' and type(input_parameter) is not LocationObject:
setattr(self, attribute, LocationObject())
else: # everything OK
setattr(self, attribute, input_parameter)
def __repr__(self):
"""Representation of the PowerPlant."""
return 'PowerPlant: {0}'.format(self.idnr)
def __str__(self):
"""String representation of the PowerPlant."""
try:
s = ['{',
' id: ' + str(self.idnr),
' name: ' + str(self.name),
' primary fuel: ' + str(self.primary_fuel),
' owner: ' + str(self.owner),
' capacity: ' + str(self.capacity),
' has_location: ' + str(bool(self.location)),
'}']
return '\n'.join(s)
except:
return self.__repr__()
class MasterPlant(object):
#TODO: remove this class
def __init__(self, master_idnr, matches):
"""Plant identifier in cases of unit-level data, not plant-level."""
self.idnr = master_idnr
self.matches = matches
class SourceObject(object):
def __init__(self, name, priority, country,
url=NO_DATA_UNICODE, year=NO_DATA_NUMERIC):
"""
Class holding information about where powerplant data comes from.
Parameters
----------
name : str
Entity/ministry/department/report/dataset providing the data.
priority : int
Tier (1-5) of source updatability and format.
country : str
Country/region/scope of data source.
url : str
URL where data can be repeatably accessed.
year : int
Time when data was collected/released.
"""
self.name = name
self.country = country
self.priority = priority
self.url = url
self.year = year
class CountryObject(object):
def __init__(self, primary_name, iso_code, iso_code2,
geo_name, carma_name, iea_name, automated,
use_geo, wri_data_built_in):
"""
Class holding information on a specific country.
Parameters
----------
primary_name : str
Human-readable name.
iso_code : str
3-character ISO name.
iso_code2 : str
2-character ISO name.
geo_name : str
Name used by the Global Energy Observatory (GEODB) database.
carma_name : str
Name used by the CARMA database.
iea_name: str
Name used by the IEA statistics website.
automated : int
1 or 0 depending on automatic energy report releases.
use_geo : int
1 or 0 depending on whether GEODB is the sole source of data.
wri_data_built_in : str
3-letter ISO code of the country that the WRI-collected data should actually belong to.
"""
self.primary_name = primary_name
self.iso_code = iso_code
self.iso_code2 = iso_code2
self.geo_name = geo_name
self.carma_name = carma_name
self.iea_name = iea_name
self.automated = automated
self.use_geo = use_geo
self.wri_data_built_in = wri_data_built_in
class LocationObject(object):
def __init__(self, description=u"", latitude=None, longitude=None):
"""
Class holding information on the location (lat, lon) of a powerplant.
Parameters
----------
description : unicode
Note on how the location has been identified.
latitude : float
WGS84 (EPSG:4326)
longitude : float
WGS84 (EPSG:4326)
"""
self.description = description
self.latitude = latitude
self.longitude = longitude
def __repr__(self):
lat = self.latitude
lon = self.longitude
desc = self.description
return 'Location: lat={0}; lon={1}; desc={2}'.format(lat, lon, desc)
def __nonzero__(self):
"""Boolean checking."""
return (self.longitude is not None) and (self.latitude is not None)
class PlantGenerationObject(object):
def __init__(self, gwh=None, start_date=None, end_date=None, source=None, estimated=False):
"""
Class holding information on the generation of a powerplant.
Parameters
----------
gwh : float
Electricity generation in units of GigaWatt Hours.
start_date : datetime
Start date for the generation period.
end_date : datetime
End date for the generation period.
source : unicode
Source (URL/name) that produced the data.
estimated: boolean
Whether data is reported value or estimated from a model.
Raises
------
ValueError if `end_date` is before `start_date`.
TypeError if `start_date` or `end_date` is not a datetime.
"""
self.gwh = gwh
if type(self.gwh) is int:
self.gwh = float(self.gwh)
if type(start_date) in [type(None), datetime.date]:
self.start_date = start_date
else:
self.start_date = NO_DATA_OTHER
if type(end_date) in [type(None), datetime.date]:
self.end_date = end_date
else:
self.end_date = NO_DATA_OTHER
if type(source) is str:
setattr(self, 'source', format_string(source))
elif type(source) is unicode:
setattr(self, 'source', format_string(source, encoding=None))
else:
setattr(self, 'source', NO_DATA_UNICODE)
if type(self.start_date) != type(self.end_date):
raise TypeError('start_date and end_date must both be datetime objects or None')
if self.end_date < self.start_date:
raise ValueError('end_date must be after start_date')
if type(estimated) is bool:
self.estimated = estimated
else:
self.estimated = False
def __repr__(self):
start = None
end = None
if self.start_date:
start = self.start_date.strftime('%Y-%m-%d')
if self.end_date:
end = self.end_date.strftime('%Y-%m-%d')
return 'PlantGeneration: GWh={0}; start={1}; end={2}'.format(self.gwh, start, end)
def __str__(self):
start = None
end = None
if self.start_date:
start = self.start_date.strftime('%Y-%m-%d')
if self.end_date:
end = self.end_date.strftime('%Y-%m-%d')
s = ['{',
' GWH: ' + str(self.gwh),
' start: ' + str(start),
' end: ' + str(end),
' source: ' + str(self.source.encode(UNICODE_ENCODING)),
'}'
]
return '\n'.join(s)
def __nonzero__(self):
"""Boolean checking."""
return (self.gwh is not None) \
and (self.start_date is not None) \
and (self.end_date is not None)
@staticmethod
def create(gwh, year=None, month=None, source=None):
"""
Construct a PlantGenerationObject for a certain year or month in year.
Parameters
----------
gwh : float
Electricty generation in GigaWatt*Hour.
year : int, optional
Year the generation data corresponds to.
month : int, optional
Month the generation data corresponds to.
source : str, optional
Identifying value for the source of the generation data.
Returns
-------
PlantGenerationObject
"""
if year is None:
return PlantGenerationObject(gwh, source=source)
if year is not None and month is None:
start = datetime.date(year, 1, 1)
end = datetime.date(year, 12, 31)
return PlantGenerationObject(gwh, start, end, source)
if year is not None and month is not None:
start = datetime.date(year, month, 1)
future_month = start.replace(day=28) + datetime.timedelta(days=4)
end = future_month - datetime.timedelta(days=future_month.day)
return PlantGenerationObject(gwh, start, end, source)
else: # year is None and month is not None
return PlantGenerationObject(gwh, source=source)
def annual_generation(gen_list, year):
"""
Compute the aggregated annual generation for a certain year.
Parameters
----------
gen_list : list of PlantGenerationObject
Input generation data.
year : int
Year to aggregate data.
Returns
-------
Float if generation data is found in the year, otherwise None.
"""
year_start = datetime.date(year, 1, 1)
year_end = datetime.date(year, 12, 31)
candidates = []
if gen_list == None:
return None
for gen in gen_list:
if not gen:
continue
if gen.start_date > year_end or gen.end_date < year_start:
continue
candidates.append(gen)
if not candidates:
return None
for gen in candidates:
if (gen.end_date - gen.start_date).days in [364, 365]:
return gen.gwh
return None
### ARGUMENT PARSER ###
def build_arg_parser():
"""Parse command-line system arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--download", help="download raw files", action="store_true")
return parser.parse_args()
def download(db_name='', file_savedir_url={}, post_data={}, force=False):
"""
Fetch and download a database from an online source.
TO-DO: Trap timeout or other errors.
Parameters
----------
db_name : str
Identifying name for the database to be downloaded.
file_savedir_url : dict of {str: str}
Dict with local filepaths as keys and URL as values.
post_data: dict of {str: str}
Dict with params and values for POST request.
If not specified, use GET.
TO-DO: Extend to allow different values for each entry in file_savedir_url.
force: bool
Force the download, ignoring the required command line argument.
Returns
-------
rc : bool
True: If no download requested OR download requested and successful.
False: If download requested but no database name provided OR download
requested but failed.
"""
if not (build_arg_parser().download or force):
print(u"Using raw data file(s) saved locally.")
return True
if db_name == '':
# Incorrect behavior, since db name should be specified, so return False.
print(u"Error: Download requested but no database name specified.")
return False
print(u"Downloading {0} database...").format(db_name)
try:
for savedir, url in file_savedir_url.iteritems():
if url[0:3] == u"ftp": # ftp
urllib.urlretrieve(url, savedir)
else: # http
if post_data:
response = requests.post(url, post_data)
else:
response = requests.get(url)
with open(savedir, 'w') as f:
f.write(response.content)
except:
print(u"Error: Failed to download one or more files.")
return False
else:
print(u"...done.")
return True
### FILE PATHS ###
def make_file_path(fileType="root", subFolder="", filename=""):
"""
Construct a file path, creating the nested directories as needed.
Parameters
----------
fileType : str
Shortcut phrase for project directories. e.g. 'output', 'resource'
subFolder : str
Directory name (possibly nested) within `fileType` directory.
filename : str
File basename to append to directory path on returned filepath.
Raises
-----
KeyError if fileType is invalid (not in `DIRs`).
"""
# if path doesn't exist, create it
for key, path in DIRs.items():
if not os.path.exists(path):
os.mkdir(path)
# find/create directory and return path
try:
dst = DIRs[fileType] # get root folder
except:
raise KeyError('Invalid directory shortcut phrase <{0}>'.format(fileType))
if subFolder:
subFolder_path = os.path.normpath(os.path.join(dst, subFolder))
if not os.path.exists(subFolder_path):
os.mkdir(subFolder_path)
return os.path.normpath(os.path.join(dst, subFolder, filename))
### SOURCES ###
def make_source_thesaurus(source_thesaurus=SOURCE_THESAURUS_FILE):
"""
Get dict mapping country name to `SourceObject` for the country.
Parameters
----------
source_thesaurus : str
Filepath for the source thesaurus data.
Returns
-------
Dict of {"Country": SourceObject} pairs.
"""
with open(source_thesaurus, 'rbU') as f:
f.readline() # skip headers
csvreader = csv.DictReader(f)
source_thesaurus = {}
for row in csvreader:
source_name = row['Source Name'].decode(UNICODE_ENCODING)
source_country = row['Country/Region'].decode(UNICODE_ENCODING)
source_url = row['Link/File'].decode(UNICODE_ENCODING)
source_priority = row['Prioritization'].decode(UNICODE_ENCODING)
# TODO: get year info from other other file (download from Google Drive)
source_thesaurus[source_name] = SourceObject(name=source_name,
country=source_country, priority=source_priority,
url=source_url)
return source_thesaurus
### FUEL TYPES ###
def make_fuel_thesaurus(fuel_type_thesaurus=FUEL_THESAURUS_DIR):
"""
Get dict mapping standard fuel names to a list of alias values.
Parameters
----------
fuel_type_thesaurus : str
Filepath to the fuel thesaurus directory.
Returns
-------
Dict of {"primary fuel name": ['alt_name0', 'alt_name1', ...]}
"""
fuel_thesaurus_files = os.listdir(fuel_type_thesaurus)
fuel_thesaurus = {}
for fuel_file in fuel_thesaurus_files:
with open(os.path.join(fuel_type_thesaurus, fuel_file), 'rbU') as fin:
standard_name = fin.readline().decode(UNICODE_ENCODING).rstrip()
aliases = [x.decode(UNICODE_ENCODING).rstrip() for x in fin.readlines()]
fuel_thesaurus[standard_name] = [standard_name]
fuel_thesaurus[standard_name].extend(aliases)
return fuel_thesaurus
def standardize_fuel(fuel_instance, fuel_thesaurus, as_set=False):
"""
Get set of standardized fuel names from string of alternate names.
Parameters
----------
fuel_instance : str
Potentially non-standard fuel names separated by '/' (e.g. bitumen/sun/uranium).
fuel_thesaurus : dict
Dict returned from `make_fuel_thesaurus()`.
as_set : bool
Return set (if true) or string (if false).
Returns
-------
fuel_set : set OR string
If as_set=true: Minimum set of standard fuel names corresponding to the input string.
Returns `NO_DATA_SET` if a fuel type cannot be identified.
If as_set=false: String containing one standard fuel name corresponding to the input string.
Returns 'NO_DATA_UNICODE' is a fuel type cannot be identified.
"""
if not fuel_instance: # if fuel_instance is blank, return empty values
if as_set:
return NO_DATA_SET.copy()
else:
return NO_DATA_UNICODE
delimiter_pattern = '/| y |,| and '
if isinstance(fuel_instance, str):
fuel_instance_u = fuel_instance.decode(UNICODE_ENCODING)
elif isinstance(fuel_instance, unicode):
fuel_instance_u = fuel_instance
fuel_instance_list = re.split(delimiter_pattern,fuel_instance)
fuel_instance_list_clean = [f.strip() for f in fuel_instance_list]
fuel_set = NO_DATA_SET.copy()
for fuel in fuel_instance_list_clean:
if fuel_instance_u == NO_DATA_UNICODE:
continue
identified = False
for fuel_standard_name, fuel_synonyms in fuel_thesaurus.iteritems():
if fuel in fuel_synonyms:
fuel_set.add(fuel_standard_name)
identified = True
break
if not identified:
print(u"-Error: Couldn't identify fuel type {0}".format(fuel_instance_u))
if as_set:
# Return entire set (for other/secondary fuels)
return fuel_set
else:
# Return string of a single fuel (for primary fuel)
assert len(fuel_set) == 1
return fuel_set.pop()
### HEADER NAMES ###
def make_header_names_thesaurus(header_names_thesaurus_file=HEADER_NAMES_THESAURUS_FILE):
"""
Get a dict mapping ideal domain-specific phrases to list of alternates.
Parameters
----------
header_names_thesaurus_file : str
Filepath.
Returns
-------
Dict of {'ideal phrase': ['alt_phrase0', 'alt_phrase1', ...]}.
"""
with open(header_names_thesaurus_file, 'rbU') as f:
f.readline() # skip headers
csvreader = csv.reader(f)
header_names_thesaurus = {}
for row in csvreader:
header_primary_name = row[0]
header_names_thesaurus[header_primary_name] = [x.lower().rstrip() for x in filter(None,row)]
return header_names_thesaurus
### COUNTRY NAMES ###
def make_country_names_thesaurus(country_names_thesaurus_file=COUNTRY_INFORMATION_FILE):
"""
Get a dict mapping ideal country names to list of alternates.
Parameters
----------
country_names_thesaurus_file : str
Filepath.
Returns
-------
Dict of {'country': ['alt_country0', 'alt_country1', ...]}.
"""
with open(country_names_thesaurus_file, 'rbU') as f:
csvreader = csv.DictReader(f)
country_names_thesaurus = {}
for row in csvreader:
country_primary_name = row['primary_country_name'].decode(UNICODE_ENCODING)
country_names_thesaurus[country_primary_name] = [
row['geo_country_name'].decode(UNICODE_ENCODING),
row['carma_country_name'].decode(UNICODE_ENCODING),
row['iea_country'].decode(UNICODE_ENCODING)
]
return country_names_thesaurus
def make_country_dictionary(country_information_file=COUNTRY_INFORMATION_FILE):
"""
Get a dict mapping country name to `CountryObject`.
Parameters
----------
country_information_file : str
Filepath.
Returns
-------
Dict of {'country': CountryObject}.
"""
with open(country_information_file, 'rbU') as f:
csvreader = csv.DictReader(f)
country_dictionary = {}
for row in csvreader:
primary_name = row['primary_country_name'].decode(UNICODE_ENCODING)
country_code = row['iso_country_code'].decode(UNICODE_ENCODING)
country_code2 = row['iso_country_code_2'].decode(UNICODE_ENCODING)
automated = int(row['automated'])
use_geo = int(row['use_geo'])
wri_data_built_in = row['wri_data_built_in'].decode(UNICODE_ENCODING)
geo_name = row['geo_country_name'].decode(UNICODE_ENCODING)
carma_name = row['carma_country_name'].decode(UNICODE_ENCODING)
iea_name = row['iea_country'].decode(UNICODE_ENCODING)
new_country = CountryObject(primary_name, country_code, country_code2,
geo_name, carma_name, iea_name,
automated, use_geo, wri_data_built_in)
country_dictionary[primary_name] = new_country
return country_dictionary
def standardize_country(country_instance, country_thesaurus):
"""
Get the standard country name from a non-ideal instance.
Parameters
----------
country_instance : str
Non-ideal or alternative country name (e.g. 'United States').
country_thesaurus : dict
Dict returned by `make_country_names_thesaurus()`.
Returns
-------
country_primary_name : unicode
Standard country name (e.g. 'United States of America').
Returns `NO_DATA_UNICODE` if country cannot be identified.
"""
country_instance = country_instance.replace(",", "")
for primary_name, aliases in country_thesaurus.iteritems():
if country_instance in aliases:
return primary_name
print("Couldn't identify country {0}".format(country_instance))
return NO_DATA_UNICODE
### ID NUMBERS AND MATCHING ###
def make_id(letter_code, id_number):
"""
Make the standard-format id (3- or 5-letter alpha code, followed by 7-digit number).
Parameters
----------
letter_code : str
3-character code (e.g. USA, BRA, CHN) or 5-character source code.
id_number : int
Number less than 10-million.
Returns
-------
idnr : unicode
Alpha code followed by zero-leading 7-character numeral.
"""
return u"{alpha}{num:07d}".format(alpha=letter_code, num=id_number)
def make_plant_concordance(master_plant_condordance_file=MASTER_PLANT_CONCORDANCE_FILE):
"""
Get a dict that enables matching between the same plants from multiple databases.
Parameters
----------
master_plant_concordance_file : str
Filepath for plant concordance.
Returns
-------
Dict mapping WRI-specific ID to a dict of equivalent ids for other databases.
"""
# Note: These IDs are 'item source', not plant IDs.
with open(master_plant_condordance_file, 'rbU') as f:
csvreader = csv.DictReader(f)
plant_concordance = {}
for row in csvreader:
wri_id = make_id(u"WRI", int(row['f']))
geo_id = make_id(u"GEODB", int(row['geo_id'])) if row['geo_id'] else ""
carma_id = make_id(u"CARMA", int(row['carma_id'])) if row['carma_id'] else ""
osm_id = make_id(u"OSM", int(row['osm_id'])) if row['osm_id'] else ""
plant_concordance[wri_id] = {
'geo_id': geo_id, 'carma_id': carma_id, 'osm_id': osm_id
}
return plant_concordance
def add_wepp_id(powerplant_dictionary, wepp_matches_file=WEPP_CONCORDANCE_FILE):
"""
Set WEPP Location ID for each plant, if a match is available.
Modifies powerplant_dictionary in place.
Parameters
----------
powerplant_dictionary : dict
Dictionary of all PowerPlant objects.
wepp_concordance_file : path
Path to file with WEPP Location ID matches.
Returns
-------
None.
"""
wepp_match_count = 0
with open(wepp_matches_file, 'rbU') as f:
csvreader = csv.DictReader(f)
for row in csvreader:
# skip rows we have marked to ignore (for various reasons)
if row['ignore'] == '1':
continue
if row['wepp_location_id']:
gppd_id = str(row['gppd_idnr'])
wepp_id = str(row['wepp_location_id'])
if gppd_id in powerplant_dictionary:
# test that we haven't already set this wepp id
try:
if not powerplant_dictionary[gppd_id].wepp_id:
powerplant_dictionary[gppd_id].wepp_id = wepp_id
wepp_match_count += 1
else:
print(u"Error: Duplicate WEPP match for plant {0}".format(gppd_id))
except:
print(u"Error: plant {0} does not have wepp_id attribute".format(gppd_id))
else:
print(u"Error: Attempt to match WEPP ID {0} to non-existant plant {1}".format(wepp_id, gppd_id))
print(u"Added {0} matches to WEPP plants.".format(wepp_match_count))
### STRING CLEANING ###
def format_string(value, encoding=UNICODE_ENCODING):
"""
Format string to another representation and dissolve problem characters.
Parameters
----------
value : str
The string to parse and format.
encoding : str
Encoding to decode `value` into.
Returns
-------
clean_value : unicode
`value` stripped of control characters, commas, and trailing whitespace.
`NO_DATA_UNICODE` if problem with re-encoding.
"""
# if encoding=None, don't decode
try:
if encoding is None:
unicode_value = value
else:
unicode_value = value.decode(encoding)
clean_value = unicode_value.replace("\n", " ").replace("\r", " ").replace(",", " ").strip()
# TODO: Find better way to handle substitute characters than this:
clean_value = clean_value.replace(u"\u001A", "")
return clean_value
except:
return NO_DATA_UNICODE
### GENERATION ESTIMATION ###
def estimate_generation(powerplant_dictionary, total_generation_file=GENERATION_FILE):
"""
Function to estimate annual generation by plant.
Uses data from IEA on total national generation (2014) by fuel type.
Allocates generation among plants by capacity.
Excludes plants for which generation data are reported and included in database.
Parameters
----------
powerplant_dictionary : dict of PowerPlant objects
The power plants for which to estimate generation.
total_generation_file : file path
File with national total for annual generation, by fuel type.
Returns
-------
estimate_count : int
Number of plants for which generation was estimated.
Note
----
Plant objects in powerplant_dictionary have `plant_estimated_generation_gwh' value set after this function call.
"""
# read in generation total data (by country and fuel)
generation_totals = {}
with open(total_generation_file, 'rU') as f:
csvreader = csv.DictReader(f)
for row in csvreader:
country = row['country']
fuel = row['fuel']
gen_gwh = float(row['generation_gwh_2014'])
if country not in generation_totals:
generation_totals[country] = {}
generation_totals[country][fuel] = gen_gwh
# read in plants and sum capacity by country and fuel
capacity_totals = {}
for plantid, plant in powerplant_dictionary.iteritems():
country = plant.country
capacity = plant.capacity
if capacity == None: # TODO: catch these errors; should not occur
continue
fuel = plant.primary_fuel
# check if plant has 2014 reported generation
if plant.generation is not None:
generation_2014 = annual_generation(plant.generation, 2014)
if generation_2014 is not None:
# don't count this capacity, and do subtract this generation from country/fuel total
try:
generation_totals[country][fuel] -= generation_2014
except:
print("Warning {0}: attempt to discount fuel {1} from country {2}".format(plantid, fuel, country))
continue
# if no 2014 reported generation, add capacity to cumulative total
if country not in capacity_totals:
capacity_totals[country] = {}
fuel_cap = capacity_totals[country].get(fuel, 0)
capacity_totals[country][fuel] = fuel_cap + capacity
# now allocate remaining generation by relative capacity
estimate_count = 0
for plantid, plant in powerplant_dictionary.iteritems():
if annual_generation(plant.generation, 2014) is not None:
continue
country = plant.country
capacity = plant.capacity
if capacity == None: # TODO: catch these errors; should not occur
continue
fuel = plant.primary_fuel
try:
capacity_fraction = capacity / float(capacity_totals[country][fuel])
estimated_generation = capacity_fraction * generation_totals[country][fuel]
if estimated_generation < 0: # might happen because of subtraction step above
estimated_generation = 0
plant.estimated_generation_gwh = estimated_generation
estimate_count += 1
except:
continue
# no need to return dictionary; modifying directly
return estimate_count
### PARSE DATA RETURNED BY ELASTIC SEARCH ###
#TODO: understand this function
def parse_powerplant_data(json_data,db_source):
"""
Parse data returned by Enipedia elastic search API.
Parameters
----------
json_data : dict
???
db_source : str
???
Returns
-------
score : float
???
parsed_values : dict
???
"""