-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpcr_economic_limit_groundwater_extraction.py
1850 lines (1563 loc) · 91.3 KB
/
pcr_economic_limit_groundwater_extraction.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
#
# Global Economic Limits of Groundwater for Irrigation
#
# Copyright (c) L.P.H. (Rens) van Beek / Marc F.P. Bierkens 2018-2022
# Faculty of Geosciences, Utrecht University, Utrecht, The Netherlands
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###########
# modules #
###########
import os
import sys
import datetime
import logging
import numpy as np
import pcraster as pcr
import pcraster.framework as pcrm
sys.path.insert(0,'/home/rens/Scripts/pylib')
from spatialDataSet2PCR import spatialAttributes, setClone, spatialDataSet
from ncRecipes_fixed import getNCDates, writeField
from read_temporal_info_to_pcr import getTimedPCRData
from functions_economical_limit_groundwater_extraction import *
from zonalStatistics import zonal_statistics_pcr
from ncRecipes_fixed import getNCDates, createNetCDF
####################
# global variables #
####################
# logger
logger = logging.getLogger(__name__)
# single year spinup: does what it says to speed processing
fixed_yearly_increment = 1
#############
# functions #
#############
def recast_real_as_natural_ratio(r_f):
'''Returns the ratio r_n which is the ratio of the natural number n, \
so that r_n= 1:n or r_n= n:1 on the basis of the float r_f provided that \
r_f is non zero, otherwise r_n= 0 is retunred.
At the moment, no check on precision is included.
Input:
======
r_f: float
Output:
=======
r_n: float, the ratio of 1:n or n:1, or zero,
dependent on the sign and value of r_f
n_s: integer, the selected root to which the decimal
part of r_f is scaled; n_s * r_f should again
return an integer, including zero.
'''
#-Initialization
#-check on r_f
if not isinstance(r_f, float) and not isinstance(r_f, int):
sys.exit('r_n is not a float or cannot be recast as a float')
elif isinstance(r_f, int):
r_f= float(r_f)
#-initialize r_n and n_s
# r_n is set to zero and this value is returned if r_f is zero
n_s= 1
r_n= 0.0
# a precision is defined, a value of zero requires an exact match
# so that r_f * n_s % 1 equals zero
precision= 1.0e-5
n_max= int(1 // precision + 1)
#-Start
# If r_f is not zero, split the absolute number abs(r_f) into its inte-
# ger root and decimal fraction and keep its sign, test on d and return
# the new value of r_n
if r_f != 0:
#-sign, integer and decimal part of r_f
if r_f < 0:
s_f= -1.0
else:
s_f= 1.0
m_r= int(abs(r_f))
d_r= abs(r_f) % 1
if d_r <= (precision**0.5 * m_r) and m_r > 0:
d_r= 0.0
#-recast d_r as n_r
# Get the absolute inverse of d_r, n_r, and create a list of integers
# up to the order of n_r + 1, n_list; next, check when the ratio of
# an element of n_list, n_s over d_r returns an integer (or a float
# close to one), then return n_s and n_r to compute the ratio that
# constitutes the decimal part of r_n= m_r + n_r / n_s
if d_r > 0:
# get the list of integers to process
n_list= list(range(2, n_max+1))
# start at n_s is 1 and compute n_r,
# next check whether n_r is an integer and if not, repeat
# by getting n_s from n_list in ascending order until this
# condition is met
n_s= 1
n_r= d_r * n_s
while abs(n_r - round(n_r)) > precision and len(n_list) > 0:
n_s= n_list.pop(0)
n_r= d_r * n_s
#-return r_n, the sum of the integer and the decimal part, the
# latter being n_r / n_s; the total sum is multiplied by the sign.
n_r= round(d_r * n_s)
r_n= s_f* (m_r + n_r / n_s)
#-Return
#-return r_n and n_s
return r_n, n_s
def retrieve_ids_from_mask(mask, id_map, id_list, id_names, message_str = ''):
'''returns the list of selected ids as well as a message string that lists the names'''
# initialize the selected ids, then check on the mask to see if further
# processing is necessary
selected_ids = []
# this speeds up things:
if pcr.cellvalue(pcr.mapmaximum(pcr.scalar(mask)), 1)[0] > 0:
selection_list = zonal_statistics_pcr(mask, \
id_map, id_list, np.max)
for selected_id in id_list:
if selection_list[id_list.index(selected_id)] == 1:
selected_ids.append(selected_id)
message_str = str.join('\n', ( \
message_str,
'\t%3d: %s' % (selected_id, id_names[selected_id]), \
))
# return selected_ids and message_str
return selected_ids, message_str
####################
# class definition #
####################
class pcr_economic_limit_groundwater_extraction(pcrm.StaticModel):
#-definition of the static model script object to allocate areas to crops in
# order to satisfy demand
###################
# binding section #
###################
def __init__(self, modelconfiguration):
pcrm.StaticModel.__init__(self)
##################
# Initialization #
##################
# Initialization: most information is supplied from the configuration file
# Parameters
# dummy variable name and a list of julian days of the first day of the month;
# this list is used to read in the crop factors
self.dummyvariablename = 'dummy'
self.missing_value = -999.9
self.full_report = modelconfiguration.general['full_report']
self.testverbose = modelconfiguration.general['testverbose']
# this is not going to work but it gives results
self.date_selection_method = 'exact'
# conversion from tonnes to kg:
# conversion for producer price: price is in $ per metric tonne, whereas
# production as computed in kg per cell area
self.convfactor_tonnes_to_kg = 1000.0
self.convfactor_ha_to_m2 = None
# set the pumping efficiency
self.initial_pumping_efficiency = 0.95
self.final_pumping_efficiency = 0.60
# set the years to process; config info read as list
self.startyear = int(modelconfiguration.general['startyear'])
self.max_number_years = int(modelconfiguration.general['max_number_years'])
# dynamic crop info?
if 'true' in modelconfiguration.general['dynamic_crop_info_present'].lower():
self.dynamic_crop_info_present = True
else:
self.dynamic_crop_info_present = False
# and a dummy date to read in values
dummydate = datetime.datetime(self.startyear, 1, 1)
# setting on reconstruction of existing wells
self.reconstruct_existing_wells = \
modelconfiguration.general['reconstruct_existing_wells']
# Set the clone on the basis of the spatial attributes of the clone map
self.cloneattributes= spatialAttributes(modelconfiguration.general['clone'])
setClone(self.cloneattributes)
# read in the clone map
self.landmask = pcr.cover(pcr.readmap(modelconfiguration.general['clone']) != 0, \
pcr.boolean(0))
# read in the countries, regions and cell area
# countries
self.countries = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.general['countries'], 'INT32', 'Nominal',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
self.countries = pcr.ifthen(self.landmask, self.countries)
self.countries = pcr.ifthen(self.countries != 0, self.countries)
# cell area
# get the multiplication factor
dataattributes = spatialAttributes(modelconfiguration.general['cellarea'])
productResolution, data_scale_division = recast_real_as_natural_ratio(\
dataattributes.xResolution)
productResolution, clone_scale_division = recast_real_as_natural_ratio(\
self.cloneattributes.xResolution)
scale_factor = (data_scale_division / clone_scale_division)**2
# get the cell area
self.cellarea = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.general['cellarea'], 'FLOAT32', 'Scalar',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
self.cellarea = pcr.ifthen(self.landmask, scale_factor * self.cellarea)
# regions
self.regions = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.general['regions'], 'INT32', 'Nominal',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
self.regions = pcr.ifthen(self.landmask, self.regions)
# read in the groundwater information
# specific yields of the confined and unconfined layers
# TODO: replace file access by file_handler's read_file_entry method
# but this currently is not compatible with python 2 due to the netCDF
# class.
# read in the specific yield
# unconfined
if os.path.isfile(modelconfiguration.groundwater['specific_yield_unconflayer']):
specificyield_unconfined = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.groundwater['specific_yield_unconflayer'], 'FLOAT32', 'Scalar',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
else:
specificyield_unconfined = modelconfiguration.convert_string_to_input( \
modelconfiguration.groundwater['specific_yield_unconflayer'], float)
# confined
if os.path.isfile(modelconfiguration.groundwater['specific_yield_conflayer']):
specificyield_confined = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.groundwater['specific_yield_conflayer'], 'FLOAT32', 'Scalar',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
else:
specificyield_confined = modelconfiguration.convert_string_to_input( \
modelconfiguration.groundwater['specific_yield_conflayer'], float)
# and just make sure they are spatial scalar PCRaster maps
specificyield_unconfined = pcr.spatial(pcr.scalar(specificyield_unconfined))
specificyield_confined = pcr.spatial(pcr.scalar(specificyield_confined))
# and put them in the list for use
self.specificyields = [specificyield_confined, specificyield_unconfined]
# read in the confined layer depth, the unconfined depth is set to a missing value
# unconfined
layerdepth_unconfined = self.missing_value
# confined
if os.path.isfile(modelconfiguration.groundwater['confinining_layer_thickness']):
layerdepth_confined = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.groundwater['confinining_layer_thickness'], 'FLOAT32', 'Scalar',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
else:
layerdepth_confined = modelconfiguration.convert_string_to_input( \
modelconfiguration.groundwater['confinining_layer_thickness'], float)
# and just make sure they are spatial scalar PCRaster maps
layerdepth_confined = pcr.spatial(pcr.scalar(layerdepth_confined))
self.layerdepths = [layerdepth_confined, layerdepth_unconfined]
# odd variables
self.vars_in_list = {'layerdepth_confined' : ('layerdepths', 0), \
'layerdepth_unconfined' : ('layerdepths', 1), \
'specificyield_confined' : ('specificyields', 0), \
'specificyield_unconfined' : ('specificyields', 1), \
}
# read in the original groundwater depth
self.groundwaterdepth = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.groundwater['groundwaterdepth'], 'FLOAT32', 'Scalar',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
self.groundwaterdepth = pcr.ifthen(self.landmask, pcr.max(0, self.groundwaterdepth))
self.original_groundwaterdepth = self.groundwaterdepth
self.projected_groundwaterdepth = self.groundwaterdepth
# read in the output path; creat and set it if necessary
self.outputpath = modelconfiguration.general['outputpath']
# if it does not exist, create it
if not os.path.isdir(self.outputpath):
os.makedirs(self.outputpath)
# crop information: set the necesary information, then add the completed
# file names to the dictionaries
self.crop_systems = modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['crop_systems'], str)
self.selected_crops = modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['selected_crop_ids'], int)
self.crop_ids = modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['crop_ids'], int)
self.crop_names = modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['crop_names'], str)
self.crop_types = dict(zip(self.crop_ids, self.crop_names))
self.irrigation_types = modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['irrigation_types'], str)
# the following variables are initialized als local variables only and converted
# into class attributes as cell averages
irrigation_efficiency = dict(zip(self.irrigation_types, \
modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['irrigation_efficiency'], float)))
irrigation_overpressure_ratio = \
dict(zip(self.irrigation_types, \
modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['irrigation_overpressure_ratio'], float)))
# set cell-averaged characteristics
# initialize the overall overpressure and the irrigation efficiency
self.fraction_irrigation_type = {}
self.head_overpressure = pcr.scalar(0)
self.irrigation_efficiency = pcr.scalar(0)
# read in the irrigation fractions and set the efficiency as well as the over pressure
# overpressure is in Pa and is converted to m
sprinkler_radius = modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['sprinkler_radius'], float)
sprinkler_correction = modelconfiguration.convert_string_to_input( \
modelconfiguration.crops['sprinkler_correction'], float)
head_overpressure, velocity = compute_overpressure_sprinklers( \
sprinkler_radius, cor_factor = sprinkler_correction)
head_overpressure = head_overpressure / 1000 / 9.81
# iterate over the irrigation types
for irrigation_type in self.irrigation_types:
# get the fraction
self.fraction_irrigation_type[irrigation_type] = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.crops['fraction_irrigation_type_fileroot'] % irrigation_type, \
'FLOAT32', 'Scalar',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
# correct the fraction irrigation type to unity where the values are not properly set
self.fraction_irrigation_type['surface'] = pcr.max(0.0, 1.0 - \
pcr.cover(self.fraction_irrigation_type['drip'] + \
self.fraction_irrigation_type['sprinkler'], 0))
# iterate over the irrigation types
for irrigation_type in self.irrigation_types:
# update the overpressure
self.head_overpressure = self.head_overpressure + \
self.fraction_irrigation_type[irrigation_type] * \
irrigation_overpressure_ratio[irrigation_type] * head_overpressure
# update the efficiency
self.irrigation_efficiency = self.irrigation_efficiency + \
self.fraction_irrigation_type[irrigation_type] * \
irrigation_efficiency[irrigation_type]
# complement the file names
crop_water_requirement_fileroot = modelconfiguration.crops['crop_water_requirement_fileroot']
maximum_crop_area_fileroot = modelconfiguration.crops['maximum_crop_area_fileroot']
# and initialize the dictionaries
self.maximum_crop_area_files = {}
self.crop_water_requirement_files = {}
# iterate over the crop systems
for crop_system in self.crop_systems:
# nest the dictionary for crop systems
self.maximum_crop_area_files[crop_system] = {}
self.crop_water_requirement_files[crop_system] = {}
# iterate over the crop types
for crop_id in self.selected_crops:
# get the name
crop_name = self.crop_types[crop_id]
# add the files
self.maximum_crop_area_files[crop_system][crop_name] = \
maximum_crop_area_fileroot % (crop_system, crop_name)
self.crop_water_requirement_files[crop_system][crop_name] = \
crop_water_requirement_fileroot % (crop_system, crop_name)
# table information to be read from text files: all relevant model
# configuration items are set here as internal variables so that they
# can be updated in the initial / dynamic sections of the model
# water productivity
self.water_productivity_tbl_filename = modelconfiguration.crops['water_productivity_tbl']
# country information: table with various information organized per coun-
# try and the entries provided per row
# country_table_column_start: this is the last column of those columns identifying
# the different information on country and region IDs as contained by the country-specfic
# tables:
# FID ISO1 ISO2 ISO3 Name IMAGE26 IMAGE26_name fraction_agricultural_population
self.country_data_tbl_filename = modelconfiguration.table_info['country_data_tbl_filename']
#~ self.agricultural_population_tbl_filename = modelconfiguration.countrysettings['agricultural_population_tbl_filename']
self.table_info = {}
for key, value in modelconfiguration.table_info.items():
if key[:6] == 'table_':
self.table_info[key[6:]] = int(value)
#~ self.agricultural_population_tbl_columns = modelconfiguration.countrysettings['agricultural_population_tbl_columns']
# adjustment info for the sensitivity analysis
self.adjustment_info = {}
if 'adjustments' in vars(modelconfiguration).keys():
for key in modelconfiguration.adjustments.keys():
# check on the value
if modelconfiguration.adjustments[key][:2] == '\-':
modelconfiguration.adjustments[key] = modelconfiguration.adjustments[key][1:]
# process the value
if os.path.isfile(modelconfiguration.adjustments[key]):
# value is a PCRaster map
value = pcr.cover(getattr(spatialDataSet(self.dummyvariablename,\
modelconfiguration.adjustments[key], 'FLOAT32', 'Scalar',\
self.cloneattributes.xLL, self.cloneattributes.xUR, self.cloneattributes.yLL, self.cloneattributes.yUR,\
self.cloneattributes.xResolution, self.cloneattributes.yResolution,\
pixels= self.cloneattributes.numberCols, lines= self.cloneattributes.numberRows), self.dummyvariablename), 0)
else:
value = modelconfiguration.convert_string_to_input( \
modelconfiguration.adjustments[key], float)
self.adjustment_info[key] = value
# ******************
# * model products *
# ******************
# define the model products, set the settings to create the netCDF files
# and initialize the netCDF files
# *********************
# * netCDF attributes *
# *********************
self.ncattributes= {}
excludedkeys= []
for key, value in modelconfiguration.netcdfattrs.items():
if key not in excludedkeys:
self.ncattributes[key]= value
if not 'history' in self.ncattributes.keys():
self.ncattributes['history']= ''
self.ncattributes['history']+= '\ncreated on %s.' % (datetime.datetime.now())
# resolution, number of rows and columns
productResolution, scale_division = recast_real_as_natural_ratio(\
self.cloneattributes.xResolution)
number_rows= (self.cloneattributes.yUR - self.cloneattributes.yLL + \
0.5 * productResolution) // productResolution
number_cols= (self.cloneattributes.xUR - self.cloneattributes.xLL + \
0.5 * productResolution) // productResolution
# set latitudes and longitudes
latitudes = -np.arange(number_rows) /\
scale_division + self.cloneattributes.yUR - 0.5 * productResolution
longitudes = np.arange(number_cols) /\
scale_division + self.cloneattributes.xLL + 0.5 * productResolution
# model products that are written in the approprate places
# in the dynamic section
# full_report lists additional variables that can be reported
self.modelproducts= {}
# year groundwater limit is met
variablename= 'year_groundwater_limit_met'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= '-'
self.modelproducts[variablename]['method']= 'frequency'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= False
self.modelproducts[variablename]['report']= True
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# total_extracted_volume
variablename= 'total_extracted_volume'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'm3'
self.modelproducts[variablename]['method']= 'frequency'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= True
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# groundwater depth
variablename= 'groundwaterdepth'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'm'
self.modelproducts[variablename]['method']= 'frequency'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= self.full_report
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# number wells
variablename= 'number_wells'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= '-'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= True
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# well depth
variablename= 'well_depth'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'm'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= True
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# actual efficiency
variablename= 'actual_pumping_efficiency'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= '-'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= self.full_report
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# projected efficiency
variablename= 'projected_pumping_efficiency'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= '-'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= self.full_report
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# investment cost per year
variablename= 'investment_cost'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'US$'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= self.full_report
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# energy cost per year
variablename= 'energy_cost'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'US$/year'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= self.full_report
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# interest cost per year
variablename= 'interest_cost_investment'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'US$/year'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= self.full_report
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# total_revenue_loans
variablename= 'total_revenue_loans'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'US$/year'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= self.full_report
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# total_revenue_savings
variablename= 'total_revenue_savings'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'US$/year'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= False
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# net_present_value_loans
variablename= 'net_present_value_loans'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'US$/year'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= True
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# net_present_value_savings
variablename= 'net_present_value_savings'
self.modelproducts[variablename]= {}
self.modelproducts[variablename]['alias']= variablename
self.modelproducts[variablename]['conversionfactor']= 1.00
self.modelproducts[variablename]['unit']= 'US$'
self.modelproducts[variablename]['method']= 'average'
self.modelproducts[variablename]['data']= variablename
self.modelproducts[variablename]['dynamic']= True
self.modelproducts[variablename]['report']= False
self.modelproducts[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# crop information, this sets fixed data to files
# in the case of irrigated crops:
# - irrigated_crop_area
# - total_water_requirement_irrigation
# - total_income_irrigated
# this information is not written by default!
self.write_crop_info = self.full_report
self.cropinfo_products = {}
# irrigated crop area
variablename= 'irrigated_crop_area'
self.cropinfo_products[variablename]= {}
self.cropinfo_products[variablename]['alias']= variablename
self.cropinfo_products[variablename]['conversionfactor']= 1.00
self.cropinfo_products[variablename]['unit']= 'm2'
self.cropinfo_products[variablename]['method']= 'average'
self.cropinfo_products[variablename]['data']= variablename
self.cropinfo_products[variablename]['dynamic']= True
self.cropinfo_products[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# total_income_irrigated
variablename= 'total_income_irrigated'
self.cropinfo_products[variablename]= {}
self.cropinfo_products[variablename]['alias']= variablename
self.cropinfo_products[variablename]['conversionfactor']= 1.00
self.cropinfo_products[variablename]['unit']= 'US$/year'
self.cropinfo_products[variablename]['method']= 'average'
self.cropinfo_products[variablename]['data']= variablename
self.cropinfo_products[variablename]['dynamic']= True
self.cropinfo_products[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# total_water_requirement_irrigation
variablename= 'total_water_requirement_irrigation'
self.cropinfo_products[variablename]= {}
self.cropinfo_products[variablename]['alias']= variablename
self.cropinfo_products[variablename]['conversionfactor']= 1.00
self.cropinfo_products[variablename]['unit']= 'm3/year'
self.cropinfo_products[variablename]['method']= 'average'
self.cropinfo_products[variablename]['data']= variablename
self.cropinfo_products[variablename]['dynamic']= True
self.cropinfo_products[variablename]['filename']= os.path.join(\
self.outputpath, 'netcdf', '%s.nc' % variablename.lower())
# initialize the netCDF files
for variablename in self.modelproducts.keys():
if self.modelproducts[variablename]['report']:
variablelongname= variablename
createNetCDF(self.modelproducts[variablename]['filename'], \
longitudes, latitudes, 'longitude', 'latitude', 'time',\
self.modelproducts[variablename]['alias'], self.modelproducts[variablename]['unit'],\
self.missing_value, self.ncattributes, varLongName= variablelongname)
if self.write_crop_info:
for variablename in self.cropinfo_products.keys():
variablelongname= variablename
createNetCDF(self.cropinfo_products[variablename]['filename'], \
longitudes, latitudes, 'longitude', 'latitude', 'time',\
self.cropinfo_products[variablename]['alias'], self.cropinfo_products[variablename]['unit'],\
self.missing_value, self.ncattributes, varLongName= variablelongname)
######################
# internal functions #
######################
def obtain_crop_info(self, \
crop_water_requirement_files, \
maximum_crop_area_files, \
nc_date_info, date, date_selection_method, \
water_productivity, \
crop_systems, selected_crops, crop_types, \
landmask, cloneattributes, irrigation_efficiency = 0.7):
'''
obtain_crop_info: returns crop information using information on the files and \
dates and the water productivity.
'''
# obtain the production per crop type as mass per cell
rainfed_crop_production_info = {}
irrigated_crop_production_info = {}
# set the totals of production and area
rainfed_crop_area = pcr.scalar(0)
irrigated_crop_area = pcr.scalar(0)
total_crop_area= pcr.scalar(0)
rainfed_crop_production = pcr.scalar(0)
irrigated_crop_production = pcr.scalar(0)
total_crop_production = pcr.scalar(0)
# total water requirement: only for irrigation
total_water_requirement_irrigation = pcr.scalar(0)
# iterate over all crop systems and the
# crop types
for crop_system in crop_systems:
# iterate over the crop types
for crop_id in selected_crops:
# get the name
crop_name = crop_types[crop_id]
# netCDF file name and dates: crop area
nc_filename = maximum_crop_area_files[crop_system][crop_name]
nc_date_list = nc_date_info[nc_filename]
crop_area, returned_date, message_str= \
getTimedPCRData(nc_filename,\
nc_date_list, date,\
dateSelectionMethod= date_selection_method,\
dataAttributes= cloneattributes)
# get the multiplication factor
dataattributes = spatialAttributes(nc_filename)
productResolution, data_scale_division = recast_real_as_natural_ratio(\
dataattributes.xResolution)
productResolution, clone_scale_division = recast_real_as_natural_ratio(\
self.cloneattributes.xResolution)
scale_factor = (data_scale_division / clone_scale_division)**2
crop_area = scale_factor * crop_area
# crop areas have been updated on velocity and snellius!
# ~ # *** temporary ***
# ~ # correction for crop area
# ~ crop_area = 100.0 * crop_area
# ~ # *** temporary ***
# netCDF file name and dates: crop water requirement
nc_filename = crop_water_requirement_files[crop_system][crop_name]
nc_date_list = nc_date_info[nc_filename]
crop_water_requirement, returned_date, message_str= \
getTimedPCRData(nc_filename,\
nc_date_list, date,\
dateSelectionMethod= date_selection_method,\
dataAttributes= cloneattributes)
# get the crop yield
crop_yield = pcr.ifthen(landmask, \
water_productivity[crop_system][crop_id] * \
crop_water_requirement)
# add the data to the dictionary
if crop_system == 'rainfed':
rainfed_crop_production_info[crop_id] = crop_yield * crop_area
rainfed_crop_area = rainfed_crop_area + crop_area
rainfed_crop_production = rainfed_crop_production + \
rainfed_crop_production_info[crop_id]
if crop_system == 'irrigated':
irrigated_crop_production_info[crop_id] = crop_yield * crop_area
irrigated_crop_area = irrigated_crop_area + crop_area
irrigated_crop_production = irrigated_crop_production + \
irrigated_crop_production_info[crop_id]
total_water_requirement_irrigation = \
total_water_requirement_irrigation + \
pcr.ifthen(landmask, \
crop_area * crop_water_requirement / irrigation_efficiency)
#~ # *** temporary ***
#~ # as a test on the data, report the yield in tonnes per ha for
#~ # irrigated wheat
#~ if crop_id == 1:
#~ pcr.report( \
#~ 10.0 * irrigated_crop_production_info[crop_id] / crop_area,\
#~ 'temp_wheat_yield.map')
#~ # *** temporary ***
# and obtain the total crop area and total production
total_crop_area = rainfed_crop_area + irrigated_crop_area
total_crop_production = rainfed_crop_production + irrigated_crop_production
# return the output
return rainfed_crop_production_info, rainfed_crop_area, \
rainfed_crop_production, \
irrigated_crop_production_info, irrigated_crop_area, \
irrigated_crop_production, total_water_requirement_irrigation, \
total_crop_area, total_crop_production
# end of additional internal functions
###################
# initial section #
###################
def initial(self):
# echo to screen
message_str = str.join('\n', \
(' * Initializing all information that is assumed to be static over time.', \
'currently this includes the following variables that may become dynamic:', \
' - water productivity', \
' - producer price per crop', \
' - energy costs', \
' - labour costs', \
' - material costs invariant with depth', \
' - material costs per depth', \
' - population', \
))
logger.info(message_str)
# *** truly static information ***
# file information
# get the dates for all netCDFs
nc_date_info = {}
# get the file names, and add its dates
for crop_system in self.crop_systems:
# iterate over the crop types
for crop_id in self.selected_crops:
# get the name
crop_name = self.crop_types[crop_id]
# netCDF file name
# crop water requirement
nc_filename = self.crop_water_requirement_files[crop_system][crop_name]
nc_date_info[nc_filename]= getNCDates(nc_filename)
# maximum crop area
nc_filename = self.maximum_crop_area_files[crop_system][crop_name]
nc_date_info[nc_filename]= getNCDates(nc_filename)
# initializion of internal variables
# set the amount of money saved to zero as it can be updated during the
# spinup period, which is equal to the well life time and the present value
self.total_revenue_loans = pcr.scalar(0)
self.total_revenue_savings = pcr.scalar(0)
self.net_present_value_loans = pcr.scalar(0)
self.net_present_value_savings = pcr.scalar(0)
# set the long-term water requirements
self.longterm_water_requirement_irrigation = pcr.scalar(0)
# set the total extracted groundwater volume
self.total_extracted_volume = pcr.scalar(0)
# initialize the costs at zero
self.pump_installation_cost = pcr.ifthen(self.landmask, pcr.scalar(0))
self.well_construction_cost = pcr.ifthen(self.landmask, pcr.scalar(0))
self.irrigation_installation_cost = pcr.ifthen(self.landmask, pcr.scalar(0))
self.investment_cost = pcr.ifthen(self.landmask, pcr.scalar(0))
self.interest_cost_investment = pcr.ifthen(self.landmask, pcr.scalar(0))
self.energy_cost = pcr.ifthen(self.landmask, pcr.scalar(0))
# initialize current investment level at zero and initialize
# the investment year
self.current_investment = pcr.ifthen(self.landmask, pcr.scalar(0))
self.investment_year = pcr.ifthen(self.landmask, pcr.scalar(0))
self.abstraction_year = pcr.ifthen(self.landmask, pcr.scalar(0))
# set the initial number of pumps to zero and the well depth as well
self.number_wells = pcr.ifthen(self.landmask, pcr.scalar(0))
self.well_depth = pcr.ifthen(self.landmask, pcr.scalar(0))
# *** information that may become dynamic ***
# water productivity: dictionary per crop for each crop system
self.water_productivity = {}
self.water_productivity['rainfed'] = read_water_productivity( \
datafile = self.water_productivity_tbl_filename, \
selectedcrops = self.selected_crops, testverbose = self.testverbose)
self.water_productivity['irrigated'] = read_water_productivity( \
datafile = self.water_productivity_tbl_filename, \
selectedcrops = self.selected_crops, testverbose = self.testverbose)
# producer price
self.rainfed_crop_price_info = {}
self.irrigated_crop_price_info= {}
selected_keys = list(self.table_info.keys())
# iterate over the crops to get the yield and price
for crop_id in self.selected_crops:
# get the column index
data_key = 'price_%s' % self.crop_types[crop_id]
data_column = self.table_info[data_key]
selected_keys.remove(data_key)
# add the information to the crop information
self.rainfed_crop_price_info[crop_id] = \
map_table_info_to_pcr(\
datafile = self.country_data_tbl_filename, \
key_map = self.countries, \
key_column = self.table_info['country_id'], \
data_column = data_column, \
pcr_data_type = pcr.scalar, \
testverbose = False)
self.irrigated_crop_price_info[crop_id] = \
map_table_info_to_pcr(\
datafile = self.country_data_tbl_filename, \
key_map = self.countries, \
key_column = self.table_info['country_id'], \
data_column = data_column, \
pcr_data_type = pcr.scalar, \
testverbose = False)
# echo to screen
message_str = 'currently the water productivity is fixed for all years.'
logger.warning(message_str)
# mapped info: countries (test) and mapped information that is not crop dependent
# as stored in the selected keys
selected_keys.remove('country_name')
self.mapped_country_info = {}
# add the country-specific information
for data_key in selected_keys:
# get the mapped data