-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
energy_production_from_fossil_fuels.py
442 lines (400 loc) · 10.8 KB
/
energy_production_from_fossil_fuels.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
"""Script to create a snapshot of dataset 'Energy production from fossil fuels'."""
import json
import re
import sys
from pathlib import Path
from time import sleep
from typing import List
import click
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
from owid.datautils import dataframes
from tqdm.auto import tqdm
from etl.snapshot import add_snapshot
# Version for current snapshot dataset.
SNAPSHOT_VERSION = Path(__file__).parent.name
# Time (in seconds) to wait between consecutive queries.
TIME_BETWEEN_QUERIES = 1
# Maximum number of countries to fetch in each query.
MAX_NUM_COUNTRIES_PER_QUERY = 10
# Parameters for query.
SHIFT_URL = "https://www.theshiftdataportal.org/"
ENERGY_UNIT = "TWh"
# First year with data (make it any older year than 1900, in case they have data before this year).
START_YEAR = 1900
# Last year with data (make it an arbitrary future year, in case they have recent data).
END_YEAR = 2100
# List of energy sources.
ENERGY_SOURCES = ["coal", "gas", "oil"]
# List of countries and regions.
SHIFT_COUNTRIES = [
"Afghanistan",
"Africa",
"Albania",
"Algeria",
"American Samoa",
"Angola",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Asia and Oceania",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Brazil",
"British Virgin Islands",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burma",
"Burundi",
"Cambodia",
"Cameroon",
"Canada",
"Cape Verde",
"Cayman Islands",
"Central African Republic",
"Central and South America",
"Chad",
"Chile",
"China",
"Colombia",
"Comoros",
"Congo",
"Cook Islands",
"Costa Rica",
"Croatia",
"Cuba",
"Cyprus",
"Czech republic",
"Czechia",
"Czechoslovakia",
"Democratic Republic of the Congo",
"Denmark",
"Djibouti",
"Dominica",
"Dominican Republic",
"EU28",
"Ecuador",
"Egypt",
"El Salvador",
"Equatorial Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Eurasia",
"Europe",
"Faeroe Islands",
"Falkland Islands (Malvinas)",
"Fiji",
"Finland",
"France",
"French Guiana",
"French Polynesia",
"Gabon",
"Gambia",
"Georgia",
"Germany",
"Ghana",
"Gibraltar",
"Greece",
"Greenland",
"Grenada",
"Guadeloupe",
"Guam",
"Guatemala",
"Guinea",
"Guinea-Bissau",
"Guyana",
"Haiti",
"Honduras",
"Hong Kong Special Administrative Region (China)",
"Hungary",
"Iceland",
"Inde",
"India",
"Indonesia",
"Iran",
"Iraq",
"Ireland",
"Israel",
"Italy",
"Ivory Coast",
"Jamaica",
"Japan",
"Jordan",
"Kazakhstan",
"Kenya",
"Kiribati",
"Kosovo",
"Kuwait",
"Kyrgyzstan",
"Laos",
"Latvia",
"Lebanon",
"Lesotho",
"Liberia",
"Libya",
"Lithuania",
"Luxembourg",
"Macao Special Administrative Region (China)",
"Macedonia",
"Madagascar",
"Malawi",
"Malaysia",
"Maldives",
"Mali",
"Malta",
"Martinique",
"Mauritania",
"Mauritius",
"Mexico",
"Middle East",
"Moldova",
"Mongolia",
"Montenegro",
"Montserrat",
"Morocco",
"Mozambique",
"NZ",
"Namibia",
"Nauru",
"Nepal",
"Netherlands",
"Netherlands Antilles",
"New Caledonia",
"New Zealand",
"Nicaragua",
"Niger",
"Nigeria",
"Niue",
"North America",
"North Korea",
"Northern Mariana Islands",
"Norway",
"OECD",
"OPEC",
"Oman",
"Pakistan",
"Palestinian Territories",
"Panama",
"Papua New Guinea",
"Paraguay",
"Persian Gulf",
"Peru",
"Philippines",
"Poland",
"Portugal",
"Puerto Rico",
"Qatar",
"Reunion",
"Romania",
"Russian Federation & USSR",
"Rwanda",
"Saint Helena",
"Saint Kitts and Nevis",
"Saint Lucia",
"Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines",
"Samoa",
"Sao Tome and Principe",
"Saudi Arabia",
"Senegal",
"Serbia",
"Seychelles",
"Sierra Leone",
"Singapore",
"Slovakia",
"Slovenia",
"Solomon Islands",
"Somalia",
"South Africa",
"South Korea",
"South Sudan",
"Spain",
"Sri Lanka",
"Sudan",
"Suriname",
"Swaziland",
"Sweden",
"Switzerland",
"Syria",
"Taiwan",
"Tajikistan",
"Tanzania",
"Thailand",
"Timor-Leste",
"Togo",
"Tonga",
"Trinidad and Tobago",
"Tunisia",
"Turkey",
"Turkmenistan",
"Turks and Caicos Islands",
"U.S. Pacific Islands",
"U.S. Territories",
"Uganda",
"Ukraine",
"United Arab Emirates",
"United Kingdom",
"United States Virgin Islands",
"United States of America",
"Uruguay",
"Uzbekistan",
"Vanuatu",
"Venezuela",
"Viet Nam",
"Wake Island",
"Western Sahara",
"World",
"Yemen",
"Yugoslavia",
"Zambia",
"Zimbabwe",
]
def prepare_query_url(energy_source: str, countries: List[str]) -> str:
"""Prepare a query URL to request data for a specific energy source and a list of countries.
Parameters
----------
energy_source : str
Name of energy source (e.g. "coal").
countries : list
Countries to include in the query.
Returns
-------
query_url : str
Query URL to use to request data.
"""
# Prepare a query url for request.
query_url = (
f"{SHIFT_URL}energy/{energy_source}?chart-type=line&chart-types=line&chart-types=ranking&"
f"disable-en=false&energy-unit={ENERGY_UNIT}"
)
# Add each country to the url.
for country in countries:
query_url += f"&group-names={country.replace(' ', '%20').replace('&', '%26')}"
# Add some conditions to the query (not all of them may be necessary).
query_url += (
f"&is-range=true&dimension=total&end={END_YEAR}&start={START_YEAR}&multi=true&type=Production&"
f"import-types=Imports&import-types=Exports&import-types=Net%20Imports"
)
return query_url
def fetch_data_for_energy_source_and_a_list_of_countries(energy_source: str, countries: List[str]) -> pd.DataFrame:
"""Fetch data from Shift for a specific energy source and a list of countries.
Parameters
----------
energy_source : str
Name of energy source (e.g. "coal").
countries : list
Countries to include in the query.
Returns
-------
df : pd.DataFrame
Shift data.
"""
query_url = prepare_query_url(energy_source=energy_source, countries=countries)
soup = BeautifulSoup(requests.get(query_url).content, "html.parser")
data = json.loads(
soup.find(
"script",
{"type": "application/json", "id": re.compile(r"^((?!tb-djs).)*$")},
).string # type: ignore
)
fields = data["props"]["apolloState"]
elements = {} # type: ignore
years = []
for key in list(fields):
if (ENERGY_UNIT in key) and ("name" in fields[key]) and ("data" in fields[key]):
if fields[key]["name"] in countries:
elements[fields[key]["name"]] = fields[key]["data"]["json"]
if (ENERGY_UNIT in key) and ("categories" in fields[key]):
years = fields[key]["categories"]["json"]
assert all([len(elements[country]) == len(years) for country in elements])
# Use years as index and elements (data for each country) as columns.
df = pd.DataFrame(elements, index=years)
# Rearrange dataframe for convenience.
df = df.reset_index().rename(columns={"index": "year"}).astype({"year": int})
return df
def fetch_all_data_for_energy_source(energy_source: str) -> pd.DataFrame:
"""Fetch all data for a specific energy source and all countries.
The list of countries is defined above, in SHIFT_COUNTRIES.
Parameters
----------
energy_source : str
Name of energy source (e.g. "coal").
Returns
-------
combined : pd.DataFrame
Data for a specific energy source and all countries.
"""
# Split list of countries in smaller chunks to avoid errors when requesting data.
n_chunks = int(len(SHIFT_COUNTRIES) / MAX_NUM_COUNTRIES_PER_QUERY) + 1
# Create chunks of country names.
countries_chunks = np.array_split(SHIFT_COUNTRIES, n_chunks)
dfs = []
for countries_chunk in tqdm(countries_chunks, desc="Subset of countries", file=sys.stdout):
# Fetch data for current chunk of countries and specified energy source.
df = fetch_data_for_energy_source_and_a_list_of_countries(
energy_source=energy_source,
countries=countries_chunk, # type: ignore
)
# Wait between consecutive requests.
sleep(TIME_BETWEEN_QUERIES)
# Collect data for current chunk of countries.
dfs.append(df)
# Combine dataframes of all chunks of countries into one dataframe.
combined = dataframes.multi_merge(dfs=dfs, on="year", how="outer")
# Restructure dataframe conveniently.
combined = combined.melt(id_vars="year", value_name=energy_source, var_name="country")
combined = combined.sort_values(["country", "year"]).reset_index(drop=True)
return combined
def fetch_all_data_for_all_energy_sources() -> pd.DataFrame:
"""Fetch all Shift data for all energy sources and all countries.
The list of energy sources and countries are defined above, in ENERGY_SOURCES and SHIFT_COUNTRIES, respectively.
Returns
-------
energy_data : pd.DataFrame
Energy data for all energy sources and countries specified above.
"""
energy_dfs = []
for energy_source in tqdm(ENERGY_SOURCES, desc="Energy source", file=sys.stdout):
# Fetch all data for current energy source.
energy_df = fetch_all_data_for_energy_source(energy_source=energy_source)
energy_dfs.append(energy_df)
# Combine data from different energy sources.
energy_data = dataframes.multi_merge(energy_dfs, on=["country", "year"], how="outer")
# Create index.
energy_data = energy_data.set_index(["country", "year"], verify_integrity=True).sort_index()
return energy_data
@click.command()
@click.option(
"--upload/--skip-upload",
default=True,
type=bool,
help="Upload dataset to Snapshot",
)
def main(upload: bool) -> None:
# Download all data from Shift as a dataframe.
energy_data = fetch_all_data_for_all_energy_sources()
# Create a new snapshot.
add_snapshot(
uri=f"shift/{SNAPSHOT_VERSION}/energy_production_from_fossil_fuels.csv", dataframe=energy_data, upload=upload
)
if __name__ == "__main__":
main()