-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpostprocessing.py
204 lines (183 loc) · 6.43 KB
/
postprocessing.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
"""Postprocess the trained models."""
import os
import itertools
from pathlib import Path
import numpy as np
import pandas as pd
import jax
import jax.numpy as jnp
import jax.tree_util as jtu
from jax_canveg import load_model
from jax_canveg.shared_utilities import compute_metrics, get_time
from tqdm import tqdm # pyright: ignore
jax.config.update("jax_enable_x64", True)
# Current directory
dir_mother = Path(os.path.dirname(os.path.realpath(__file__)))
################################################################
# JAX-CanVeg
################################################################
canopy_layers = ["1L", "ML"]
model_types = ["PB", "Hybrid"]
multi_optim_le_weight = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
combinations = list(
itertools.product(canopy_layers, model_types, multi_optim_le_weight)
)
for cl, mt, mow in tqdm(combinations):
# Step 0: Stay in the current directory
os.chdir(dir_mother)
# Step 1: Case folder name
dir_case = dir_mother / f"{mt}-{cl}-{mow}"
f_configs = dir_case / "configs.json"
if not f_configs.is_file():
print(f"The case does not exist: {dir_case}")
continue
else:
print(f"Processing the case: {dir_case} ...")
# Step 2: Load the model, forcings, and observations
model, met_train, met_test, obs_train, obs_test = load_model(f_configs)
timesteps_train, timesteps_test = get_time(met_train), get_time(met_test)
# Step 3: Run the model on both training and test datasets
states_train, drivers_train = model(met_train)
states_test, drivers_test = model(met_test)
can_train, can_test = states_train[-1], states_test[-1]
veg_train, veg_test = states_train[-2], states_test[-2]
soil_train, soil_test = states_train[-3], states_test[-3]
# Step 3-a: Remove some large numbers due to the numerical instability
@jnp.vectorize
def convert_instability_to_nan(d_e):
return jax.lax.cond(
jnp.abs(d_e) > 10000,
lambda: jnp.nan,
lambda: d_e,
)
can_train = jtu.tree_map(convert_instability_to_nan, can_train)
can_test = jtu.tree_map(convert_instability_to_nan, can_test)
veg_train = jtu.tree_map(convert_instability_to_nan, veg_train)
veg_test = jtu.tree_map(convert_instability_to_nan, veg_test)
soil_train = jtu.tree_map(convert_instability_to_nan, soil_train)
soil_test = jtu.tree_map(convert_instability_to_nan, soil_test)
# Step 4: Assemble key simulations
sim_train = np.array(
[
met_train.soilmoisture,
obs_train.LE,
obs_train.Fco2,
can_train.LE,
can_train.NEE,
veg_train.gs,
veg_train.Tsfc,
veg_train.Ps,
veg_train.GPP,
soil_train.resp,
]
).T
sim_test = np.array(
[
met_test.soilmoisture,
obs_test.LE,
obs_test.Fco2,
can_test.LE,
can_test.NEE,
veg_test.gs,
veg_test.Tsfc,
veg_test.Ps,
veg_test.GPP,
soil_test.resp,
]
).T
sim_train_df = pd.DataFrame(
sim_train,
index=timesteps_train,
columns=[
"SWC-obs",
"LE-obs",
"NEE-obs",
"LE",
"NEE",
"gs",
"Tsfc",
"Ps",
"GPP",
"Rsoil",
],
)
sim_test_df = pd.DataFrame(
sim_test,
index=timesteps_test,
columns=[
"SWC-obs",
"LE-obs",
"NEE-obs",
"LE",
"NEE",
"gs",
"Tsfc",
"Ps",
"GPP",
"Rsoil",
],
)
# Step 5: Calculate the metrics of LE and NEE
value_pairs = [
[can_train.LE, obs_train.LE],
[can_test.LE, obs_test.LE],
[can_train.NEE, obs_train.Fco2],
[can_test.NEE, obs_test.Fco2],
]
metric_values = []
for pred, true in value_pairs:
# print(pred.mean(), true.mean())
metrics = compute_metrics(pred, true, mask_naninf=True)
metric_values.append(list(metrics.values()))
metric_keys = list(metrics.keys())
metric_values = np.array(metric_values)
metric_df = pd.DataFrame(metric_values, columns=metric_keys) # pyright: ignore
metric_df.index = ["LE-train", "LE-test", "NEE-train", "NEE-test"]
# Step 6: Save the metrics and simulations
f_metrics = dir_case / "metrics.csv"
metric_df.to_csv(f_metrics)
f_sim_train = dir_case / "predictions_train.csv"
sim_train_df.to_csv(f_sim_train)
f_sim_test = dir_case / "predictions_test.csv"
sim_test_df.to_csv(f_sim_test)
################################################################
# Pure deep learning model
################################################################
w_set = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
# w_set = [0., 0.5, 1.0]
for w in tqdm(w_set):
# Step 0: Stay in the current directory
os.chdir(dir_mother)
# Step 1: Case folder name
dir_case = dir_mother / f"DNN_LE-GPP-{w}"
if not dir_case.is_dir():
print(f"The case does not exist: {dir_case}")
continue
else:
print(f"Processing the case: {dir_case} ...")
# Step 2: Load the predictions
f_sim_train = dir_case / "predictions_train.txt"
f_sim_test = dir_case / "predictions_test.txt"
sim_train, sim_test = np.loadtxt(f_sim_train), np.loadtxt(f_sim_test)
le_train, nee_train = sim_train[:, 0], sim_train[:, 1]
le_test, nee_test = sim_test[:, 0], sim_test[:, 1]
# print(le_train.shape, le_test.shape, nee_train.shape)
# print(obs_train.LE.shape)
# Step 3: Compute the metrics
value_pairs = [
[le_train, obs_train.LE], # pyright: ignore
[le_test, obs_test.LE], # pyright: ignore
[nee_train, obs_train.Fco2], # pyright: ignore
[nee_test, obs_test.Fco2], # pyright: ignore
]
metric_values = []
for pred, true in value_pairs:
metrics = compute_metrics(pred, true, mask_naninf=True)
metric_values.append(list(metrics.values()))
metric_keys = list(metrics.keys())
metric_values = np.array(metric_values)
metric_df = pd.DataFrame(metric_values, columns=metric_keys) # pyright: ignore
metric_df.index = ["LE-train", "LE-test", "NEE-train", "NEE-test"]
# Step 4: Save the metrics
f_metrics = dir_case / "metrics.csv"
metric_df.to_csv(f_metrics)