forked from cryotools/cosipy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_config.py
339 lines (282 loc) · 9.62 KB
/
convert_config.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
"""Convert old config.py and constants.py files into .toml.
This utility must be run from source!
To safely migrate before upgrading to the new configuration system:
.. code-block:: console
git fetch --all
git checkout master -- convert_config.py
python convert_config.py # generate .toml files
Otherwise, copy and run this file in the top-level directory of a COSIPY
source tree.
You MUST manually add the values for `create_static` in the generated
`utilities_config.toml`, as that utility script cannot be converted.
"""
import configparser
import inspect
import sys
import config
import constants
import toml
import utilities.aws2cosipy.aws2cosipyConfig as aws2cosipyConfig
import utilities.wrf2cosipy.wrf2cosipyConfig as wrf2cosipyConfig
class ModuleWrapper(object):
"""Hacky way to get module attributes."""
def __init__(self, module):
self.module = module
def __getattr__(self, name):
try:
return getattr(self.module, name)
except AttributeError:
return None
def set_module_params(module, parameters: dict, key_pairs: dict) -> dict:
"""Set parameters from module variables."""
for key, attributes in key_pairs.items():
parameters[key] = {}
for attr in attributes:
value = module.__getattr__(attr)
if value is None:
value = 0
parameters[key].update({attr: value})
return parameters
def get_config_params() -> dict:
"""Get module parameters from config.py."""
module = ModuleWrapper(sys.modules[config.__name__])
params = {}
table_keys = {
"SIMULATION_PERIOD": ("time_start", "time_end"),
"FILENAMES": ("data_path", "input_netcdf", "output_prefix"),
"RESTART": ("restart",),
"STAKE_DATA": (
"stake_evaluation",
"stakes_loc_file",
"stakes_data_file",
"eval_method",
"obs_type",
),
"TRANSIENT SNOWLINE DATA": (
"time_start_cali",
"time_end_cali",
"tsl_evaluation",
"write_csv_status",
"time_col_obs",
"tsla_col_obs",
"min_snowheight",
"tsl_method",
"tsl_normalize",
"tsl_data_file",
),
"RUN LAPSE RATES ONLINE": (
"station_altitude",
),
"DIMENSIONS": ("WRF", "WRF_X_CSPY", "northing", "easting"),
"COMPRESSION": ("compression_level",),
"PARALLELIZATION": ("slurm_use", "workers", "local_port"),
"FULL_FIELDS": ("full_field",),
"FORCINGS": ("force_use_TP", "force_use_N"),
"SUBSET": ("tile", "xstart", "xend", "ystart", "yend"),
}
params = set_module_params(
module=module, parameters=params, key_pairs=table_keys
)
# Different name
if "_" in config.output_netcdf:
output_split = config.output_netcdf.split("_") # remove date
else:
output_split = config.output_netcdf.split(".") # remove nc
output_prefix = "_".join(output_split[:-1])
params["FILENAMES"]["output_prefix"] = output_prefix
params["OUTPUT_VARIABLES"] = get_output_params()
return params
def get_output_params() -> dict:
"""Get output variable selection from cosipy/output."""
output_config = configparser.ConfigParser()
output_config.read("./cosipy/output")
variables = output_config["vars"]
params = {}
params["output_atm"] = variables["atm"]
params["output_internal"] = variables["internal"]
params["output_full"] = variables["full"]
return params
def get_constants_params() -> dict:
"""Get module parameters from constants.py."""
module = ModuleWrapper(sys.modules[constants.__name__])
params = {}
table_keys = {
"GENERAL": ("dt", "max_layers", "z"),
"PARAMETERIZATIONS": (
"stability_correction",
"albedo_method",
"densification_method",
"penetrating_method",
"roughness_method",
"saturation_water_vapour_method",
"thermal_conductivity_method",
"sfc_temperature_method",
),
"INITIAL_CONDITIONS": (
"initial_snowheight_constant",
"initial_snow_layer_heights",
"initial_glacier_height",
"initial_glacier_layer_heights",
"initial_top_density_snowpack",
"initial_bottom_density_snowpack",
"temperature_bottom",
"const_init_temp",
"zlt1",
"zlt2",
),
"PRECIPITATION": (
"center_snow_transfer_function",
"spread_snow_transfer_function",
"mult_factor_RRR",
"minimum_snow_layer_height",
"minimum_snowfall",
),
"REMESHING": (
"remesh_method",
"first_layer_height",
"layer_stretching",
"merge_max",
"density_threshold_merging",
"temperature_threshold_merging",
),
"CONSTANTS": (
"constant_density",
"albedo_fresh_snow",
"albedo_firn",
"albedo_ice",
"albedo_mod_snow_aging",
"albedo_mod_snow_depth",
"t_star_wet",
"t_star_dry",
"t_star_K",
"t_star_cutoff",
"roughness_fresh_snow",
"roughness_ice",
"roughness_firn",
"aging_factor_roughness",
"snow_ice_threshold",
"lat_heat_melting",
"lat_heat_vaporize",
"lat_heat_sublimation",
"spec_heat_air",
"spec_heat_ice",
"spec_heat_water",
"k_i",
"k_w",
"k_a",
"water_density",
"ice_density",
"air_density",
"sigma",
"zero_temperature",
"surface_emission_coeff",
),
}
params = set_module_params(
module=module, parameters=params, key_pairs=table_keys
)
return params
def get_aws2cosipy_params() -> dict:
"""Get module parameters from aws2cosipyConfig.py."""
module = ModuleWrapper(sys.modules[aws2cosipyConfig.__name__])
params = {}
table_keys = {
"names": (
"PRES_var",
"T2_var",
"in_K",
"RH2_var",
"G_var",
"RRR_var",
"U2_var",
"LWin_var",
"SNOWFALL_var",
"N_var",
),
"coords": ("WRF", "aggregate", "aggregation_step", "ELEV_model", "delimiter"),
"radiation": (
"radiationModule",
"LUT",
"dtstep",
"tcart",
"timezone_lon",
"zeni_thld",
),
"points": ("point_model", "plon", "plat", "hgt"),
"station": ("stationName", "stationAlt", "stationLat"),
"lapse": ("lapse_T", "lapse_RH", "lapse_RRR", "lapse_SNOWFALL"),
}
params = set_module_params(
module=module, parameters=params, key_pairs=table_keys
)
return params
def get_wrf2cosipy_params() -> dict:
"""Get module parameters from wrf2cosipyConfig.py."""
module = ModuleWrapper(sys.modules[wrf2cosipyConfig.__name__])
params = {}
table_keys = {"constants": ("hu", "lu_class")}
params = set_module_params(
module=module, parameters=params, key_pairs=table_keys
)
return params
def get_create_static_params() -> dict:
"""Get module parameters from create_static.py.
As create_static cannot be imported, this sets parameters to a
default value instead.
"""
params = {}
table_keys = {
"paths": ("static_folder", "dem_path", "shape_path", "output_file"),
"coords": (
"tile",
"aggregate",
"aggregate_degree",
"longitude_upper_left",
"latitude_upper_left",
"longitude_lower_right",
"latitude_lower_right",
),
}
for key, attributes in table_keys.items():
params[key] = {}
for attr in attributes:
if key == "paths":
value = ""
elif key == "coords" and attr in ["tile", "aggregate"]:
value = True
else:
value = 0.0
params[key].update({attr: value})
return params
def get_utilities_params() -> dict:
"""Aggregate paramters for all utilities."""
params = {}
params["aws2cosipy"] = get_aws2cosipy_params()
params["create_static"] = get_create_static_params()
params["wrf2cosipy"] = get_wrf2cosipy_params()
return params
def write_toml(parameters: dict, filename: str):
"""Write parameters to .toml file."""
with open(f"{filename}.toml", "w") as f:
toml.dump(parameters, f)
print(f"Generated {filename}.toml")
def print_warning():
tag = (
f"\n{79*'-'}\n"
"Configuration for create_static must be manually added to the generated `utilities_config.toml`.",
"All custom configuration variables not present in the master branch will be lost!",
"Make sure to add these back manually." f"\n{79*'-'}\n",
)
print("\n".join(tag))
def main():
print_warning()
script_path = inspect.getfile(inspect.currentframe())
toml_suffix = script_path.split("/")[-2] # avoid overwrite
config_params = get_config_params()
write_toml(parameters=config_params, filename=f"config")
constants_params = get_constants_params()
write_toml(parameters=constants_params, filename=f"constants")
utilities_params = get_utilities_params()
write_toml(parameters=utilities_params, filename=f"utilities_config")
if __name__ == "__main__":
main()