forked from ESCOMP/CTSM
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfsurdat_modifier.py
More file actions
668 lines (609 loc) · 19.5 KB
/
fsurdat_modifier.py
File metadata and controls
668 lines (609 loc) · 19.5 KB
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
"""
Run this code by using the following wrapper script:
tools/modify_input_files/fsurdat_modifier
The wrapper script includes a full description and instructions.
"""
import os
import logging
import argparse
from configparser import ConfigParser
from ctsm.utils import abort, write_output
from ctsm.config_utils import get_config_value, get_config_value_or_array
from ctsm.ctsm_logging import (
setup_logging_pre_config,
add_logging_args,
process_logging_args,
)
from ctsm.modify_input_files.modify_fsurdat import ModifyFsurdat
logger = logging.getLogger(__name__)
def main():
"""
Description
-----------
Calls function that modifies an fsurdat (surface dataset)
"""
args = fsurdat_modifier_arg_process()
fsurdat_modifier(args)
def fsurdat_modifier_arg_process():
"""Argument processing for fsurdat_modifier script"""
# set up logging allowing user control
setup_logging_pre_config()
# read the command line argument to obtain the path to the .cfg file
parser = argparse.ArgumentParser()
parser.add_argument("cfg_path", help="/path/name.cfg of input file, eg ./modify.cfg")
parser.add_argument(
"-i",
"--fsurdat_in",
default="UNSET",
required=False,
type=str,
help="The input surface dataset to modify. ",
)
parser.add_argument(
"-o",
"--fsurdat_out",
required=False,
default="UNSET",
type=str,
help="The output surface dataset with the modifications. ",
)
parser.add_argument(
"--overwrite",
required=False,
default=False,
action="store_true",
help="Overwrite the output file if it already exists. ",
)
add_logging_args(parser)
args = parser.parse_args()
process_logging_args(args)
# Error checking of arguments
if not os.path.exists(args.cfg_path):
abort("Config file does NOT exist: " + str(args.cfg_path))
return args
def check_no_subgrid_section(config):
"""Check that there isn't a subgrid section when it's processing is turned off"""
section = "modify_fsurdat_subgrid_fractions"
if config.has_section(section):
abort(
"Config file does have a section: "
+ section
+ " that should NOT be there since it is turned off"
)
def check_no_varlist_section(config):
"""Check that there isn't a var list section when it's processing is turned off"""
section = "modify_fsurdat_variable_list"
if config.has_section(section):
abort(
"Config file does have a section: "
+ section
+ " that should NOT be there since it is turned off"
)
def check_range(var, section, value, minval, maxval):
"""Check that the value is within range"""
if value < minval or value > maxval:
abort("Variable " + var + " in " + section + " is out of range of 0 to 100 = " + str(value))
def read_cfg_subgrid(config, cfg_path, numurbl=3):
"""Read the subgrid fraction section from the config file"""
section = "modify_fsurdat_subgrid_fractions"
if not config.has_section(section):
abort("Config file does not have the expected section: " + section)
subgrid_settings = {}
var_list = config.options(section)
valid_list = [
"pct_natveg",
"pct_crop",
"pct_lake",
"pct_glacier",
"pct_wetland",
"pct_urban",
"pct_ocean",
]
varsum = 0
for var in var_list:
if valid_list.count(var) == 0:
abort(
"Variable "
+ var
+ " in "
+ section
+ " is not a valid variable name. Valid vars ="
+ str(valid_list)
)
# Urban is multidimensional
if var == "pct_urban":
vallist = get_config_value(
config=config,
section=section,
item=var,
file_path=cfg_path,
is_list=True,
convert_to_type=float,
)
if len(vallist) != numurbl:
abort("PCT_URBAN is not a list of the expected size of " + str(numurbl))
# so if a scalar value, must be multiplied # by the density dimension
for val in vallist:
check_range(var, section, val, 0.0, 100.0)
varsum += val
value = vallist
else:
value = get_config_value(
config=config, section=section, item=var, file_path=cfg_path, convert_to_type=float
)
check_range(var, section, value, 0.0, 100.0)
varsum += value
subgrid_settings[var.upper()] = value
if varsum != 100.0:
abort(
"PCT fractions in subgrid section do NOT sum to a hundred as they should. Sum = "
+ str(varsum)
)
return subgrid_settings
def read_cfg_var_list(config, idealized=True):
"""Read the variable list section from the config file"""
section = "modify_fsurdat_variable_list"
if not config.has_section(section):
abort("Config file does not have the expected section: " + section)
varlist_settings = {}
var_list = config.options(section)
ideal_list = [
"soil_color",
"pct_sand",
"pct_clay",
"organic",
"pct_cft",
"pct_nat_pft",
"fmax",
"std_elev",
]
subgrid_list = ["pct_natveg", "pct_crop", "pct_lake", "pct_glacier", "pct_wetland", "pct_urban"]
# List of variables that should be excluded because they are changed elsewhere,
# or they shouldn't be changed # Ds, Dsmax, and Ws are excluded because they
# are of mixed case and we only search for varaibles in lowercase
# or uppercase and not mixed case.
monthly_list = [
"monthly_lai",
"monthly_sai",
"monthly_height_top",
"monthly_height_bot",
"ds",
"mxsoil_color",
"natpft",
"cft",
"time",
"longxy",
"latixy",
"dsmax",
"area",
"ws",
]
for var in var_list:
if idealized and ideal_list.count(var) != 0:
abort(
var
+ " is a special variable handled in the idealized section."
+ " This should NOT be handled in the variable list section."
+ " Special idealized vars ="
+ str(ideal_list)
)
if subgrid_list.count(var) != 0:
abort(
var
+ " is a variable handled in the subgrid section."
+ " This should NOT be handled in the variable list section."
+ " Subgrid vars ="
+ str(subgrid_list)
)
if monthly_list.count(var) != 0:
abort(
var
+ " is a variable handled as part of the dom_pft handling."
+ " This should NOT be handled in the variable list section."
+ " Monthly vars handled this way ="
+ str(monthly_list)
)
value = get_config_value_or_array(
config=config, section=section, item=var, convert_to_type=float
)
varlist_settings[var] = value
return varlist_settings
def modify_optional(
modify_fsurdat,
idealized,
include_nonveg,
max_sat_area,
std_elev,
soil_color,
dom_pft,
evenly_split_cropland,
lai,
sai,
hgt_top,
hgt_bot,
):
"""Modify the dataset according to the optional settings"""
# Set fsurdat variables in a rectangle that could be global (default).
# Note that the land/ocean mask gets specified in
# the ocean mesh files. Here the user may specify
# fsurdat variables inside a box but cannot change which points will
# run as land and which as ocean.
if idealized:
modify_fsurdat.set_idealized() # set 2D variables
# set 3D and 4D variables pertaining to natural vegetation
# to default values here; allow override values with the later call
# to set_dom_pft
modify_fsurdat.set_dom_pft(dom_pft=0, lai=[], sai=[], hgt_top=[], hgt_bot=[])
logger.info("idealized complete")
if max_sat_area is not None: # overwrite "idealized" value
modify_fsurdat.setvar_lev0("FMAX", max_sat_area)
logger.info("max_sat_area complete")
if std_elev is not None: # overwrite "idealized" value
modify_fsurdat.setvar_lev0("STD_ELEV", std_elev)
logger.info("std_elev complete")
if soil_color is not None: # overwrite "idealized" value
modify_fsurdat.setvar_lev0("SOIL_COLOR", soil_color)
logger.info("soil_color complete")
if not include_nonveg:
modify_fsurdat.zero_nonveg()
logger.info("zero_nonveg complete")
# set_dom_pft follows idealized and zero_nonveg because it modifies
# PCT_NATVEG and PCT_CROP in the user-defined rectangle
if dom_pft is not None:
modify_fsurdat.set_dom_pft(
dom_pft=dom_pft, lai=lai, sai=sai, hgt_top=hgt_top, hgt_bot=hgt_bot
)
logger.info("dom_pft complete")
if evenly_split_cropland:
modify_fsurdat.evenly_split_cropland()
logger.info("evenly_split_cropland complete")
def read_cfg_optional_basic_opts(modify_fsurdat, config, cfg_path, section):
"""Read the optional parts of the main section of the config file.
The main section is called modify_fsurdat_basic_options.
Users may set these optional parts but are not required to do so."""
lai = get_config_value(
config=config,
section=section,
item="lai",
file_path=cfg_path,
is_list=True,
convert_to_type=float,
can_be_unset=True,
)
sai = get_config_value(
config=config,
section=section,
item="sai",
file_path=cfg_path,
is_list=True,
convert_to_type=float,
can_be_unset=True,
)
hgt_top = get_config_value(
config=config,
section=section,
item="hgt_top",
file_path=cfg_path,
is_list=True,
convert_to_type=float,
can_be_unset=True,
)
hgt_bot = get_config_value(
config=config,
section=section,
item="hgt_bot",
file_path=cfg_path,
is_list=True,
convert_to_type=float,
can_be_unset=True,
)
max_soil_color = int(modify_fsurdat.file.mxsoil_color)
soil_color = get_config_value(
config=config,
section=section,
item="soil_color",
file_path=cfg_path,
allowed_values=range(1, max_soil_color + 1), # 1 to max_soil_color
convert_to_type=int,
can_be_unset=True,
)
std_elev = get_config_value(
config=config,
section=section,
item="std_elev",
file_path=cfg_path,
convert_to_type=float,
can_be_unset=True,
)
max_sat_area = get_config_value(
config=config,
section=section,
item="max_sat_area",
file_path=cfg_path,
convert_to_type=float,
can_be_unset=True,
)
return (
max_sat_area,
std_elev,
soil_color,
lai,
sai,
hgt_top,
hgt_bot,
)
def read_cfg_option_control(
modify_fsurdat,
config,
section,
cfg_path,
):
"""Read the option control section"""
# required but fallback values available for variables omitted
# entirely from the .cfg file
idealized = get_config_value(
config=config,
section=section,
item="idealized",
file_path=cfg_path,
convert_to_type=bool,
)
if idealized:
logger.info("idealized option is on")
else:
logger.info("idealized option is off")
process_subgrid = get_config_value(
config=config,
section=section,
item="process_subgrid_section",
file_path=cfg_path,
convert_to_type=bool,
)
if process_subgrid:
logger.info("process_subgrid_section option is on")
else:
logger.info("process_subgrid_section option is off")
process_var_list = get_config_value(
config=config,
section=section,
item="process_var_list_section",
file_path=cfg_path,
convert_to_type=bool,
)
if process_var_list:
logger.info("process_var_list_section option is on")
else:
logger.info("process_var_list_section option is off")
include_nonveg = get_config_value(
config=config,
section=section,
item="include_nonveg",
file_path=cfg_path,
convert_to_type=bool,
)
if include_nonveg:
logger.info("include_nonveg option is on")
else:
logger.info("include_nonveg option is off")
max_pft = int(max(modify_fsurdat.file.lsmpft))
dom_pft = get_config_value(
config=config,
section=section,
item="dom_pft",
file_path=cfg_path,
allowed_values=range(max_pft + 1), # integers from 0 to max_pft
convert_to_type=int,
can_be_unset=True,
)
if dom_pft:
logger.info("dom_pft option is on and = %s", str(dom_pft))
else:
logger.info("dom_pft option is off")
evenly_split_cropland = get_config_value(
config=config,
section=section,
item="evenly_split_cropland",
file_path=cfg_path,
convert_to_type=bool,
)
if (
evenly_split_cropland
and dom_pft is not None
and dom_pft > int(max(modify_fsurdat.file.natpft.values))
):
abort("dom_pft must not be set to a crop PFT when evenly_split_cropland is True")
if process_subgrid and idealized:
abort("idealized AND process_subgrid_section can NOT both be on, pick one or the other")
return (
idealized,
process_subgrid,
process_var_list,
include_nonveg,
dom_pft,
evenly_split_cropland,
)
def read_cfg_required_basic_opts(config, section, cfg_path):
"""Read the required part of the control section"""
lnd_lat_1 = get_config_value(
config=config,
section=section,
item="lnd_lat_1",
file_path=cfg_path,
convert_to_type=float,
)
lnd_lat_2 = get_config_value(
config=config,
section=section,
item="lnd_lat_2",
file_path=cfg_path,
convert_to_type=float,
)
lnd_lon_1 = get_config_value(
config=config,
section=section,
item="lnd_lon_1",
file_path=cfg_path,
convert_to_type=float,
)
lnd_lon_2 = get_config_value(
config=config,
section=section,
item="lnd_lon_2",
file_path=cfg_path,
convert_to_type=float,
)
lon_type = get_config_value(
config=config,
section=section,
item="lon_type",
file_path=cfg_path,
convert_to_type=int,
)
landmask_file = get_config_value(
config=config,
section=section,
item="landmask_file",
file_path=cfg_path,
can_be_unset=True,
)
lat_dimname = get_config_value(
config=config, section=section, item="lat_dimname", file_path=cfg_path, can_be_unset=True
)
lon_dimname = get_config_value(
config=config, section=section, item="lon_dimname", file_path=cfg_path, can_be_unset=True
)
return (
lnd_lat_1,
lnd_lat_2,
lnd_lon_1,
lnd_lon_2,
landmask_file,
lat_dimname,
lon_dimname,
lon_type,
)
def fsurdat_modifier(parser):
"""Implementation of fsurdat_modifier command"""
# read the .cfg (config) file
cfg_path = str(parser.cfg_path)
config = ConfigParser()
config.read(cfg_path)
section = "modify_fsurdat_basic_options"
if not config.has_section(section):
abort("Config file does not have the expected section: " + section)
if parser.fsurdat_in == "UNSET":
# required: user must set these in the .cfg file
fsurdat_in = get_config_value(
config=config, section=section, item="fsurdat_in", file_path=cfg_path
)
else:
if config.has_option(section=section, option="fsurdat_in"):
abort("fsurdat_in is specified in both the command line and the config file, pick one")
fsurdat_in = str(parser.fsurdat_in)
# Error checking of input file
if not os.path.exists(fsurdat_in):
abort("Input fsurdat_in file does NOT exist: " + str(fsurdat_in))
if parser.fsurdat_out == "UNSET":
fsurdat_out = get_config_value(
config=config, section=section, item="fsurdat_out", file_path=cfg_path
)
else:
if config.has_option(section=section, option="fsurdat_out"):
abort("fsurdat_out is specified in both the command line and the config file, pick one")
fsurdat_out = str(parser.fsurdat_out)
# If output file exists, abort before starting work
if os.path.exists(fsurdat_out):
if not parser.overwrite:
errmsg = "Output file already exists: " + fsurdat_out
abort(errmsg)
else:
warnmsg = (
"Output file already exists"
+ ", but the overwrite option was selected so the file will be overwritten."
)
logger.warning(warnmsg)
(
lnd_lat_1,
lnd_lat_2,
lnd_lon_1,
lnd_lon_2,
landmask_file,
lat_dimname,
lon_dimname,
lon_type,
) = read_cfg_required_basic_opts(config, section, cfg_path)
# Create ModifyFsurdat object
modify_fsurdat = ModifyFsurdat.init_from_file(
fsurdat_in,
lnd_lon_1,
lnd_lon_2,
lnd_lat_1,
lnd_lat_2,
landmask_file,
lat_dimname,
lon_dimname,
lon_type,
)
# Read control information about the optional sections
(
idealized,
process_subgrid,
process_var_list,
include_nonveg,
dom_pft,
evenly_split_cropland,
) = read_cfg_option_control(
modify_fsurdat,
config,
section,
cfg_path,
)
# Read parts that are optional
(
max_sat_area,
std_elev,
soil_color,
lai,
sai,
hgt_top,
hgt_bot,
) = read_cfg_optional_basic_opts(modify_fsurdat, config, cfg_path, section)
# ------------------------------
# modify surface data properties
# ------------------------------
modify_optional(
modify_fsurdat,
idealized,
include_nonveg,
max_sat_area,
std_elev,
soil_color,
dom_pft,
evenly_split_cropland,
lai,
sai,
hgt_top,
hgt_bot,
)
#
# Handle optional sections
#
if process_subgrid:
subgrid = read_cfg_subgrid(config, cfg_path, numurbl=modify_fsurdat.get_urb_dens())
modify_fsurdat.set_varlist(subgrid, cfg_path)
logger.info("process_subgrid is complete")
else:
check_no_subgrid_section(config)
if process_var_list:
varlist = read_cfg_var_list(config, idealized=idealized)
update_list = modify_fsurdat.check_varlist(
varlist, allow_uppercase_vars=True, source="Config file: " + cfg_path
)
modify_fsurdat.set_varlist(update_list, cfg_path)
logger.info("process_var_list is complete")
else:
check_no_varlist_section(config)
# ----------------------------------------------
# Output the now modified CTSM surface data file
# ----------------------------------------------
write_output(modify_fsurdat.file, fsurdat_in, fsurdat_out, "fsurdat")