-
Notifications
You must be signed in to change notification settings - Fork 2
/
downstream_beneficiaries.py
1190 lines (1037 loc) · 48.1 KB
/
downstream_beneficiaries.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
"""Calculate downstream beneficiaries."""
import argparse
import collections
import glob
import logging
import math
import multiprocessing
import os
import queue
import pathlib
import shutil
import sqlite3
import threading
import time
from inspect import signature
from functools import wraps
from multiprocessing import managers
from osgeo import gdal
from osgeo import osr
import ecoshard
import numpy
from ecoshard import geoprocessing
from ecoshard.geoprocessing import routing
from ecoshard import taskgraph
gdal.SetCacheMax(2**27)
logging.basicConfig(
level=logging.DEBUG,
#filename='log.out',
format=(
'%(asctime)s (%(relativeCreated)d) %(processName)s %(levelname)s '
'%(name)s [%(funcName)s:%(lineno)d] %(message)s'))
LOGGER = logging.getLogger(__name__)
logging.getLogger('ecoshard.taskgraph').setLevel(logging.WARN)
logging.getLogger('ecoshard.geoprocessing').setLevel(logging.WARN)
FA_THRESHOLD = 10000
# Backport of https://github.com/python/cpython/pull/4819
# Improvements to the Manager / proxied shared values code
# broke handling of proxied objects without a custom proxy type,
# as the AutoProxy function was not updated.
#
# This code adds a wrapper to AutoProxy if it is missing the
# new argument.
orig_AutoProxy = managers.AutoProxy
@wraps(managers.AutoProxy)
def AutoProxy(*args, incref=True, manager_owned=False, **kwargs):
# Create the autoproxy without the manager_owned flag, then
# update the flag on the generated instance. If the manager_owned flag
# is set, `incref` is disabled, so set it to False here for the same
# result.
autoproxy_incref = False if manager_owned else incref
proxy = orig_AutoProxy(*args, incref=autoproxy_incref, **kwargs)
proxy._owned_by_manager = manager_owned
return proxy
def apply_manager_autopatch():
if "manager_owned" in signature(managers.AutoProxy).parameters:
return
LOGGER.debug(
"Patching multiprocessing.managers.AutoProxy to add manager_owned")
managers.AutoProxy = AutoProxy
# re-register any types already registered to SyncManager without a custom
# proxy type, as otherwise these would all be using the old unpatched
# AutoProxy
SyncManager = managers.SyncManager
registry = managers.SyncManager._registry
for typeid, (callable, exposed, method_to_typeid, proxytype) in \
registry.items():
if proxytype is not orig_AutoProxy:
continue
create_method = hasattr(managers.SyncManager, typeid)
SyncManager.register(
typeid,
callable=callable,
exposed=exposed,
method_to_typeid=method_to_typeid,
create_method=create_method,
)
DEM_ZIP_URL = 'https://storage.googleapis.com/global-invest-sdr-data/global_dem_3s_md5_22d0c3809af491fa09d03002bdf09748.zip'
WATERSHED_VECTOR_ZIP_URL = 'https://storage.googleapis.com/ipbes-ndr-ecoshard-data/watersheds_globe_HydroSHEDS_15arcseconds_blake2b_14ac9c77d2076d51b0258fd94d9378d4.zip'
POPULATION_RASTER_URL_MAP = {
#'2000': 'https://storage.googleapis.com/ecoshard-root/population/lspop2000_md5_79a872e3480c998a4a8bfa28feee228c.tif',
#'2017': 'https://storage.googleapis.com/ecoshard-root/population/lspop2017_md5_2e8da6824e4d67f8ea321ba4b585a3a5.tif',
#'floodplain': 'https://storage.googleapis.com/ecoshard-root/population/floodplains_masked_pop_30s_md5_c027686bb9a9a36bdababbe8af35d696.tif',
#'ssp3': 'https://storage.googleapis.com/ecoshard-root/population/lspop_ssp3_md5_0455273be50a249ca4af001ffa2c57e9.tif',
# 'canonical': 'https://storage.googleapis.com/ecoshard-root/population/canonicalpop.tif',
'2019': 'https://storage.googleapis.com/ecoshard-root/population/lspop2019_compressed_md5_d0bf03bd0a2378196327bbe6e898b70c.tif',
}
#HAB_MASK_URL = 'https://storage.googleapis.com/critical-natural-capital-ecoshards/habmasks/masked_all_nathab_esa2015_md5_50debbf5fba6dbdaabfccbc39a9b1670.tif'
HAB_MASK_URL_MAP = {
#'esa': 'https://storage.googleapis.com/ecoshard-root/ci_global_restoration/ESACCI-LC-L4-LCCS-Map-300m-P1Y-2020-v2.1.1_md5_2ed6285e6f8ec1e7e0b75309cc6d6f9f_hab_mask.tif',
#'restoration': 'https://storage.googleapis.com/ecoshard-root/ci_global_restoration/restoration_pnv0.0001_on_ESA2020_clip_md5_93d43b6124c73cb5dc21698ea5f9c8f4_hab_mask.tif'
'restoration_v2': 'https://storage.googleapis.com/ecoshard-root/ci_global_restoration/restoration_pnv0.0001_on_ESA2020_v2_md5_47613f8e4d340c92b2c481cc8080cc9d.tif',
}
WORKSPACE_DIR = 'workspace'
WATERSHED_WORKSPACE_DIR = os.path.join(WORKSPACE_DIR, 'watershed_workspace')
for dir_path in [WORKSPACE_DIR, WATERSHED_WORKSPACE_DIR]:
os.makedirs(dir_path, exist_ok=True)
N_TO_STITCH = 100
def _calculate_stream_layer(
flow_accum_raster_path, flow_dir_mfd_raster_path, fa_threshold,
outlet_raster_path, half_life, target_stream_raster_path):
"""Calculate a stream layer and merge into outlet raster."""
nodata = -1
pixel_size = geoprocessing.get_raster_info(
flow_accum_raster_path)['pixel_size'][0]
decay_rate = .5**(pixel_size/half_life)
LOGGER.debug(f'************pixel_size: {pixel_size} {half_life} {decay_rate} {pixel_size/half_life}')
directory = os.path.dirname(target_stream_raster_path)
stream_raster_path = os.path.join(
directory, f'stream_{os.path.basename(target_stream_raster_path)}')
routing.extract_streams_mfd(
(flow_accum_raster_path, 1), (flow_dir_mfd_raster_path, 1),
fa_threshold, stream_raster_path)
stream_nodata = geoprocessing.get_raster_info(
stream_raster_path)['nodata'][0]
def scale_and_merge(stream_array, outlet):
result = numpy.full(stream_array.shape, nodata, dtype=numpy.float32)
valid_mask = ~numpy.isclose(stream_array, stream_nodata)
result[valid_mask] = decay_rate
result[valid_mask] = numpy.where(
stream_array[valid_mask] > 0, 1.0, decay_rate)
result[outlet == 1] = 1.0
return result
geoprocessing.raster_calculator(
[(stream_raster_path, 1), (outlet_raster_path, 1)],
scale_and_merge, target_stream_raster_path, gdal.GDT_Float32,
nodata)
def _warp_and_wgs84_area_scale(
base_raster_path, model_raster_path, target_raster_path,
interpolation_alg, clip_bb, watershed_vector_path,
mask_vector_where_filter,
working_dir):
base_raster_info = geoprocessing.get_raster_info(base_raster_path)
model_raster_info = geoprocessing.get_raster_info(model_raster_path)
clipped_base_path = '%s_clip%s' % os.path.splitext(target_raster_path)
geoprocessing.warp_raster(
base_raster_path, base_raster_info['pixel_size'],
clipped_base_path, 'near',
target_bb=clip_bb,
vector_mask_options={
'mask_vector_path': watershed_vector_path,
'mask_vector_where_filter': mask_vector_where_filter,
},
working_dir=working_dir)
lat_min, lat_max = clip_bb[1], clip_bb[3]
_, n_rows = geoprocessing.get_raster_info(
clipped_base_path)['raster_size']
m2_area_per_lat = geoprocessing.geoprocessing._create_latitude_m2_area_column(
lat_min, lat_max, n_rows)
def _mult_op(base_array, base_nodata, scale, datatype):
"""Scale non-nodata by scale."""
result = base_array.astype(datatype)
if base_nodata is not None:
valid_mask = ~numpy.isclose(base_array, base_nodata)
else:
valid_mask = numpy.ones(
base_array.shape, dtype=bool)
result[valid_mask] = result[valid_mask] * scale[valid_mask]
return result
scaled_raster_path = os.path.join(
'%s_scaled%s' % os.path.splitext(clipped_base_path))
base_pixel_area_m2 = model_raster_info['pixel_size'][0]**2
# multiply the pixels in the resampled raster by the ratio of
# the pixel area in the wgs84 units divided by the area of the
# original pixel
base_nodata = base_raster_info['nodata'][0]
geoprocessing.raster_calculator(
[(clipped_base_path, 1), (base_nodata, 'raw'),
base_pixel_area_m2/m2_area_per_lat,
(numpy.float32, 'raw')], _mult_op,
scaled_raster_path,
gdal.GDT_Float32, base_nodata)
geoprocessing.warp_raster(
scaled_raster_path, model_raster_info['pixel_size'],
target_raster_path, 'near',
target_projection_wkt=model_raster_info['projection_wkt'],
target_bb=model_raster_info['bounding_box'],
working_dir=working_dir)
os.remove(clipped_base_path)
os.remove(scaled_raster_path)
def _create_outlet_raster(
outlet_vector_path, base_raster_path, target_outlet_raster_path):
"""Create a raster that has 1s where outlet exists and 0 everywhere else.
Args:
outlet_vector_path (str): path to input vector that has 'i', 'j'
fields indicating which pixels are outlets
base_raster_path (str): path to base raster used to create
outlet raster shape/projection.
target_outlet_raster_path (str): created by this call, contains 0s
except where pixels intersect with an outlet.
Return:
None.
"""
geoprocessing.new_raster_from_base(
base_raster_path, target_outlet_raster_path, gdal.GDT_Byte,
[0])
outlet_raster = gdal.OpenEx(
target_outlet_raster_path, gdal.OF_RASTER | gdal.GA_Update)
outlet_band = outlet_raster.GetRasterBand(1)
outlet_vector = gdal.OpenEx(outlet_vector_path, gdal.OF_VECTOR)
outlet_layer = outlet_vector.GetLayer()
one_array = numpy.ones((1, 1), dtype=numpy.int8)
for outlet_feature in outlet_layer:
outlet_band.WriteArray(
one_array,
outlet_feature.GetField('i'),
outlet_feature.GetField('j'))
outlet_band = None
outlet_raster = None
def _mask_raster(base_raster_path, mask_raster_path, target_raster_path):
"""Mask base by mask."""
base_nodata = geoprocessing.get_raster_info(
base_raster_path)['nodata'][0]
def _mask_op(base_array, mask_array):
result = numpy.full(
base_array.shape, base_nodata, dtype=numpy.float32)
valid_mask = ~numpy.isclose(base_array, base_nodata) & (mask_array == 1)
result[valid_mask] = base_array[valid_mask]
return result
geoprocessing.raster_calculator(
[(base_raster_path, 1),
(mask_raster_path, 1)], _mask_op,
target_raster_path, gdal.GDT_Float32, base_nodata)
def normalize_by_raster_sum(
raster_that_target_should_sum_to_path, base_raster_path, target_raster_path):
"""Normalize base by raster sum."""
raster_to_sum_nodata = geoprocessing.get_raster_info(
raster_that_target_should_sum_to_path)['nodata'][0]
target_sum = 0.0
for _, data_block in geoprocessing.iterblocks((raster_that_target_should_sum_to_path, 1)):
valid_mask = ~numpy.isclose(data_block, raster_to_sum_nodata)
target_sum += numpy.sum(data_block[valid_mask])
base_nodata = geoprocessing.get_raster_info(
base_raster_path)['nodata'][0]
base_sum = 0.0
for _, data_block in geoprocessing.iterblocks((base_raster_path, 1)):
valid_mask = ~numpy.isclose(data_block, base_nodata)
base_sum += numpy.sum(data_block[valid_mask])
def _div_by_sum(data_array):
result = numpy.copy(data_array)
valid_mask = ~numpy.isclose(data_array, base_nodata)
if base_sum > 0:
result[valid_mask] = data_array[valid_mask]/base_sum*target_sum
return result
geoprocessing.raster_calculator(
[(base_raster_path, 1)], _div_by_sum,
target_raster_path, gdal.GDT_Float32, base_nodata)
def div_rasters(
numerator_raster_path, denominator_raster_path, target_raster_path):
"""Normalize base by raster sum."""
numerator_nodata = geoprocessing.get_raster_info(
numerator_raster_path)['nodata'][0]
def _div_op(numerator_array, denominator_array):
result = numpy.empty(numerator_array.shape, dtype=numpy.float64)
result[:] = numerator_nodata
valid_mask = (
~numpy.isclose(numerator_array, numerator_nodata) &
(denominator_array > 0))
result[valid_mask] = numerator_array[valid_mask]/denominator_array[valid_mask]
return result
geoprocessing.raster_calculator(
[(numerator_raster_path, 1), (denominator_raster_path, 1)], _div_op,
target_raster_path, gdal.GDT_Float64, numerator_nodata)
def _sum_raster(raster_path):
"""Return the sum of the raster."""
running_sum = 0
nodata = geoprocessing.get_raster_info(raster_path)['nodata'][0]
for _, data_array in geoprocessing.iterblocks((raster_path, 1)):
if nodata is not None:
valid_mask = ~numpy.isclose(data_array, nodata)
else:
valid_mask = slice(-1)
running_sum += numpy.sum(data_array[valid_mask])
return running_sum
def rescale_by_base(base_raster_path, new_raster_path, target_raster_path):
"""Target is new * base_max/new_max."""
base_sum = _sum_raster(base_raster_path)
new_sum = _sum_raster(new_raster_path)
new_raster_info = geoprocessing.get_raster_info(new_raster_path)
new_nodata = new_raster_info['nodata'][0]
def _mult_op(new_array, scale):
"""Scale non-nodata by scale."""
result = numpy.copy(new_array)
if new_nodata is not None:
result[~numpy.isfinite(result)] = new_nodata
valid_mask = ~numpy.isclose(new_array, new_nodata)
else:
result[~numpy.isfinite(result)] = 0
valid_mask = slice(-1)
result[valid_mask] *= scale
return result
if new_sum == 0:
scale = 1.0
else:
scale = base_sum / new_sum
geoprocessing.raster_calculator(
[(new_raster_path, 1), (scale, 'raw')], _mult_op,
target_raster_path, new_raster_info['datatype'],
new_raster_info['nodata'][0])
def process_watershed(
job_id, watershed_vector_path, watershed_fid_list, epsg_code,
lat_lng_watershed_bb, dem_path,
hab_path, pop_raster_path_list, bene_half_life,
target_beneficiaries_path_list,
target_normalized_beneficiaries_path_list,
target_hab_normalized_beneficiaries_path_list,
target_flow_accum_path_list,
target_stitch_work_queue_list):
"""Calculate downstream beneficiaries for this watershed.
Args:
job_id (str): unique ID identifying this job, can be used to
create unique workspaces.
watershed_vector_path (str): path to watershed vector
watershed_fid_list (str): list of watershed ids to process
epsg_code (int): EPSG zone to locally project into
lat_lng_watershed_bb (list): lat/lng bounding box for the fids
that are in `watershed_fid_list`.
dem_path (str): path to DEM raster
hab_path (str): path to habitat mask raster
pop_raster_path_list (list): list of population rasters to route
target_beneficiaries_path_list (str): list of target downstream
beneficiary rasters to create, parallel with
`pop_raster_path_list`.
bene_half_life (float): downstream distance half-life of affected
beneficiaries.
target_normalized_beneficiaries_path_list (list): list of target
normalized downstream beneficiary rasters, parallel with other
lists.
target_hab_normalized_beneficiaries_path_list (list): list of target
hab normalized downstream beneficiary rasters, parallel with other
lists.
target_flow_accum_path_list (list): list of flow accumulation rasters
to create
target_stitch_work_queue_list (list): list of work queue tuples to
put done signals in when each beneficiary raster is done. The
first element is for the standard target, the second for the
normalized raster.
Return:
None.
"""
working_dir = os.path.join(
os.path.dirname(target_beneficiaries_path_list[0]))
os.makedirs(working_dir, exist_ok=True)
LOGGER.debug(f'create working directory for {job_id} at {working_dir}')
task_graph = taskgraph.TaskGraph(working_dir, -1)
watershed_info = geoprocessing.get_vector_info(watershed_vector_path)
epsg_sr = osr.SpatialReference()
epsg_sr.ImportFromEPSG(epsg_code)
target_watershed_bb = geoprocessing.transform_bounding_box(
lat_lng_watershed_bb,
watershed_info['projection_wkt'],
epsg_sr.ExportToWkt())
target_pixel_size = (300, -300)
warped_dem_raster_path = os.path.join(working_dir, f'{job_id}_dem.tif')
warped_habitat_raster_path = os.path.join(
working_dir, f'{job_id}_hab.tif')
LOGGER.debug(f'align and resize raster stack {job_id} at {working_dir}')
mask_vector_where_filter = (
f'"FID" in ('
f'{", ".join([str(v) for v in watershed_fid_list])})')
LOGGER.debug(mask_vector_where_filter)
align_task = task_graph.add_task(
func=geoprocessing.align_and_resize_raster_stack,
args=(
[dem_path, hab_path],
[warped_dem_raster_path, warped_habitat_raster_path],
['near', 'mode'], target_pixel_size, target_watershed_bb),
kwargs={
'target_projection_wkt': epsg_sr.ExportToWkt(),
'vector_mask_options': {
'mask_vector_path': watershed_vector_path,
'mask_vector_where_filter': mask_vector_where_filter,
},
},
target_path_list=[
warped_dem_raster_path, warped_habitat_raster_path],
task_name=(
f'align and clip and warp dem/hab to {warped_dem_raster_path} '
f'{warped_habitat_raster_path}'))
# force a drain on the watershed if its large enough
if len(watershed_fid_list) == 1:
LOGGER.debug(f'detect_lowest_drain_and_sink {job_id} at {working_dir}')
get_drain_sink_pixel_task = task_graph.add_task(
func=routing.detect_lowest_drain_and_sink,
args=((warped_dem_raster_path, 1),),
store_result=True,
dependent_task_list=[align_task],
task_name=f'get drain/sink pixel for {warped_dem_raster_path}')
edge_pixel, edge_height, pit_pixel, pit_height = (
get_drain_sink_pixel_task.get())
if pit_height < edge_height - 20:
# if the pit is 20 m lower than edge it's probably a big sink
single_outlet_tuple = pit_pixel
else:
single_outlet_tuple = edge_pixel
else:
single_outlet_tuple = None
filled_dem_raster_path = os.path.join(
working_dir, f'{job_id}_filled_dem.tif')
LOGGER.debug(f'fill_pits {job_id} at {working_dir}')
fill_pits_task = task_graph.add_task(
func=routing.fill_pits,
args=(
(warped_dem_raster_path, 1), filled_dem_raster_path),
kwargs={
'working_dir': working_dir,
'max_pixel_fill_count': -1,
'single_outlet_tuple': single_outlet_tuple},
dependent_task_list=[align_task],
target_path_list=[filled_dem_raster_path],
task_name=f'fill dem pits to {filled_dem_raster_path}')
LOGGER.debug(f'flow_dir_mfd {job_id} at {working_dir}')
flow_dir_mfd_raster_path = os.path.join(
working_dir, f'{job_id}_flow_dir_mfd.tif')
flow_dir_mfd_task = task_graph.add_task(
func=routing.flow_dir_mfd,
args=(
(filled_dem_raster_path, 1), flow_dir_mfd_raster_path),
kwargs={'working_dir': working_dir},
dependent_task_list=[fill_pits_task],
target_path_list=[flow_dir_mfd_raster_path],
task_name=f'calc flow dir for {flow_dir_mfd_raster_path}')
outlet_vector_path = os.path.join(
working_dir, f'{job_id}_outlet_vector.gpkg')
LOGGER.debug(f'detect_outlets {job_id} at {working_dir}')
detect_outlets_task = task_graph.add_task(
func=routing.detect_outlets,
args=((flow_dir_mfd_raster_path, 1), 'mfd', outlet_vector_path),
dependent_task_list=[flow_dir_mfd_task],
target_path_list=[outlet_vector_path],
task_name=f'detect outlets {outlet_vector_path}')
outlet_raster_path = os.path.join(
working_dir, f'{job_id}_outlet_raster.tif')
LOGGER.debug(f'_create_outlet_raster {job_id} at {working_dir}')
create_outlet_raster_task = task_graph.add_task(
func=_create_outlet_raster,
args=(
outlet_vector_path, flow_dir_mfd_raster_path, outlet_raster_path),
dependent_task_list=[detect_outlets_task],
target_path_list=[outlet_raster_path],
task_name=f'create outlet raster {outlet_raster_path}')
LOGGER.debug(f'create_flow_accum_raster {job_id} at {working_dir}')
flow_accum_mfd_raster_path = os.path.join(
working_dir, f'{job_id}_flow_accum_mfd.tif')
flow_accum_mfd_task = task_graph.add_task(
func=routing.flow_accumulation_mfd,
args=(
(flow_dir_mfd_raster_path, 1), flow_accum_mfd_raster_path),
dependent_task_list=[flow_dir_mfd_task],
target_path_list=[flow_accum_mfd_raster_path],
task_name=f'calc flow accum for {flow_accum_mfd_raster_path}')
flow_accum_mfd_task.join()
target_stitch_work_queue_list[0][3].put(
(flow_accum_mfd_raster_path, working_dir, job_id))
# create stream layer w/ threshold or outlet
stream_decay_raster_path = os.path.join(
working_dir, f'stream_decay_{job_id}_{bene_half_life}.tif')
stream_decay_task = task_graph.add_task(
func=_calculate_stream_layer,
args=(
flow_accum_mfd_raster_path,
flow_dir_mfd_raster_path,
FA_THRESHOLD, outlet_raster_path,
bene_half_life, stream_decay_raster_path),
dependent_task_list=[flow_accum_mfd_task, flow_dir_mfd_task],
target_path_list=[stream_decay_raster_path],
task_name=f'calc stream layer {stream_decay_raster_path}')
for (pop_raster_path, target_beneficiaries_path,
target_normalized_beneficiaries_path,
target_hab_normalized_beneficiaries_path,
stitch_queue_tuple) in zip(
pop_raster_path_list, target_beneficiaries_path_list,
target_normalized_beneficiaries_path_list,
target_hab_normalized_beneficiaries_path_list,
target_stitch_work_queue_list):
LOGGER.debug(f'processing {target_beneficiaries_path} and normalized')
aligned_pop_raster_path = os.path.join(
working_dir,
f'''{job_id}_{os.path.basename(
os.path.splitext(pop_raster_path)[0])}.tif''')
LOGGER.debug(f'_warp_and_wgs84_area_scale {job_id} at {working_dir} {target_beneficiaries_path}')
pop_warp_task = task_graph.add_task(
func=_warp_and_wgs84_area_scale,
args=(
pop_raster_path, warped_dem_raster_path,
aligned_pop_raster_path,
'near', lat_lng_watershed_bb,
watershed_vector_path, mask_vector_where_filter, working_dir),
dependent_task_list=[align_task],
target_path_list=[aligned_pop_raster_path],
task_name=f'align {aligned_pop_raster_path}')
LOGGER.debug(
f'distance_to_channel_mfd {job_id} at {working_dir} {target_beneficiaries_path}')
downstream_bene_task = task_graph.add_task(
func=routing.distance_to_channel_mfd,
args=(
(flow_dir_mfd_raster_path, 1), (outlet_raster_path, 1),
target_beneficiaries_path),
kwargs={
'weight_raster_path_band': (aligned_pop_raster_path, 1),
'decay_raster_path_band': (stream_decay_raster_path, 1)},
dependent_task_list=[
pop_warp_task, create_outlet_raster_task, flow_dir_mfd_task,
stream_decay_task],
target_path_list=[target_beneficiaries_path],
task_name=(
'calc downstream beneficiaries for '
f'{target_beneficiaries_path}'))
# TODO: roll this into a function that does the put?
downstream_bene_task.join()
stitch_queue_tuple[0].put(
(target_beneficiaries_path, working_dir, job_id))
LOGGER.debug(f'normalize_by_raster_sum {job_id} at {working_dir} {target_beneficiaries_path}')
normalize_by_pop_sum_task = task_graph.add_task(
func=normalize_by_raster_sum,
args=(
aligned_pop_raster_path,
target_beneficiaries_path,
target_normalized_beneficiaries_path),
dependent_task_list=[downstream_bene_task, align_task],
target_path_list=[target_normalized_beneficiaries_path],
task_name=(
f'normalized beneficiaries for '
f'{target_normalized_beneficiaries_path}'))
normalize_by_pop_sum_task.join()
stitch_queue_tuple[1].put(
(target_normalized_beneficiaries_path, working_dir, job_id))
LOGGER.debug(f'_mask_raster {job_id} at {working_dir} {target_beneficiaries_path}')
mask_downstream_norm_bene_task = task_graph.add_task(
func=_mask_raster,
args=(
target_normalized_beneficiaries_path,
warped_habitat_raster_path,
target_hab_normalized_beneficiaries_path),
dependent_task_list=[
normalize_by_pop_sum_task,
align_task],
target_path_list=[target_hab_normalized_beneficiaries_path],
task_name=f'mask {target_hab_normalized_beneficiaries_path}')
mask_downstream_norm_bene_task.join()
stitch_queue_tuple[2].put(
(target_hab_normalized_beneficiaries_path, working_dir, job_id))
task_graph.close()
task_graph.join()
task_graph = None
def get_completed_job_id_set(db_path):
"""Return set of completed jobs, or initialize if not set."""
if not os.path.exists(db_path):
LOGGER.debug(f'dbpath: {db_path}')
connection = sqlite3.connect(db_path)
cursor = connection.execute(
"""
CREATE TABLE completed_job_ids (
job_id TEXT NOT NULL,
PRIMARY KEY (job_id)
);
""")
cursor.close()
connection.commit()
connection.close()
cursor = None
connection = None
ro_uri = r'%s?mode=ro' % pathlib.Path(
os.path.abspath(db_path)).as_uri()
connection = sqlite3.connect(ro_uri, uri=True)
cursor = connection.execute('''SELECT * FROM completed_job_ids''')
result = set([_[0] for _ in cursor.fetchall()])
cursor.close()
connection.commit()
connection.close()
cursor = None
connection = None
return result
def job_complete_worker(
completed_work_queue, work_db_path, clean_result, n_expected):
"""Update the database with completed work.
Args:
completed_work_queue (queue): queue with (working_dir, job_id)
incoming from each stitched raster
work_db_path (str): path to the work database
clean_result (bool): if true, delete the working directory after
``n_expected`` results come through.
n_expected (int): number of expected duplicate jobs to come through
before marking complete.
Return:
``None``
"""
try:
start_time = time.time()
connection = sqlite3.connect(work_db_path)
uncommited_count = 0
processed_so_far = 0
working_jobs = collections.defaultdict(int)
global WATERSHEDS_TO_PROCESS_COUNT
LOGGER.info(f'started job complete worker, initial watersheds {WATERSHEDS_TO_PROCESS_COUNT}')
while True:
payload = completed_work_queue.get()
if payload is None:
LOGGER.info('got None in completed work, terminating')
break
working_dir, job_id = payload
working_jobs[job_id] += 1
if working_jobs[job_id] < n_expected:
continue
# we got n_expected, so mark complete
del working_jobs[job_id]
WATERSHEDS_TO_PROCESS_COUNT -= 1
if clean_result:
shutil.rmtree(working_dir, ignore_errors=True)
cursor = connection.execute(
f"""
INSERT INTO completed_job_ids VALUES ("{job_id}")
""")
cursor.close()
LOGGER.info(f'done with {job_id} {working_dir}')
uncommited_count += 1
if uncommited_count > N_TO_STITCH:
connection.commit()
processed_so_far += uncommited_count
watersheds_per_sec = processed_so_far / (time.time() - start_time)
uncommited_count = 0
remaining_time_s = (
WATERSHEDS_TO_PROCESS_COUNT / watersheds_per_sec)
remaining_time_h = int(remaining_time_s // 3600)
remaining_time_s -= remaining_time_h * 3600
remaining_time_m = int(remaining_time_s // 60)
remaining_time_s -= remaining_time_m * 60
LOGGER.info(
f'remaining watersheds to process: '
f'{WATERSHEDS_TO_PROCESS_COUNT} - '
f'processed so far {processed_so_far} - '
f'process/sec: {watersheds_per_sec:.1f} - '
f'time left: {remaining_time_h}:'
f'{remaining_time_m:02d}:{remaining_time_s:04.1f}')
connection.commit()
connection.close()
cursor = None
connection = None
except Exception:
LOGGER.exception('error on job complete worker')
raise
def general_worker(work_queue):
"""Invoke func on args coming through work queue."""
while True:
payload = work_queue.get()
if payload is None:
work_queue.put(None)
LOGGER.debug('got a none on general worker, quitting')
break
func, args = payload
process = multiprocessing.Process(
target=func, args=args)
process.start()
process.join()
def _sqrt_op(array, nodata):
result = numpy.full(array.shape, nodata, dtype=numpy.float32)
valid_array = array >= 0
result[valid_array] = numpy.sqrt(array[valid_array])
return result
def stitch_worker(
stitch_work_queue, target_stitch_raster_path,
stitch_done_queue, clean_result):
"""Take jobs from stitch work queue and stitch into target."""
stitch_buffer_list = []
done_buffer = []
n_buffered = 0
while True:
payload = stitch_work_queue.get()
if payload is None:
LOGGER.debug(f'stitch worker for {target_stitch_raster_path} got DONE signal')
stitch_work_queue.put(None)
else:
raster_path, working_dir, job_id = payload
done_buffer.append((working_dir, job_id))
if not os.path.exists(raster_path):
message = f'{raster_path} does not exist on disk when stitching into {target_stitch_raster_path} also working dir is {working_dir}'
LOGGER.error(message)
raise ValueError(message)
stitch_buffer_list.append((raster_path, 1))
n_buffered += 1
if n_buffered > N_TO_STITCH or payload is None:
LOGGER.info(
f'about to stitch {n_buffered} into '
f'{target_stitch_raster_path}')
start_time = time.time()
geoprocessing.stitch_rasters(
stitch_buffer_list, ['near']*n_buffered,
(target_stitch_raster_path, 1),
area_weight_m2_to_wgs84=True,
overlap_algorithm='replace')
for working_dir, job_id in done_buffer:
stitch_done_queue.put((working_dir, job_id))
stitch_buffer_list = []
done_buffer = []
elapsed_time = time.time() - start_time
LOGGER.info(
f'took {time.time()-start_time:.2f}s to stitch '
f'{n_buffered/elapsed_time:.2f} per sec into '
f'{target_stitch_raster_path}')
n_buffered = 0
if payload is None:
break
def main(prefix, hab_mask_url, watershed_ids=None):
"""Entry point.
Args:
watershed_ids (list): if present, only run analysis on the list
of 'watershed,fid' strings in this list.
Return:
None.
"""
LOGGER.info('create new taskgraph')
task_graph = taskgraph.TaskGraph(WORKSPACE_DIR, -1)
basename_dem = os.path.basename(os.path.splitext(DEM_ZIP_URL)[0])
dem_download_dir = os.path.join(WORKSPACE_DIR, basename_dem)
watershed_download_dir = os.path.join(
WORKSPACE_DIR, os.path.basename(os.path.splitext(
WATERSHED_VECTOR_ZIP_URL)[0]))
population_download_dir = os.path.join(
WORKSPACE_DIR, 'population_rasters')
work_db_path = os.path.join(WORKSPACE_DIR, f'{prefix}_completed_fids.db')
LOGGER.info('fetch completed job set')
completed_job_set = get_completed_job_id_set(work_db_path)
LOGGER.info(f'there are {len(completed_job_set)} completed jobs so far')
for dir_path in [
dem_download_dir, watershed_download_dir,
population_download_dir]:
os.makedirs(dir_path, exist_ok=True)
LOGGER.info('download dem')
download_dem_task = task_graph.add_task(
func=ecoshard.download_and_unzip,
args=(DEM_ZIP_URL, dem_download_dir),
target_path_list=[
os.path.join(
dem_download_dir, os.path.basename(DEM_ZIP_URL))],
task_name='download and unzip dem')
dem_tile_dir = os.path.join(dem_download_dir, 'global_dem_3s')
dem_tile_list = glob.glob(os.path.join(dem_tile_dir, '*.tif'))
dem_vrt_path = os.path.join(
dem_tile_dir,
f'{os.path.basename(os.path.splitext(DEM_ZIP_URL)[0])}.vrt')
LOGGER.debug(f'build vrt to {dem_vrt_path}')
LOGGER.info('build vrt')
task_graph.add_task(
func=_make_vrt,
args=(dem_tile_list, dem_vrt_path),
target_path_list=[dem_vrt_path],
dependent_task_list=[download_dem_task],
task_name='build dem vrt')
download_watershed_vector_task = task_graph.add_task(
func=ecoshard.download_and_unzip,
args=(WATERSHED_VECTOR_ZIP_URL, watershed_download_dir),
task_name='download and unzip watershed vector')
hab_mask_raster_path = os.path.join(
WORKSPACE_DIR, os.path.basename(hab_mask_url))
download_hab_mask_task = task_graph.add_task(
func=ecoshard.download_url,
args=(hab_mask_url, hab_mask_raster_path),
target_path_list=[hab_mask_raster_path],
task_name=f'download {hab_mask_url}')
n_stitch_rasters = 0
pop_raster_path_map = {}
stitch_raster_path_map = {}
for pop_id, pop_url in POPULATION_RASTER_URL_MAP.items():
pop_raster_path = os.path.join(
population_download_dir, os.path.basename(pop_url))
LOGGER.info(f'download {pop_url}')
download_pop_raster = task_graph.add_task(
func=ecoshard.download_url,
args=(pop_url, pop_raster_path),
target_path_list=[pop_raster_path],
task_name=f'download {pop_url}')
pop_raster_path_map[pop_id] = pop_raster_path
stitch_raster_path_map[pop_id] = [
os.path.join(WORKSPACE_DIR, f'{prefix}downstream_bene_{pop_id}_{args.bene_half_life}.tif'),
os.path.join(WORKSPACE_DIR, f'{prefix}downstream_bene_{pop_id}_{args.bene_half_life}_normalized.tif'),
os.path.join(WORKSPACE_DIR, f'{prefix}downstream_bene_{pop_id}_{args.bene_half_life}_hab_normalized.tif'),
os.path.join(WORKSPACE_DIR, f'{prefix}flow_accum_{pop_id}.tif')]
n_stitch_rasters += len(stitch_raster_path_map[pop_id])
for stitch_path in stitch_raster_path_map[pop_id]:
if not os.path.exists(stitch_path):
driver = gdal.GetDriverByName('GTiff')
cell_size = 10./3600. * 2 # do this for Nyquist theorem
n_cols = int(360./cell_size)
n_rows = int(180./cell_size)
LOGGER.info(f'**** creating raster of size {n_cols} by {n_rows}')
target_raster = driver.Create(
stitch_path,
int(360/cell_size), int(180/cell_size), 1,
gdal.GDT_Float32,
options=(
'TILED=YES', 'BIGTIFF=YES', 'COMPRESS=LZW',
'SPARSE_OK=TRUE', 'BLOCKXSIZE=256', 'BLOCKYSIZE=256'))
wgs84_srs = osr.SpatialReference()
wgs84_srs.ImportFromEPSG(4326)
target_raster.SetProjection(wgs84_srs.ExportToWkt())
target_raster.SetGeoTransform(
[-180, cell_size, 0, 90, 0, -cell_size])
target_band = target_raster.GetRasterBand(1)
target_band.SetNoDataValue(-9999)
target_raster = None
# reduce by len of pop - 1 to accoutn for us not doing flow accumulation
# for every pop value
n_stitch_rasters -= len(stitch_raster_path_map) - 1
LOGGER.info('wait for downloads to conclude')
task_graph.join()
task_graph.close()
task_graph = None
#apply_manager_autopatch()
manager = multiprocessing.Manager()
completed_work_queue = manager.Queue()
LOGGER.info('start complete worker thread')
global WATERSHEDS_TO_PROCESS_COUNT
WATERSHEDS_TO_PROCESS_COUNT = 0
# expecting 6 stitches, base, norm, habnorm times 2 pop scenarios
job_complete_worker_thread = threading.Thread(
target=job_complete_worker,
args=(
completed_work_queue, work_db_path, args.clean_result,
n_stitch_rasters))
job_complete_worker_thread.daemon = True
job_complete_worker_thread.start()
# contains work queues for regular and normalized beneficiaries
stitch_work_queue_list = []
stitch_worker_process_list = []
for target_stitch_raster_path_list in [
stitch_raster_path_map[raster_id]
for raster_id in POPULATION_RASTER_URL_MAP.keys()]:
stitch_work_queue_tuple = tuple(
[manager.Queue(N_TO_STITCH*2) for _ in range(
len(target_stitch_raster_path_list))])
stitch_work_queue_list.append(stitch_work_queue_tuple)
for stitch_work_queue, target_stitch_raster_path in zip(
stitch_work_queue_tuple, target_stitch_raster_path_list):
LOGGER.debug(f'starting a stitcher for {target_stitch_raster_path}')
stitch_worker_process = multiprocessing.Process(
target=stitch_worker,
args=(
stitch_work_queue, target_stitch_raster_path,
completed_work_queue, args.clean_result))
stitch_worker_process.deamon = True
stitch_worker_process.start()
stitch_worker_process_list.append(stitch_worker_process)
watershed_work_queue = queue.Queue()
watershed_root_dir = os.path.join(
watershed_download_dir, 'watersheds_globe_HydroSHEDS_15arcseconds')
watershed_worker_process_list = []
for _ in range(multiprocessing.cpu_count()):
watershed_worker_process = threading.Thread(
target=general_worker,
args=(watershed_work_queue,))
watershed_worker_process.daemon = True
watershed_worker_process.start()
watershed_worker_process_list.append(watershed_worker_process)
LOGGER.info('building watershed fid list')
# TODO: for immediate mode
if watershed_ids:
valid_watershed_basenames = set()
valid_watersheds = set()
for watershed_id in watershed_ids:
watershed_basename, watershed_fid = watershed_id.split(',')
valid_watershed_basenames.add(watershed_basename)
valid_watersheds.add((watershed_basename, int(watershed_fid)))
LOGGER.debug(
f'valid watershed basenames: {valid_watershed_basenames} '
f'valid valid_watersheds: {valid_watersheds} ')
duplicate_job_index_map = collections.defaultdict(int)
for watershed_path in glob.glob(
os.path.join(watershed_root_dir, '*.shp')):
LOGGER.debug(f'processing {watershed_path}')
watershed_fid_index = collections.defaultdict(
lambda: [list(), list(), 0])
watershed_basename = os.path.splitext(