-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathbuild_shapes.py
1369 lines (1124 loc) · 46.3 KB
/
build_shapes.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
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: PyPSA-Earth and PyPSA-Eur Authors
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# -*- coding: utf-8 -*-
import multiprocessing as mp
import os
import shutil
from itertools import takewhile
from operator import attrgetter
import fiona
import geopandas as gpd
import numpy as np
import pandas as pd
import rasterio
import requests
import xarray as xr
from _helpers import (
configure_logging,
create_logger,
sets_path_to_root,
three_2_two_digits_country,
two_2_three_digits_country,
two_digits_2_name_country,
)
from numba import njit
from numba.core import types
from numba.typed import Dict
from rasterio.mask import mask
from rasterio.windows import Window
from shapely.geometry import MultiPolygon
from shapely.ops import unary_union
from shapely.validation import make_valid
from tqdm import tqdm
sets_path_to_root("pypsa-earth")
logger = create_logger(__name__)
def get_GADM_filename(country_code):
"""
Function to get the GADM filename given the country code.
"""
special_codes_GADM = {
"XK": "XKO", # kosovo
"CP": "XCL", # clipperton island
"SX": "MAF", # sint maartin
"TF": "ATF", # french southern territories
"AX": "ALA", # aland
"IO": "IOT", # british indian ocean territory
"CC": "CCK", # cocos island
"NF": "NFK", # norfolk
"PN": "PCN", # pitcairn islands
"JE": "JEY", # jersey
"XS": "XSP", # spratly
"GG": "GGY", # guernsey
"UM": "UMI", # united states minor outlying islands
"SJ": "SJM", # svalbard
"CX": "CXR", # Christmas island
}
if country_code in special_codes_GADM:
return f"gadm41_{special_codes_GADM[country_code]}"
else:
return f"gadm41_{two_2_three_digits_country(country_code)}"
def download_GADM(country_code, update=False, out_logging=False):
"""
Download gpkg file from GADM for a given country code.
Parameters
----------
country_code : str
Two letter country codes of the downloaded files
update : bool
Update = true, forces re-download of files
Returns
-------
gpkg file per country
"""
GADM_filename = get_GADM_filename(country_code)
GADM_url = f"https://geodata.ucdavis.edu/gadm/gadm4.1/gpkg/{GADM_filename}.gpkg"
GADM_inputfile_gpkg = os.path.join(
os.getcwd(),
"data",
"gadm",
GADM_filename,
GADM_filename + ".gpkg",
) # Input filepath gpkg
if not os.path.exists(GADM_inputfile_gpkg) or update is True:
if out_logging:
logger.warning(
f"Stage 5 of 5: {GADM_filename} of country {two_digits_2_name_country(country_code)} does not exist, downloading to {GADM_inputfile_gpkg}"
)
# create data/osm directory
os.makedirs(os.path.dirname(GADM_inputfile_gpkg), exist_ok=True)
try:
r = requests.get(GADM_url, stream=True, timeout=300)
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
raise Exception(
f"GADM server is down at {GADM_url}. Data needed for building shapes can't be extracted.\n\r"
)
except Exception as exception:
raise Exception(
f"An error happened when trying to load GADM data by {GADM_url}.\n\r"
+ str(exception)
+ "\n\r"
)
else:
with open(GADM_inputfile_gpkg, "wb") as f:
shutil.copyfileobj(r.raw, f)
return GADM_inputfile_gpkg, GADM_filename
def filter_gadm(
geodf,
layer,
cc,
contended_flag,
output_nonstd_to_csv=False,
):
# identify non standard geodf rows
geodf_non_std = geodf[geodf["GID_0"] != two_2_three_digits_country(cc)].copy()
if not geodf_non_std.empty:
logger.info(
f"Contended areas have been found for gadm layer {layer}. They will be treated according to {contended_flag} option"
)
# NOTE: in these options GID_0 is not changed because it is modified below
if contended_flag == "drop":
geodf.drop(geodf_non_std.index, inplace=True)
elif contended_flag != "set_by_country":
# "set_by_country" option is the default; if this elif applies, the desired option falls back to the default
logger.warning(
f"Value '{contended_flag}' for option contented_flag is not recognized.\n"
+ "Fallback to 'set_by_country'"
)
# force GID_0 to be the country code for the relevant countries
geodf["GID_0"] = cc
# country shape should have a single geometry
if (layer == 0) and (geodf.shape[0] > 1):
logger.warning(
f"Country shape is composed by multiple shapes that are being merged in agreement to contented_flag option '{contended_flag}'"
)
# take the first row only to re-define geometry keeping other columns
geodf = geodf.iloc[[0]].set_geometry([geodf.unary_union])
# debug output to file
if output_nonstd_to_csv and not geodf_non_std.empty:
geodf_non_std.to_csv(
f"resources/non_standard_gadm{layer}_{cc}_raw.csv", index=False
)
return geodf
def get_GADM_layer(
country_list,
layer_id,
geo_crs,
contended_flag,
update=False,
outlogging=False,
):
"""
Function to retrieve a specific layer id of a geopackage for a selection of
countries.
Parameters
----------
country_list : str
List of the countries
layer_id : int
Layer to consider in the format GID_{layer_id}.
When the requested layer_id is greater than the last available layer, then the last layer is selected.
When a negative value is requested, then, the last layer is requested
"""
# initialization of the geoDataFrame
geodf_list = []
for country_code in country_list:
# Set the current layer id (cur_layer_id) to global layer_id
cur_layer_id = layer_id
# download file gpkg
file_gpkg, name_file = download_GADM(country_code, update, outlogging)
# get layers of a geopackage
list_layers = fiona.listlayers(file_gpkg)
# get layer name
if (cur_layer_id < 0) or (cur_layer_id >= len(list_layers)):
# when layer id is negative or larger than the number of layers, select the last layer
cur_layer_id = len(list_layers) - 1
# read gpkg file
geodf_temp = gpd.read_file(
file_gpkg, layer="ADM_ADM_" + str(cur_layer_id), engine="pyogrio"
).to_crs(geo_crs)
geodf_temp = filter_gadm(
geodf=geodf_temp,
layer=cur_layer_id,
cc=country_code,
contended_flag=contended_flag,
output_nonstd_to_csv=False,
)
# create a subindex column that is useful
# in the GADM processing of sub-national zones
geodf_temp["GADM_ID"] = geodf_temp[f"GID_{cur_layer_id}"]
# append geodataframes
geodf_list.append(geodf_temp)
geodf_GADM = gpd.GeoDataFrame(pd.concat(geodf_list, ignore_index=True))
geodf_GADM.set_crs(geo_crs)
return geodf_GADM
def _simplify_polys(polys, minarea=0.01, tolerance=0.01, filterremote=False):
"Function to simplify the shape polygons"
if isinstance(polys, MultiPolygon):
polys = sorted(polys.geoms, key=attrgetter("area"), reverse=True)
mainpoly = polys[0]
mainlength = np.sqrt(mainpoly.area / (2.0 * np.pi))
if mainpoly.area > minarea:
polys = MultiPolygon(
[
p
for p in takewhile(lambda p: p.area > minarea, polys)
if not filterremote or (mainpoly.distance(p) < mainlength)
]
)
else:
polys = mainpoly
return polys.simplify(tolerance=tolerance)
def countries(countries, geo_crs, contended_flag, update=False, out_logging=False):
"Create country shapes"
if out_logging:
logger.info("Stage 1 of 5: Create country shapes")
# download data if needed and get the layer id 0, corresponding to the countries
df_countries = get_GADM_layer(
countries,
0,
geo_crs,
contended_flag,
update,
out_logging,
)
# select and rename columns
df_countries = df_countries[["GID_0", "geometry"]].copy()
df_countries.rename(columns={"GID_0": "name"}, inplace=True)
# set index and simplify polygons
ret_df = df_countries.set_index("name")["geometry"].map(_simplify_polys)
# there may be "holes" in the countries geometry which cause troubles along the workflow
# e.g. that is the case for enclaves like Dahagram–Angarpota for IN/BD
ret_df = ret_df.make_valid()
return ret_df
def country_cover(country_shapes, eez_shapes=None, out_logging=False, distance=0.02):
if out_logging:
logger.info("Stage 3 of 5: Merge country shapes to create continent shape")
shapes = country_shapes.apply(lambda x: x.buffer(distance))
shapes_list = list(shapes)
if eez_shapes is not None:
shapes_list += list(eez_shapes)
africa_shape = make_valid(unary_union(shapes_list))
return africa_shape
def save_to_geojson(df, fn):
if os.path.exists(fn):
os.unlink(fn) # remove file if it exists
if not isinstance(df, gpd.GeoDataFrame):
df = gpd.GeoDataFrame(dict(geometry=df))
# save file if the GeoDataFrame is non-empty
if df.shape[0] > 0:
df = df.reset_index()
schema = {**gpd.io.file.infer_schema(df), "geometry": "Unknown"}
df.to_file(fn, driver="GeoJSON", schema=schema)
else:
# create empty file to avoid issues with snakemake
with open(fn, "w") as fp:
pass
def load_EEZ(countries_codes, geo_crs, EEZ_gpkg="./data/eez/eez_v11.gpkg"):
"""
Function to load the database of the Exclusive Economic Zones.
The dataset shall be downloaded independently by the user (see
guide) or together with pypsa-earth package.
"""
if not os.path.exists(EEZ_gpkg):
raise Exception(
f"File EEZ {EEZ_gpkg} not found, please download it from https://www.marineregions.org/download_file.php?name=World_EEZ_v11_20191118_gpkg.zip and copy it in {os.path.dirname(EEZ_gpkg)}"
)
geodf_EEZ = gpd.read_file(EEZ_gpkg, engine="pyogrio").to_crs(geo_crs)
geodf_EEZ.dropna(axis=0, how="any", subset=["ISO_TER1"], inplace=True)
# [["ISO_TER1", "TERRITORY1", "ISO_SOV1", "ISO_SOV2", "ISO_SOV3", "geometry"]]
geodf_EEZ = geodf_EEZ[["ISO_TER1", "geometry"]]
selected_countries_codes_3D = [
two_2_three_digits_country(x) for x in countries_codes
]
geodf_EEZ = geodf_EEZ[
[any([x in selected_countries_codes_3D]) for x in geodf_EEZ["ISO_TER1"]]
]
geodf_EEZ["ISO_TER1"] = geodf_EEZ["ISO_TER1"].map(
lambda x: three_2_two_digits_country(x)
)
geodf_EEZ.reset_index(drop=True, inplace=True)
geodf_EEZ.rename(columns={"ISO_TER1": "name"}, inplace=True)
return geodf_EEZ
def eez(
countries,
geo_crs,
country_shapes,
EEZ_gpkg,
out_logging=False,
distance=0.01,
minarea=0.01,
tolerance=0.01,
):
"""
Creates offshore shapes by buffer smooth countryshape (=offset country
shape) and differ that with the offshore shape which leads to for instance
a 100m non-build coastline.
"""
if out_logging:
logger.info("Stage 2 of 5: Create offshore shapes")
# load data
df_eez = load_EEZ(countries, geo_crs, EEZ_gpkg)
eez_countries = [cc for cc in countries if df_eez.name.str.contains(cc).any()]
ret_df = gpd.GeoDataFrame(
{
"name": eez_countries,
"geometry": [
df_eez.geometry.loc[df_eez.name == cc].geometry.unary_union
for cc in eez_countries
],
}
).set_index("name")
ret_df = ret_df.geometry.map(
lambda x: _simplify_polys(x, minarea=minarea, tolerance=tolerance)
)
ret_df = ret_df.apply(lambda x: make_valid(x))
country_shapes_with_buffer = country_shapes.buffer(distance)
ret_df_new = ret_df.difference(country_shapes_with_buffer)
# repeat to simplify after the buffer correction
ret_df_new = ret_df_new.map(
lambda x: (
x if x is None else _simplify_polys(x, minarea=minarea, tolerance=tolerance)
)
)
ret_df_new = ret_df_new.apply(lambda x: x if x is None else make_valid(x))
# Drops empty geometry
ret_df = ret_df_new.dropna()
ret_df = ret_df[ret_df.geometry.is_valid & ~ret_df.geometry.is_empty]
return ret_df
def download_WorldPop(
country_code,
worldpop_method,
year=2020,
update=False,
out_logging=False,
size_min=300,
):
"""
Download Worldpop using either the standard method or the API method.
Parameters
----------
worldpop_method: str
worldpop_method = "api" will use the API method to access the WorldPop 100mx100m dataset. worldpop_method = "standard" will use the standard method to access the WorldPop 1KMx1KM dataset.
country_code : str
Two letter country codes of the downloaded files.
Files downloaded from https://data.worldpop.org/ datasets WorldPop UN adjusted
year : int
Year of the data to download
update : bool
Update = true, forces re-download of files
size_min : int
Minimum size of each file to download
"""
if worldpop_method == "api":
return download_WorldPop_API(country_code, year, update, out_logging, size_min)
elif worldpop_method == "standard":
return download_WorldPop_standard(
country_code, year, update, out_logging, size_min
)
def download_WorldPop_standard(
country_code,
year=2020,
update=False,
out_logging=False,
size_min=300,
):
"""
Download tiff file for each country code using the standard method from
worldpop datastore with 1kmx1km resolution.
Parameters
----------
country_code : str
Two letter country codes of the downloaded files.
Files downloaded from https://data.worldpop.org/ datasets WorldPop UN adjusted
year : int
Year of the data to download
update : bool
Update = true, forces re-download of files
size_min : int
Minimum size of each file to download
Returns
-------
WorldPop_inputfile : str
Path of the file
WorldPop_filename : str
Name of the file
"""
if country_code == "XK":
WorldPop_filename = f"kos_ppp_{year}_constrained.tif"
WorldPop_urls = [
f"https://data.worldpop.org/GIS/Population/Global_2000_2020_Constrained/2020/BSGM/KOS/{WorldPop_filename}",
f"https://data.worldpop.org/GIS/Population/Global_2000_2020_Constrained/2020/maxar_v1/KOS/{WorldPop_filename}",
]
else:
WorldPop_filename = f"{two_2_three_digits_country(country_code).lower()}_ppp_{year}_UNadj_constrained.tif"
# Urls used to possibly download the file
WorldPop_urls = [
f"https://data.worldpop.org/GIS/Population/Global_2000_2020_Constrained/2020/BSGM/{two_2_three_digits_country(country_code).upper()}/{WorldPop_filename}",
f"https://data.worldpop.org/GIS/Population/Global_2000_2020_Constrained/2020/maxar_v1/{two_2_three_digits_country(country_code).upper()}/{WorldPop_filename}",
]
WorldPop_inputfile = os.path.join(
os.getcwd(), "data", "WorldPop", WorldPop_filename
) # Input filepath tif
if not os.path.exists(WorldPop_inputfile) or update is True:
if out_logging:
logger.warning(
f"Stage 3 of 5: {WorldPop_filename} does not exist, downloading to {WorldPop_inputfile}"
)
# create data/osm directory
os.makedirs(os.path.dirname(WorldPop_inputfile), exist_ok=True)
loaded = False
for WorldPop_url in WorldPop_urls:
with requests.get(WorldPop_url, stream=True) as r:
with open(WorldPop_inputfile, "wb") as f:
if float(r.headers["Content-length"]) > size_min:
shutil.copyfileobj(r.raw, f)
loaded = True
break
if not loaded:
logger.error(f"Stage 3 of 5: Impossible to download {WorldPop_filename}")
return WorldPop_inputfile, WorldPop_filename
def download_WorldPop_API(
country_code, year=2020, update=False, out_logging=False, size_min=300
):
"""
Download tiff file for each country code using the api method from worldpop
API with 100mx100m resolution.
Parameters
----------
country_code : str
Two letter country codes of the downloaded files.
Files downloaded from https://data.worldpop.org/ datasets WorldPop UN adjusted
year : int
Year of the data to download
update : bool
Update = true, forces re-download of files
size_min : int
Minimum size of each file to download
Returns
-------
WorldPop_inputfile : str
Path of the file
WorldPop_filename : str
Name of the file
"""
WorldPop_filename = f"{two_2_three_digits_country(country_code).lower()}_ppp_{year}_UNadj_constrained.tif"
# Request to get the file
WorldPop_inputfile = os.path.join(
os.getcwd(), "data", "WorldPop", WorldPop_filename
) # Input filepath tif
os.makedirs(os.path.dirname(WorldPop_inputfile), exist_ok=True)
year_api = int(str(year)[2:])
loaded = False
WorldPop_api_urls = [
f"https://www.worldpop.org/rest/data/pop/wpgp?iso3={two_2_three_digits_country(country_code)}",
]
for WorldPop_api_url in WorldPop_api_urls:
with requests.get(WorldPop_api_url, stream=True) as r:
WorldPop_tif_url = r.json()["data"][year_api]["files"][0]
with requests.get(WorldPop_tif_url, stream=True) as r:
with open(WorldPop_inputfile, "wb") as f:
if float(r.headers["Content-length"]) > size_min:
shutil.copyfileobj(r.raw, f)
loaded = True
break
if not loaded:
logger.error(f"Stage 3 of 5: Impossible to download {WorldPop_filename}")
return WorldPop_inputfile, WorldPop_filename
def convert_GDP(name_file_nc, year=2015, out_logging=False):
"""
Function to convert the nc database of the GDP to tif, based on the work at https://doi.org/10.1038/sdata.2018.4.
The dataset shall be downloaded independently by the user (see guide) or together with pypsa-earth package.
"""
if out_logging:
logger.info("Stage 5 of 5: Access to GDP raster data")
# tif namefile
name_file_tif = name_file_nc[:-2] + "tif"
# path of the nc file
GDP_nc = os.path.join(os.getcwd(), "data", "GDP", name_file_nc) # Input filepath nc
# path of the tif file
GDP_tif = os.path.join(
os.getcwd(), "data", "GDP", name_file_tif
) # Input filepath nc
# Check if file exists, otherwise throw exception
if not os.path.exists(GDP_nc):
raise Exception(
f"File {name_file_nc} not found, please download it from https://datadryad.org/stash/dataset/doi:10.5061/dryad.dk1j0 and copy it in {os.path.dirname(GDP_nc)}"
)
# open nc dataset
GDP_dataset = xr.open_dataset(GDP_nc)
# get the requested year of data or its closest one
list_years = GDP_dataset["time"]
if year not in list_years:
if out_logging:
logger.warning(
f"Stage 5 of 5 GDP data of year {year} not found, selected the most recent data ({int(list_years[-1])})"
)
year = float(list_years[-1])
# subset of the database and conversion to dataframe
GDP_dataset = GDP_dataset.sel(time=year).drop("time")
GDP_dataset.rio.to_raster(GDP_tif)
return GDP_tif, name_file_tif
def load_GDP(
countries_codes,
year=2015,
update=False,
out_logging=False,
name_file_nc="GDP_PPP_1990_2015_5arcmin_v2.nc",
):
"""
Function to load the database of the GDP, based on the work at https://doi.org/10.1038/sdata.2018.4.
The dataset shall be downloaded independently by the user (see guide) or together with pypsa-earth package.
"""
if out_logging:
logger.info("Stage 5 of 5: Access to GDP raster data")
# path of the nc file
name_file_tif = name_file_nc[:-2] + "tif"
GDP_tif = os.path.join(
os.getcwd(), "data", "GDP", name_file_tif
) # Input filepath tif
if update | (not os.path.exists(GDP_tif)):
if out_logging:
logger.warning(
f"Stage 5 of 5: File {name_file_tif} not found, the file will be produced by processing {name_file_nc}"
)
convert_GDP(name_file_nc, year, out_logging)
return GDP_tif, name_file_tif
def generalized_mask(src, geom, **kwargs):
"Generalize mask function to account for Polygon and MultiPolygon"
if geom.geom_type == "Polygon":
return mask(src, [geom], **kwargs)
elif geom.geom_type == "MultiPolygon":
return mask(src, geom.geoms, **kwargs)
else:
return mask(src, geom, **kwargs)
def _sum_raster_over_mask(shape, img):
"""
Function to sum the raster value within a shape.
"""
# select the desired area of the raster corresponding to each polygon
# Approximation: the population is measured including the pixels
# where the border of the shape lays. This leads to slightly overestimate
# the output, but the error is limited and it enables halving the
# computational time
out_image, out_transform = generalized_mask(
img, shape, all_touched=True, invert=False, nodata=0.0
)
# calculate total output in the selected geometry
out_image[np.isnan(out_image)] = 0
out_sum = out_image.sum()
# out_sum = out_image.sum()/2 + out_image_int.sum()/2
return out_sum
def add_gdp_data(
df_gadm,
year=2020,
update=False,
out_logging=False,
name_file_nc="GDP_PPP_1990_2015_5arcmin_v2.nc",
nprocesses=2,
disable_progressbar=False,
):
"""
Function to add gdp data to arbitrary number of shapes in a country.
Inputs:
-------
df_gadm: Geodataframe with one Multipolygon per row
- Essential column ["country", "geometry"]
- Non-essential column ["GADM_ID"]
Outputs:
--------
df_gadm: Geodataframe with one Multipolygon per row
- Same columns as input
- Includes a new column ["gdp"]
"""
if out_logging:
logger.info("Stage 5 of 5: Add gdp data to GADM GeoDataFrame")
# initialize new gdp column
df_gadm["gdp"] = 0.0
GDP_tif, name_tif = load_GDP(year, update, out_logging, name_file_nc)
with rasterio.open(GDP_tif) as src:
# resample data to target shape
tqdm_kwargs = dict(
ascii=False,
unit=" geometries",
total=df_gadm.shape[0],
desc="Compute GDP ",
)
for i in tqdm(df_gadm.index, **tqdm_kwargs):
df_gadm.loc[i, "gdp"] = _sum_raster_over_mask(df_gadm.geometry.loc[i], src)
return df_gadm
def _init_process_pop(df_gadm_, df_tasks_, dict_worldpop_file_locations_):
global df_gadm, df_tasks
df_gadm, df_tasks = df_gadm_, df_tasks_
global dict_worldpop_file_locations
dict_worldpop_file_locations = dict_worldpop_file_locations_
def process_function_population(row_id):
"""
Function that reads the task from df_tasks and executes all the methods.
to obtain population values for the specified region
Inputs:
-------
row_id: integer which indicates a specific row of df_tasks
Outputs:
--------
windowed_pop_count: Dataframe containing "GADM_ID" and "pop" columns
It represents the amount of population per region (GADM_ID),
for the settings given by the row in df_tasks
"""
# Get the current task values
current_row = df_tasks.iloc[row_id]
c_code = current_row["c_code"]
window_dimensions = current_row["window_dimensions"]
transform = current_row["affine_transform"]
latlong_topleft = current_row["latlong_coordinate_topleft"]
latlong_botright = current_row["latlong_coordinate_botright"]
# Obtain the inputfile location from dict
WorldPop_inputfile = dict_worldpop_file_locations[c_code]
# get subset by country code
country_rows = df_gadm.loc[df_gadm["country"] == c_code]
np_pop_val, np_pop_xy = get_worldpop_val_xy(WorldPop_inputfile, window_dimensions)
# If no values are present in the current window skip the remaining steps
if len(np_pop_val) == 0:
return []
# get the geomask with id mappings
region_geomask, id_mapping = compute_geomask_region(
country_rows, transform, window_dimensions, latlong_topleft, latlong_botright
)
# If no values are present in the id_mapping skip the remaining steps
if len(id_mapping) == 0:
return []
# Calculate the population for each region
windowed_pop_count = sum_values_using_geomask(
np_pop_val, np_pop_xy, region_geomask, id_mapping
)
return windowed_pop_count
def get_worldpop_val_xy(WorldPop_inputfile, window_dimensions):
"""
Function to extract data from .tif input file.
Inputs:
-------
WorldPop_inputfile: file location of worldpop file
window_dimensions: dimensions of window used when reading file
Outputs:
--------
np_pop_valid: array filled with values for each nonzero pixel in the worldpop file
np_pop_xy: array with [x,y] coordinates of the corresponding nonzero values in np_pop_valid
"""
col_offset, row_offset, width, height = window_dimensions
current_window = Window(col_offset, row_offset, width, height)
# Open the file using rasterio
with rasterio.open(WorldPop_inputfile) as src:
# --- Process the pixels in the image for population data ---
# Read the gray layer (1) to get an np.array of this band
# Rasterio doesn't support lower than float32 readout
# Hence np_pop_raster will have nbytes = 4 * width * height
np_pop_raster = src.read(1, window=current_window)
# Set 'nodata' values to 0
np_pop_raster[np_pop_raster == src.nodata] = 0
# Set np_pop_xy to pixel locations of non zero values
np_pop_xy = np_pop_raster.nonzero()
# Transform to get [ x, y ] array
# np_pop_xy as 'I' (uintc), see
# https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.uintc
np_pop_xy = np.array([np_pop_xy[0], np_pop_xy[1]]).T.astype("I")
# Extract the values from the locations of non zero pixels
np_pop_valid = np_pop_raster[np_pop_xy.T[0], np_pop_xy.T[1]]
return np_pop_valid, np_pop_xy
def compute_geomask_region(
country_rows, affine_transform, window_dimensions, latlong_topleft, latlong_botright
):
"""
Function to mask geometries into np_map_ID using an incrementing counter.
Inputs:
-------
country_rows: geoDataFrame filled with geometries and their GADM_ID
affine_transform: affine transform of current window
window_dimensions: dimensions of window used when reading file
latlong_topleft: [latitude, longitude] of top left corner of the window
latlong_botright: [latitude, longitude] of bottom right corner of the window
Outputs:
--------
np_map_ID.astype("H"): np_map_ID contains an ID for each location (undefined is 0)
dimensions are taken from window_dimensions, .astype("H") for memory savings
id_result:
DataFrame of the mapping from id (from counter) to GADM_ID
"""
col_offset, row_offset, x_axis_len, y_axis_len = window_dimensions
# Set an empty numpy array with the dimensions of the country .tif file
# np_map_ID will contain an ID for each location (undefined is 0)
# ID corresponds to a specific geometry in country_rows
np_map_ID = np.zeros((y_axis_len, x_axis_len))
# List to contain the mappings of id to GADM_ID
id_to_GADM_ID = []
# Loop the country_rows geoDataFrame
for i in range(len(country_rows)):
# Set the current geometry
cur_geometry = country_rows.iloc[i]["geometry"]
latitude_min = cur_geometry.bounds[1]
latitude_max = cur_geometry.bounds[3]
# Check if bounds of geometry overlap the window
# In the following cases we can skip the rest of the loop
# If the geometry is above the window
if latitude_min > latlong_topleft[0]:
continue
# If the geometry is below the window
if latitude_max < latlong_botright[0]:
continue
# Generate a mask for the specific geometry
temp_mask = rasterio.features.geometry_mask(
[cur_geometry],
(y_axis_len, x_axis_len),
transform=affine_transform,
all_touched=True,
invert=True,
)
# Map the values of counter value to np_map_ID
np_map_ID[temp_mask] = i + 1
# Store the id -> GADM_ID mapping
id_to_GADM_ID.append([i + 1, country_rows.iloc[i]["GADM_ID"]])
if len(id_to_GADM_ID) > 0:
id_result = pd.DataFrame(id_to_GADM_ID).set_index(0)
else:
id_result = pd.DataFrame()
# Return np_map_ID as type 'H' np.ushort
# 'H' -> https://numpy.org/doc/stable/reference/arrays.scalars.html#numpy.ushort
# This lowers memory usage, note: ID has to be within the range [0,65535]
return np_map_ID.astype("H"), id_result
def sum_values_using_geomask(np_pop_val, np_pop_xy, region_geomask, id_mapping):
"""
Function that sums all the population values in np_pop_val into the correct
GADM_ID It uses np_pop_xy to access the key stored in region_geomask[x][y]
The relation of this key to GADM_ID is stored in id_mapping
Inputs:
-------
np_pop_val: array filled with values for each nonzero pixel in the worldpop file
np_pop_xy: array with [x,y] coordinates of the corresponding nonzero values in np_pop_valid
region_geomask: array with dimensions of window, values are keys that map to GADM_ID using id_mapping
id_mapping: Dataframe that contains mappings of region_geomask values to GADM_IDs
Outputs:
--------
df_pop_count: Dataframe with columns
- "GADM_ID"
- "pop" containing population of GADM_ID region
"""
# Initialize a dictionary
dict_id = Dict.empty(
key_type=types.int64,
value_type=types.int64,
)
dict_id[0] = 0
counter = 1
# Loop over ip mapping and add indices to the dictionary
for ID_index in np.array(id_mapping.index):
dict_id[ID_index] = counter
counter += 1
# Declare an array to contain population counts
np_pop_count = np.zeros(len(id_mapping) + 1)
# Calculate population count of region using a numba njit compiled function
np_pop_count = loop_and_extact_val_x_y(
np_pop_count, np_pop_val, np_pop_xy, region_geomask, dict_id
)
df_pop_count = pd.DataFrame(np_pop_count, columns=["pop"])
df_pop_count["GADM_ID"] = np.append(np.array("NaN"), id_mapping.values)
df_pop_count = df_pop_count[["GADM_ID", "pop"]]
return df_pop_count
@njit
def loop_and_extact_val_x_y(
np_pop_count, np_pop_val, np_pop_xy, region_geomask, dict_id
):
"""
Function that will be compiled using @njit (numba) It takes all the
population values from np_pop_val and stores them in np_pop_count.
where each location in np_pop_count is mapped to a GADM_ID through dict_id (id_mapping by extension)
Inputs:
-------
np_pop_count: np.zeros array, which will store population counts
np_pop_val: array filled with values for each nonzero pixel in the worldpop file
np_pop_xy: array with [x,y] coordinates of the corresponding nonzero values in np_pop_valid
region_geomask: array with dimensions of window, values are keys that map to GADM_ID using id_mapping
dict_id: numba typed.dict containing id_mapping.index -> location in np_pop_count
Outputs:
--------
np_pop_count: np.array containing population counts
"""
# Loop the population data
for i in range(len(np_pop_val)):
cur_value = np_pop_val[i]
cur_x, cur_y = np_pop_xy[i]
# Set the current id to the id at the same coordinate of the geomask
cur_id = region_geomask[int(cur_x)][int(cur_y)]
# Add the current value to the population
np_pop_count[dict_id[cur_id]] += cur_value
return np_pop_count
def calculate_transform_and_coords_for_window(
current_transform, window_dimensions, original_window=False
):
"""
Function which calculates the [lat,long] corners of the window given
window_dimensions, if not(original_window) it also changes the affine
transform to match the window.
Inputs:
-------
- current_transform: affine transform of source image
- window_dimensions: dimensions of window used when reading file
- original_window: boolean to track if window covers entire country
Outputs:
--------
A list of: [
adjusted_transform: affine transform adjusted to window
coordinate_topleft: [latitude, longitude] of top left corner of the window
coordinate_botright: [latitude, longitude] of bottom right corner of the window ]
"""
col_offset, row_offset, x_axis_len, y_axis_len = window_dimensions
# Declare a affine transformer with given current_transform
transformer = rasterio.transform.AffineTransformer(current_transform)
# Obtain the coordinates of the upper left corner of window
window_topleft_longitude, window_topleft_latitude = transformer.xy(