Repository navigation
Expand file tree
/
Copy pathplot_fitted_model.py
More file actions
383 lines (342 loc) · 13.8 KB
/
Copy pathplot_fitted_model.py
File metadata and controls
383 lines (342 loc) · 13.8 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
import os
import argparse
from configparser import ConfigParser
import pickle
# CD-NLGSSM imports
from cd_dynamax.src.utils.experiment_utils import (
build_results_dir,
create_cddynamax_model_from_config,
create_cddynamax_filter_from_config,
)
from cd_dynamax.src.utils.data_generator import generate_data_from_config
# Demo plotting import
from parameter_learning_plotting_utils import (
plot_mll_learning_curve,
learnable_params_to_1d_df,
plot_param_sequences,
plot_param_dist,
)
# Main function to plot fitted model to data
def plot_fitted_model_to_data(
config_path,
data_config_file,
model_config_file,
filter_config_file,
fit_config_file,
output_dir,
fit_key=None,
overrides={},
):
# Figure out and build the directory structure
results_dir = build_results_dir(
output_dir,
data_config_file,
model_config_file,
filter_config_file,
overrides=overrides,
)
# And add fit_config_file info
results_dir = os.path.join(
results_dir, os.path.splitext(os.path.basename(fit_config_file))[0]
)
# Check if the results directory exists, if not, print a warning
if not os.path.exists(results_dir):
print("Warning: Results directory does not exist at:", results_dir)
print("Please run the fit_model_to_data.py experiment to generate results.")
return
# Plotting dir will be inside results_dir
plotting_dir = os.path.join(results_dir, "plots")
os.makedirs(plotting_dir, exist_ok=True)
# Generate or load data
data, data_key = generate_data_from_config(
config_path=config_path,
data_config_file=data_config_file,
data_save_file=None,
overrides=overrides,
)
# Create and initialize the CD-NLGSSM model from the model config file
learnable_model, learnable_params, learnable_props = (
create_cddynamax_model_from_config(
config_path=config_path,
true_model_config_file=model_config_file,
overrides=overrides,
)
)
# Figure-out the filtering/smoothing settings from config
filter_hyperparams, filter_info = create_cddynamax_filter_from_config(
config_path=config_path,
filter_config_file=filter_config_file,
overrides=overrides,
)
# Full path to the fit config file
fit_config_filepath = os.path.join(config_path, fit_config_file)
# Check if the config file exists
if not os.path.exists(fit_config_filepath):
raise FileNotFoundError(
f"Configuration file '{fit_config_filepath}' not found."
)
## Figure out series of inferences based on inference config file
# Initialize fit config parser
config = ConfigParser()
config.read(fit_config_filepath)
# For each optimization method specified in the config
optim_configs = config.sections()
# Run SGD for parameter estimation
if "sgd" in optim_configs:
# SGD configuration
sgd_config = config["sgd"]
# If fit_keys are provided
fit_keys = fit_key if fit_key is not None else [sgd_config.getint("key", 0)]
# Iterate over the fit_key list
for idx, key in enumerate(fit_keys):
print(
f"Loading SGD MAP estimation results with fit_key: {key} (Index {idx + 1} of {len(fit_keys)})"
)
# Load the results, for each fit_key separately
with open(
os.path.join(results_dir, f"sgd_model_fit_fitkey{key}.pkl"), "rb"
) as f:
sgd_results = pickle.load(f)
print("SGD MAP estimation results loaded for fit_key:", key)
# Results dictionary format
"""
sgd_results={
'params_fitted': fit_results[0],
'loss_history': fit_results[1],
'params_history': None,
'grad_history': None,
}
"""
# Plot the marginal log likelihood learning curve
plot_mll_learning_curve(
true_model=data["dgmodel_info"]["model"],
true_params=data["dgmodel_info"]["params"],
true_emissions=data["emissions"],
t_emissions=data["t_emissions"],
marginal_lls=sgd_results["loss_history"],
filter_hyperparams=filter_hyperparams,
plot_save_path=os.path.join(
plotting_dir, f"mll_learning_curve_fitkey{key}"
),
)
# Extract interesting parameters into 1D dataframe format for later plotting
true_params_df = learnable_params_to_1d_df(
data["dgmodel_info"]["params"], learnable_props
)
init_params_df = learnable_params_to_1d_df(
learnable_params, learnable_props
)
fitted_params_df = learnable_params_to_1d_df(
sgd_results["params_fitted"], learnable_props
)
fitted_params_history_df = learnable_params_to_1d_df(
sgd_results["params_history"], learnable_props, has_batch_dim=True
)
# Plot parameter trajectories over SGD iterations
plot_param_sequences(
param_history=fitted_params_history_df,
true=true_params_df,
init=init_params_df,
pointwise_estimate=fitted_params_df,
burn_in_frac=0.0,
pairwise_plots=True,
plot_save_path=os.path.join(
plotting_dir, f"parameter_trajectories_fitkey{key}"
),
)
# Run MCMC for parameter estimation
if "mcmc" in optim_configs:
mcmc_config = config["mcmc"]
# If fit_keys are provided
fit_keys = fit_key if fit_key is not None else [mcmc_config.getint("key", 0)]
# Iterate over the fit_key list
for idx, key in enumerate(fit_keys):
print(
f"Loading MCMC MAP estimation results with fit_key: {key} (Index {idx + 1} of {len(fit_keys)})"
)
# Load the results, for each fit_key separately
load_results_file = os.path.join(
results_dir,
mcmc_config.get("type", "unknown") + f"_mcmc_model_fit_fitkey{key}.pkl",
)
with open(load_results_file, "rb") as f:
mcmc_results = pickle.load(f)
print("MCMC MAP estimation results loaded for fit_key:", key)
# Results dictionary format
"""
mcmc_results = {
'warmup_param_samples': mcmc_result[0],
'mcmc_param_samples': mcmc_result[1],
'warmup_log_probs': mcmc_result[2],
'mcmc_log_probs': mcmc_result[3],
}
"""
# Plot the marginal log likelihood learning curve
plot_mll_learning_curve(
true_model=data["dgmodel_info"]["model"],
true_params=data["dgmodel_info"]["params"],
true_emissions=data["emissions"],
t_emissions=data["t_emissions"],
marginal_lls=mcmc_results["mcmc_log_probs"],
filter_hyperparams=filter_hyperparams,
plot_save_path=os.path.join(
plotting_dir, f"mll_learning_curve_fitkey{key}"
),
)
# Extract interesting parameters in dataframe format for later plotting
true_params_df = learnable_params_to_1d_df(
data["dgmodel_info"]["params"], learnable_props
)
init_params_df = learnable_params_to_1d_df(
learnable_params, learnable_props
)
mcmc_samples_df = learnable_params_to_1d_df(
mcmc_results["mcmc_param_samples"], learnable_props, has_batch_dim=True
)
# Plot parameter trajectories over MCMC iterations
plot_param_sequences(
param_history=mcmc_samples_df,
true=true_params_df,
init=init_params_df,
pointwise_estimate=mcmc_samples_df.mean(axis=0).to_frame().T,
burn_in_frac=0.0,
pairwise_plots=True,
plot_save_path=os.path.join(
plotting_dir, f"parameter_trajectories_fitkey{key}"
),
)
# Plot parameter distributions from MCMC samples
plot_param_dist(
samples=mcmc_samples_df,
true=true_params_df,
init=init_params_df,
pointwise_estimate=mcmc_samples_df.mean(axis=0).to_frame().T,
burn_in_frac=0.0,
pairwise_plots=True,
plot_save_path=os.path.join(
plotting_dir, f"parameter_distributions_fitkey{key}"
),
)
if "scipy" in optim_configs or "scipy_jaxopt" in optim_configs:
config_key = "scipy" if "scipy" in optim_configs else "scipy_jaxopt"
scipy_config = config[config_key]
# If fit_keys are provided
fit_keys = fit_key if fit_key is not None else [scipy_config.getint("key", 0)]
# Iterate over the fit_key list
for idx, key in enumerate(fit_keys):
print(
f"Loading Scipy MAP estimation results with fit_key: {key} (Index {idx + 1} of {len(fit_keys)})"
)
# Load the results, for each fit_key separately
load_results_file = os.path.join(
results_dir, f"scipy_model_fit_fitkey{key}.pkl"
)
with open(load_results_file, "rb") as f:
scipy_results = pickle.load(f)
print("Scipy MAP estimation results loaded for fit_key:", key)
"""
scipy_results = {
'params_fitted': scipy_result.x,
'fun_value': scipy_result.fun,
'nfev': scipy_result.nfev,
'success': scipy_result.success,
'message': scipy_result.message,
'params_history': Only for SciPy
}
"""
# Plot the marginal log likelihood learning curve
plot_mll_learning_curve(
true_model=data["dgmodel_info"]["model"],
true_params=data["dgmodel_info"]["params"],
true_emissions=data["emissions"],
t_emissions=data["t_emissions"],
marginal_lls=scipy_results["loss_history"],
filter_hyperparams=filter_hyperparams,
plot_save_path=os.path.join(
plotting_dir, f"mll_learning_curve_fitkey{key}"
),
)
# Extract interesting parameters in dataframe format for later plotting
true_params_df = learnable_params_to_1d_df(
data["dgmodel_info"]["params"], learnable_props
)
init_params_df = learnable_params_to_1d_df(
learnable_params, learnable_props
)
fitted_params_df = learnable_params_to_1d_df(
scipy_results["params_fitted"], learnable_props
)
fitted_params_history_df = learnable_params_to_1d_df(
scipy_results["params_history"], learnable_props
)
# Plot parameter trajectories over SGD iterations
plot_param_sequences(
param_history=fitted_params_history_df,
true=true_params_df,
init=init_params_df,
pointwise_estimate=fitted_params_df,
burn_in_frac=0.0,
pairwise_plots=True,
plot_save_path=os.path.join(
plotting_dir, f"parameter_trajectories_fitkey{key}"
),
)
# Print a message indicating the completion of the experiment
print("Experiment completed. Results saved to:", results_dir)
# Main script gets two arguments: config file and data save file
if __name__ == "__main__":
# Create optional flags for comamand line arguments
parser = argparse.ArgumentParser(
description="Plot fitted model to data --- as run by fit_model_to_data.py according to specified configurations of data, model and filtering."
)
parser.add_argument(
"--config_path",
type=str,
default="../configs/",
help="Path to configuration files: (default: ../configs/)",
)
parser.add_argument(
"--data_config_file",
type=str,
default="data/true_l63_data",
help="Data configuration file: (default: true_l63_data)",
)
parser.add_argument(
"--model_config_file",
type=str,
default="model/l63_mech",
help="Model configuration file: (default: l63_mech)",
)
parser.add_argument(
"--filter_config_file",
type=str,
default="filter/ekf_StateFirst_EmissionsFirst",
help="Filter configuration file: (default: ekf_StateFirst_EmissionsFirst)",
)
parser.add_argument(
"--fit_config_file",
type=str,
default="fitting/fit_sgd",
help="Fitting algorithm configuration file: (default: fit_sgd)",
)
# Add optional data_key and ftf_key arguments, which can be a sequence of integers
parser.add_argument(
"--fit_key",
type=int,
nargs="+",
default=None,
help="Optional key to use for fitting. If None, the key from the fit config file will be used.",
)
parser.add_argument(
"--output_dir",
type=str,
default="results/fit_model_to_data",
help="Output directory for results: (default: results/fit_model_to_data)",
)
args = parser.parse_args()
# Revise this if overrides are needed
overrides = {}
if args.fit_key is not None:
pass
# Run the plot_fitted_model_to_data function with the provided arguments
plot_fitted_model_to_data(**args.__dict__)