forked from KriFos1/ESMDA-MF
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_results.py
More file actions
2571 lines (2191 loc) · 95.5 KB
/
Copy pathplot_results.py
File metadata and controls
2571 lines (2191 loc) · 95.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
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
import argparse
import pickle
from pathlib import Path
import h5py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.ticker import MaxNLocator
from scipy.stats import norm
from scipy.ndimage import gaussian_filter
import imageio.v2 as imageio
from pathlib import Path
from matplotlib.ticker import ScalarFormatter
from matplotlib.colors import TwoSlopeNorm
import re
from typing import Iterable
#from run_DA import post_loss
# python plot_results.py --assim-ind 30 --assim-range 25 35 --outdir Plotting --rh-clim 1 30 --rv-clim 1 30 --aspect-to-plot Mean"
DIMS = (23,3,34)
#DIMS = (19,3,20)
MIN_RATIO = 1.0
MAX_RATIO = 4.0
METER_TO_FEET = 3.28084
CELL_THICKNESS_FT = 1.0 * METER_TO_FEET
DX = 5#CELL_THICKNESS_FT * 1.0 * 4.0
DZ = 0.437*12#CELL_THICKNESS_FT * 1.0
TOOLS = [
("6kHz", "83ft"),
("12kHz", "83ft"),
("24kHz", "83ft"),
("24kHz", "43ft"),
("48kHz", "43ft"),
("96kHz", "43ft"),
]
OBSERVED_DATA_ORDER_BFIELD = [
"real(Bxx)",
"real(Bxy)",
"real(Bxz)",
"real(Byx)",
"real(Byy)",
"real(Byz)",
"real(Bzx)",
"real(Bzy)",
"real(Bzz)",
"img(Bxx)",
"img(Bxy)",
"img(Bxz)",
"img(Byx)",
"img(Byy)",
"img(Byz)",
"img(Bzx)",
"img(Bzy)",
"img(Bzz)",
]
SELECTED_DATA = [
"real(Bxx)",
"real(Bxz)",
"real(Bzx)",
"real(Bzz)",
"img(Bxx)",
"img(Bxz)",
"img(Bzx)",
"img(Bzz)",
]
SELECTED_DATA_INDICES = [OBSERVED_DATA_ORDER_BFIELD.index(name) for name in SELECTED_DATA]
def parse_args() -> argparse.Namespace:
script_dir = Path(__file__).resolve().parent
project_root = Path("/home/AD.NORCERESEARCH.NO/mlie/3DGiG/")#script_dir.parent
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
"--example-folder",
type = str,
default = "",
help="Name of folder containing results and data for example run (to be appended script-dir)",
)
# parse just this known arg (leave the rest for the full parser)
known, _ = parser.parse_known_args()
if known.example_folder:
script_dir = (script_dir / known.example_folder).resolve()
# now create the real parser (with help) and add all args using updated script_dir
parser = argparse.ArgumentParser(description="Plot posterior predictions and parameters from ESMDA-Hybrid run.")
parser.add_argument("--example-folder", type=str, default=known.example_folder,
help="Name of a subfolder under the script directory (appended to script_dir).")
parser.add_argument("--assim-ind", type=int, required=True,
help="Assimilation index used in inversion_results_assim_{assim_ind}.pkl")
parser.add_argument(
"--data-row",
type=int,
default=None,
help="Row index for data.pkl/var.pkl. Defaults to assim-ind if not provided.",
)
parser.add_argument(
"--results-file",
type=Path,
default=None,
help="Optional explicit path to inversion results pickle.",
)
parser.add_argument(
"--assim-range",
nargs=2,
type=int,
default=None,
help="Optional range of assimilation indices [start end] for evolution plots.",
)
parser.add_argument(
"--logging-ind",
type=int,
default=None,
help="Logging point index in the reference model. Defaults to assim-ind.",
)
parser.add_argument(
"--reference-model",
type=Path,
#default=project_root / "inversion" / "data" / "Benchmark-3" / "globalmodel.h5",
default=project_root / "Benchmark-3" / "globalmodel.h5",
help="Path to reference globalmodel.h5 used to locate the logging point.",
)
parser.add_argument(
"--aspect-to-plot",
choices=["Mean", "Median", "Best", "Worst"],
type = str,
default="Mean",
help="Which ensemble aspect to plot."
)
parser.add_argument(
"--rh-clim",
nargs=2,
type=float,
default=None,
help="Color limits for rh (vmin vmax), e.g. --rh-clim 1 40",
)
parser.add_argument(
"--rv-clim",
nargs=2,
type=float,
default=None,
help="Color limits for rv (vmin vmax), e.g. --rv-clim -1 40",
)
parser.add_argument("--data-file", type=Path, default=script_dir / "data.pkl", help="Path to true data pickle.")
parser.add_argument("--var-file", type=Path, default=script_dir / "var.pkl", help="Path to variance pickle.")
parser.add_argument("--outdir", type=str, default="Plotting", help="Name of subdirectory where figures are written.")
return parser.parse_args()
def _stack_vector_list(values: list[np.ndarray], field_name: str) -> np.ndarray:
if not values:
raise ValueError(f"No entries found in '{field_name}'.")
stacked = np.asarray([np.asarray(v, dtype=float).reshape(-1) for v in values], dtype=float)
if stacked.ndim != 2:
raise ValueError(f"Unexpected shape for '{field_name}': {stacked.shape}")
return stacked
def load_results(
results_file: Path,
) -> tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray | None, np.ndarray | None, np.ndarray | None, np.ndarray | None, np.ndarray | None, np.ndarray | None]:
with results_file.open("rb") as f:
results = pickle.load(f)
if "posterior_params" not in results or "posterior_predictions" not in results:
raise KeyError(
f"Missing required keys in {results_file}. Found keys: {list(results.keys())}"
)
post_param = _stack_vector_list(results["posterior_params"], "posterior_params")
post_pred = _stack_vector_list(results["posterior_predictions"], "posterior_predictions")
post_mda_param = results.get("post_mda_params")
prior_param = results.get("prior_params")
post_loss = results.get("posterior_losses")
prior_mean_rml = results.get("prior_mean_rml", None)
prior_covariance_rml = results.get("prior_covariance_rml", None)
post_jac = results.get("posterior_jacobian", None)
post_jac_phys = results.get("posterior_jacobian_phys", None)
return post_param, post_pred, post_mda_param, prior_param, post_loss, prior_mean_rml, prior_covariance_rml, post_jac, post_jac_phys
def _resolve_tool_key(row: pd.Series, tool: tuple[str, str]) -> object:
if tool in row.index:
return tool
tool_normalized = str(tool).replace(" ", "")
for col in row.index:
if isinstance(col, str) and col.replace(" ", "") == tool_normalized:
return col
raise KeyError(f"Tool key {tool} not found in dataframe columns.")
def load_true_data_and_var(data_file: Path, var_file: Path, data_row: int) -> tuple[np.ndarray, np.ndarray]:
data_df = pd.read_pickle(data_file)
var_df = pd.read_pickle(var_file)
if not (0 <= data_row < len(data_df)):
raise IndexError(f"data_row={data_row} out of bounds for dataframe with {len(data_df)} rows.")
data_series = data_df.iloc[data_row]
var_series = var_df.iloc[data_row]
true_data = []
variances = []
for tool in TOOLS:
data_key = _resolve_tool_key(data_series, tool)
var_key = _resolve_tool_key(var_series, tool)
data_values = np.asarray(data_series[data_key], dtype=float)
var_cell = var_series[var_key]
if isinstance(var_cell, (list, tuple)) and len(var_cell) >= 2:
var_values = np.asarray(var_cell[1], dtype=float)
else:
var_values = np.asarray(var_cell, dtype=float)
true_data.append(data_values[SELECTED_DATA_INDICES])
variances.append(var_values[SELECTED_DATA_INDICES])
return np.concatenate(true_data), np.concatenate(variances)
def reconstruct_rh_rv(post_param: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
nx, _, nz = DIMS
n_param_per_type = nx * nz
expected_size = 2 * n_param_per_type
if post_param.shape[1] != expected_size:
raise ValueError(
f"Unexpected parameter size {post_param.shape[1]}. Expected {expected_size} "
f"from dims={DIMS}."
)
rh = post_param[:, :n_param_per_type].reshape(-1, nx, nz, order="C")
latent_ratio = post_param[:, n_param_per_type:].reshape(-1, nx, nz, order="C")
u = norm.cdf(latent_ratio)
ratio = MIN_RATIO * np.power(MAX_RATIO / MIN_RATIO, u)
rv = np.log(np.exp(rh) * ratio)
return np.exp(rh), np.exp(rv)
def _centers_to_edges(centers: np.ndarray) -> np.ndarray:
if centers.ndim != 1 or centers.size < 2:
raise ValueError("Need at least two center points to construct edges.")
edges = np.empty(centers.size + 1, dtype=float)
edges[1:-1] = 0.5 * (centers[:-1] + centers[1:])
first_step = centers[1] - centers[0]
last_step = centers[-1] - centers[-2]
edges[0] = centers[0] - 0.5 * first_step
edges[-1] = centers[-1] + 0.5 * last_step
return edges
def build_local_grid_axes(reference_model: Path, logging_ind: int) -> dict[str, np.ndarray | float]:
with h5py.File(reference_model, "r") as f:
wx = np.asarray(f["wellpath"]["X"]).reshape(-1)
tvd = np.asarray(f["wellpath"]["Z"]).reshape(-1)
if not (0 <= logging_ind < wx.size):
raise IndexError(
f"logging-ind={logging_ind} out of bounds for wellpath with {wx.size} points."
)
well_x_ft = float(wx[logging_ind] * METER_TO_FEET)
well_tvd_ft = float(tvd[logging_ind] * METER_TO_FEET)
nx, _, nz = DIMS
x_centers = well_x_ft + (np.arange(nx) - nx // 2) * DX
z_centers = well_tvd_ft + (np.arange(nz) - nz // 2) * DZ
x_edges = _centers_to_edges(x_centers)
z_edges = _centers_to_edges(z_centers)
return {
"well_x_ft": well_x_ft,
"well_tvd_ft": well_tvd_ft,
"x_centers": x_centers,
"z_centers": z_centers,
"x_edges": x_edges,
"z_edges": z_edges,
}
def plot_predictions_over_assim(
assim_indices: list[int],
results_dir: Path,
data_file: Path,
var_file: Path,
outdir: Path,
tool_slice: slice | None = None,
) -> Path:
"""
Plot evolution of ensemble predictions and observations vs assimilation index,
for the selected data components and tools.
"""
assim_indices = sorted(assim_indices)
n_assim = len(assim_indices)
if n_assim == 0:
raise ValueError("assim_indices is empty")
# --- Load first step to infer dimensions
first = assim_indices[0]
results_file = results_dir / f"inversion_results_assim_{first}.pkl"
if not results_file.exists():
raise FileNotFoundError(results_file)
post_param, post_pred0, _, _, _, _, _, _,_ = load_results(results_file)
true_data0, variances0 = load_true_data_and_var(data_file, var_file, data_row=first)
n_selected = len(SELECTED_DATA)
max_points = min(
post_pred0.shape[1],
true_data0.size,
variances0.size,
len(TOOLS) * n_selected,
)
n_tools_full = max_points // n_selected
if n_tools_full == 0:
raise ValueError("Not enough points to form tool responses for selected data.")
# Choose which tools to plot
if tool_slice is None:
tool_slice = slice(0, n_tools_full)
tool_indices = range(*tool_slice.indices(n_tools_full))
n_tools = len(tool_indices)
n_points = n_tools * n_selected
n_real = post_pred0.shape[0]
# Preallocate arrays: (n_assim, n_tools, n_selected)
p05 = np.empty((n_assim, n_tools, n_selected))
p50 = np.empty((n_assim, n_tools, n_selected))
p95 = np.empty((n_assim, n_tools, n_selected))
true_mat_all = np.empty((n_assim, n_tools, n_selected))
sigma_mat_all = np.empty((n_assim, n_tools, n_selected))
# --- Fill over assimilation indices
for i, aind in enumerate(assim_indices):
results_file = results_dir / f"inversion_results_assim_{aind}.pkl"
if not results_file.exists():
raise FileNotFoundError(results_file)
_, post_pred, _, _, _, _,_,_,_ = load_results(results_file)
true_data, variances = load_true_data_and_var(data_file, var_file, data_row=aind)
max_points = min(
post_pred.shape[1],
true_data.size,
variances.size,
len(TOOLS) * n_selected,
)
n_points = n_tools * n_selected
idx_list = []
for t in tool_indices:
start = t * n_selected
stop = start + n_selected
idx_list.extend(range(start, stop))
idx_arr = np.array(idx_list, dtype=int)
pred = post_pred[:, idx_arr]
true_vals = true_data[idx_arr]
var_vals = np.maximum(variances[idx_arr], 0.0)
pred_mat = pred.reshape(n_real, n_tools, n_selected)
true_mat = true_vals.reshape(n_tools, n_selected)
sigma_mat = np.sqrt(var_vals.reshape(n_tools, n_selected))
p05[i] = np.percentile(pred_mat, 5, axis=0)
p50[i] = np.percentile(pred_mat, 50, axis=0)
p95[i] = np.percentile(pred_mat, 95, axis=0)
true_mat_all[i] = true_mat
sigma_mat_all[i] = sigma_mat
# --- Plot vs assimilation index
n_cols = 2
n_rows = int(np.ceil(n_selected / n_cols))
fig, axes = plt.subplots(
n_rows, n_cols,
figsize=(14, 3.8 * n_rows),
sharex=True,
constrained_layout=True,
)
axes = np.atleast_1d(axes).ravel()
x_assim = np.asarray(assim_indices)
x = 5.0 * x_assim # assim_ind = 40 -> 200 ft
tool_dist = [f"{dist}" for _, dist in np.array(TOOLS)[list(tool_indices)]]
if tool_slice is not None:
tool_labels = [f"{freq}" for freq, _ in np.array(TOOLS)[list(tool_indices)]]
suffix = tool_dist[0]
else:
tool_labels = [f"{freq}\n{dist}" for freq, dist in np.array(TOOLS)[list(tool_indices)]]
suffix = ""
colors = plt.cm.tab10(np.linspace(0, 1, n_tools))
for idx, data_name in enumerate(SELECTED_DATA):
ax = axes[idx]
for t in range(n_tools):
ax.fill_between(
x, p05[:, t, idx], p95[:, t, idx],
alpha=0.15, color=colors[t],
)
ax.plot(
x, p50[:, t, idx],
color=colors[t], lw=2,
label=f"Pred median - {tool_labels[t]}" if idx == 0 else None,
)
ax.errorbar(
x,
true_mat_all[:, t, idx],
yerr=sigma_mat_all[:, t, idx],
fmt="o",
color=colors[t],
mfc="white",
ms=4,
ecolor=colors[t],
elinewidth=0.8,
capsize=2.0,
label=f"True ±1σ - {tool_labels[t]}" if idx == 0 else None,
)
ax.set_title(data_name)
if tool_slice is not None:
ax.set_ylabel(f"Signal for tool distance {tool_dist[0]}")
else:
ax.set_ylabel("Signal")
ax.grid(alpha=0.25)
for ax in axes[n_selected:]:
ax.axis("off")
for ax in axes[max(0, n_selected - n_cols):n_selected]:
ax.set_xlabel("Logging position, x [ft]")
if n_selected > 0:
axes[0].legend(loc="best", fontsize=8)
fig.suptitle(f"Posterior predictions vs. logging positions")
outdir.mkdir(parents=True, exist_ok=True)
out_path = outdir / f"posterior_predictions_over_assim_{assim_indices[0]}to{assim_indices[-1]}_{suffix}.png"
fig.savefig(out_path, dpi=200)
plt.close(fig)
return out_path
def plot_predictions(
post_pred: np.ndarray,
true_data: np.ndarray,
variances: np.ndarray,
assim_ind: int,
outdir: Path,
tool_slice: slice | None = None,
suffix: str = "",
) -> Path:
n_selected = len(SELECTED_DATA)
# Determine how many tools are in the full vector
max_points = min(
post_pred.shape[1],
true_data.size,
variances.size,
len(TOOLS) * n_selected,
)
n_tools_full = max_points // n_selected
if n_tools_full == 0:
raise ValueError("Not enough points to form tool responses for selected data.")
# Choose which tools to plot
if tool_slice is None:
tool_slice = slice(0, n_tools_full)
tool_indices = range(*tool_slice.indices(n_tools_full))
n_tools = len(tool_indices)
# Restrict predictions/obs/vars to those tools
# layout is [tool0 block, tool1 block, ...]
# build an index for the selected tools
idx_list = []
for t in tool_indices:
start = t * n_selected
stop = start + n_selected
idx_list.extend(range(start, stop))
idx_arr = np.array(idx_list, dtype=int)
pred = post_pred[:, idx_arr]
true_vals = true_data[idx_arr]
var_vals = np.maximum(variances[idx_arr], 0.0)
pred_mat = pred.reshape(pred.shape[0], n_tools, n_selected)
true_mat = true_vals.reshape(n_tools, n_selected)
sigma_mat = np.sqrt(var_vals.reshape(n_tools, n_selected))
print(np.min(sigma_mat))
print(np.max(sigma_mat))
print(np.min(true_mat))
print(np.max(true_mat))
p05 = np.percentile(pred_mat, 5, axis=0)
p50 = np.percentile(pred_mat, 50, axis=0)
p95 = np.percentile(pred_mat, 95, axis=0)
n_cols = 2
n_rows = int(np.ceil(n_selected / n_cols))
fig, axes = plt.subplots(
n_rows, n_cols, figsize=(14, 3.8 * n_rows),
sharex=True, constrained_layout=True
)
axes = np.atleast_1d(axes).ravel()
x = np.arange(n_tools)
tool_labels = [f"{freq}\n{dist}" for (freq, dist) in np.array(TOOLS)[list(tool_indices)]]
for idx, data_name in enumerate(SELECTED_DATA):
ax = axes[idx]
ax.fill_between(x, p05[:, idx], p95[:, idx],
alpha=0.25, color="tab:blue", label="Pred. p05–p95")
ax.plot(x, p50[:, idx], color="tab:blue", lw=2, label="Pred. median")
ax.errorbar(
x,
true_mat[:, idx],
yerr=sigma_mat[:, idx],
fmt="ko",
ecolor="0.55",
elinewidth=1.0,
capsize=2.0,
ms=4,
label="True ±1σ",
)
ax.set_title(data_name)
ax.set_ylabel("Signal")
ax.set_xticks(x)
ax.set_xticklabels(tool_labels)
ax.grid(alpha=0.25)
if idx == 0:
ax.legend(loc="best")
for ax in axes[n_selected:]:
ax.axis("off")
for ax in axes[max(0, n_selected - n_cols):n_selected]:
ax.set_xlabel("Tool setting")
fig.suptitle(f"Posterior Predictions Across Realizations (assim {assim_ind}) {suffix}")
out_path = outdir / f"posterior_predictions_assim_{assim_ind}{suffix}.png"
fig.savefig(out_path, dpi=200)
plt.close(fig)
return out_path
def plot_model_uncertainty_from_post_jac(
rh: np.ndarray,
rv: np.ndarray,
post_jac: list[np.ndarray] | np.ndarray,
grid_axes: dict,
outdir: Path,
assim_ind: int,
partial_deriv:bool = False,
jacobian_member: int | None = None, # None->use ensemble mean
reg: float = 1e-6,
data_noise_var: np.ndarray = 1.0,
cmap: str = "viridis",
save: bool = True,
) -> Path:
"""
Compute and plot relative model uncertainty = std/mean from post_jac (ensemble list/array).
- post_jac: list of (ndata, nparams) arrays or array shape (nens, ndata, nparams).
- grid_axes: output of build_local_grid_axes(...)
'drh_dm_bounded_vec','drv_dm_bounded_vec') required when which in ('rh_phys','rv_phys').
"""
outdir.mkdir(parents=True, exist_ok=True)
# normalize post_jac to stacked array (nens, ndata, nparams)
if isinstance(post_jac, np.ndarray):
if post_jac.ndim == 3:
jac_stack = post_jac
elif post_jac.ndim == 2:
jac_stack = np.expand_dims(post_jac, axis=0)
else:
raise ValueError("post_jac ndarray must be 2D or 3D")
elif isinstance(post_jac, list):
if len(post_jac) == 0:
raise ValueError("post_jac is empty")
jac_stack = np.stack(post_jac, axis=0)
else:
raise TypeError("post_jac must be list or ndarray")
nens, ndata, nparams = jac_stack.shape
# choose Jacobian to use
if jacobian_member is None:
J = np.mean(jac_stack, axis=0) # (ndata, nparams)
else:
J = jac_stack[jacobian_member]
# infer grid dims
nx = int(np.asarray(grid_axes["x_centers"]).size)
nz = int(np.asarray(grid_axes["z_centers"]).size)
nm = nx * nz
if nparams != 2 * nm:
raise ValueError(f"nparams ({nparams}) != 2*nx*nz ({2 * nm})")
data_var = np.asarray(data_noise_var).reshape(-1)
if data_var.size != ndata:
raise ValueError(f"data_noise_var length {data_var.size} != ndata {ndata}")
# avoid division by zero
data_var_safe = np.maximum(data_var, 1e-16)
Rinv = 1.0 / data_var_safe
# compute J^T R^{-1} J efficiently: scale rows of J by Rinv then multiply
JT_Rinv_J = J.T @ (Rinv[:, np.newaxis] * J)
# regularization: treat small reg (<1e-12) as relative fraction of trace
if 0 < reg < 1e-12:
diag_reg = (np.trace(JT_Rinv_J) / nparams) * reg
else:
diag_reg = reg
A = JT_Rinv_J + diag_reg * np.eye(nparams)
# invert with fallback
try:
Cov = np.linalg.inv(A)
except np.linalg.LinAlgError:
Cov = np.linalg.pinv(A)
std = np.sqrt(np.maximum(np.real(np.diag(Cov)), 0.0)) # (nparams,)
std_m = std[:nm]
std_z = std[nm:]
eps = 1e-12
# prepare mean denominators
if partial_deriv: # in optimizer space
var_name_1 = "log rh bounded"
var_name_2 = "latent_ratio"
else: # from simulator in physical space
var_name_1 = "rh"
var_name_2 = "rv"
# Helper: reduce model array to a 1D mean vector of length nm in C-order.
def to_mean_flat(vec, nm):
a = np.asarray(vec)
if a.size == nm:
return a.reshape(-1) # already flat
# possible shapes: (nx,nz) or (nz,nx) or (nens,nx,nz) or (nens,nz,nx)
if a.ndim == 3:
# average over ensemble axis
a = a.mean(axis=0)
if a.ndim == 2:
# detect orientation: prefer shape (nx,nz) used in your code, otherwise try transpose
if a.shape == (nx, nz):
flat = a.reshape(-1, order='C')
elif a.shape == (nz, nx):
flat = a.T.reshape(-1, order='C')
else:
raise ValueError(f"unexpected 2D shape for model array: {a.shape}")
return flat
raise ValueError(f"unexpected shape for model array: {a.shape}")
denom1_vec = to_mean_flat(rh, nm)
denom2_vec = to_mean_flat(rv, nm)
# Determine which std vector corresponds to which denom.
# If post_jacates are in optimizer-space, std_m/std_z map to optimizer params (m,z).
# If post_jacates are in physical-space, caller should have passed jacobians and params
# such that std_m corresponds to the first block (rh or similar) and std_z to the second (rv).
rel_unc_1 = (std_m / (np.abs(denom1_vec) + eps)).reshape((nx, nz), order="C")
rel_unc_2 = (std_z / (np.abs(denom2_vec) + eps)).reshape((nx, nz), order="C")
field_1 = rel_unc_1.T
field_2 = rel_unc_2.T
vmin = min(field_1.min(), field_2.min())
vmax = max(field_1.max(), field_2.max())
title_1 = f"Relative uncertainty std/mean in {var_name_1} (assim {assim_ind})"
title_2 = f"Relative uncertainty std/mean in {var_name_2} (assim {assim_ind})"
# plot
fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True)
ax_1 = axes[0]
ax_2 = axes[1]
im = _plot_field_panel(ax_1, field_1, grid_axes, title_1, cmap, vmin=vmin, vmax=vmax)
im = _plot_field_panel(ax_2, field_2, grid_axes, title_2, cmap, vmin=vmin, vmax=vmax)
cb = fig.colorbar(im, ax=[ax_1, ax_2], fraction=0.046, pad=0.02)
cb.set_label('model uncertainty')
outpath = outdir / f"model_uncertainty_{var_name_1}_{var_name_2}_assim_{assim_ind:03d}.png"
if save:
fig.savefig(outpath, dpi=200)
plt.close(fig)
return outpath
else:
plt.show()
return outdir
def plot_posterior_jacobian_assim(
post_jac: list[np.ndarray] | np.ndarray,
assim_ind: int,
grid_axes: dict,
outdir: Path,
tool_slice: slice | None = None,
show_svd: bool = False,
cmap: str = "viridis",
save: bool = True,
partial_deriv: bool = False,
) -> Path:
"""
Plot aggregated spatial Jacobian maps per selected data (one pair of maps per SELECTED_DATA).
Aggregation: L2 across tool-settings for that selected data (over selected tools).
"""
outdir.mkdir(parents=True, exist_ok=True)
# normalize post_jac -> (nens, ndata, nparams)
if isinstance(post_jac, np.ndarray):
if post_jac.ndim == 3:
jac_stack = post_jac
elif post_jac.ndim == 2:
jac_stack = np.expand_dims(post_jac, axis=0)
else:
raise ValueError("post_jac ndarray must be 2D or 3D")
elif isinstance(post_jac, list):
if len(post_jac) == 0:
raise ValueError("post_jac is empty")
jac_stack = np.stack(post_jac, axis=0)
else:
raise TypeError("post_jac must be list or ndarray")
nens, ndata, nparams = jac_stack.shape
# grid dims
nx = int(np.asarray(grid_axes["x_centers"]).size)
nz = int(np.asarray(grid_axes["z_centers"]).size)
nm = nx * nz
if nparams != 2 * nm:
raise ValueError(f"nparams ({nparams}) != 2*nx*nz ({2 * nm})")
# Determine tools selection
n_selected = len(SELECTED_DATA)
max_points = min(n_data := ndata, len(TOOLS) * n_selected)
n_tools_full = max_points // n_selected
if n_tools_full == 0:
raise ValueError("Not enough points to form tool responses for selected data.")
if tool_slice is None:
tool_slice = slice(0, n_tools_full)
tool_indices = range(*tool_slice.indices(n_tools_full))
if(tool_slice.stop - tool_slice.start) == 1:
t_idx = list(tool_indices)[0]
tool_entry = TOOLS[t_idx]
if isinstance(tool_entry, (list, tuple)):
tool_label = f"{tool_entry[0]}{tool_entry[1]}"
else:
tool_label = str(tool_entry)
else:
tool_label = f"tools{tool_slice.start}to{tool_slice.stop - 1}"
# build index list for those tools (same ordering as predictions)
idx_list = []
for t in tool_indices:
start = t * n_selected
stop = start + n_selected
idx_list.extend(range(start, stop))
idx_arr = np.array(idx_list, dtype=int)
n_tools = len(tool_indices)
if partial_deriv: # in optimizer space
var_name_1 = "log rh bounded"
var_name_2 = "latent_ratio"
else: # from simulator in physical space
var_name_1 = "rh"
var_name_2 = "rv"
# ensemble-mean Jacobian (ndata, nparams)
J_mean = np.mean(jac_stack, axis=0)
# For each selected data index (0..n_selected-1), collect rows across chosen tools:
# rows = [t*n_selected + data_idx for t in tool_indices]
per_data_maps_m = []
per_data_maps_z = []
for data_idx in range(n_selected):
rows = np.array([t * n_selected + data_idx for t in tool_indices], dtype=int)
# ensure rows within bounds
rows = rows[rows < ndata]
if rows.size == 0:
raise ValueError(f"No rows found for data {data_idx} with selected tools")
# aggregate across rows: L2 across tool rows of absolute Jacobian entries, averaged over ensemble
# First compute per-ensemble L2 across rows, then average ensemble (consistent with earlier sens)
per_member = np.sqrt(np.sum(jac_stack[:, rows, :] ** 2, axis=1)) # (nens, nparams)
agg = np.mean(per_member, axis=0) # (nparams,)
m_vec = agg[:nm].reshape((nx, nz), order="C").T # (nz, nx)
z_vec = agg[nm:].reshape((nx, nz), order="C").T
per_data_maps_m.append(m_vec)
per_data_maps_z.append(z_vec)
# Layout: one row per selected data, 2 columns (m,z) (n_rows = ceil(n_selected/cols) but here want pairs)
n_cols = 2
n_rows = int(np.ceil(n_selected / 1)) # one pair per row
fig, axes = plt.subplots(n_rows, n_cols, figsize=(14, 3.8 * n_rows), constrained_layout=True)
axes = np.atleast_2d(axes)
# compute global vmin/vmax for consistent color scaling
all_vals = np.concatenate([m.ravel() for m in per_data_maps_m] + [z.ravel() for z in per_data_maps_z])
vmin = all_vals.min()
vmax = all_vals.max()
for i in range(n_selected):
row = i
ax_m = axes[row, 0]
ax_z = axes[row, 1]
im_m = _plot_field_panel(ax_m, per_data_maps_m[i], grid_axes, f"{SELECTED_DATA[i]} : J ({var_name_1})", cmap, vmin=vmin,
vmax=vmax)
im_z = _plot_field_panel(ax_z, per_data_maps_z[i], grid_axes, f"{SELECTED_DATA[i]} : J ({var_name_2})", cmap, vmin=vmin,
vmax=vmax)
# only first row show legend/title handled in panel
# turn off any extra axes if n_selected < cells
total_cells = axes.size
used = n_selected * n_cols
flat_axes = axes.ravel()
for ax in flat_axes[used:]:
ax.axis("off")
# shared colorbar across all panels
fig.colorbar(im_m, ax=flat_axes[:used].tolist(), fraction=0.045, pad=0.02).set_label("|J| (aggregated)")
fig.suptitle(f"Posterior Jacobian for {tool_label} (assim {assim_ind})", fontsize=14)
# optional SVD saved separately
if show_svd:
sv = np.linalg.svd(J_mean, compute_uv=False)
svfig, svax = plt.subplots(1, 1, figsize=(6, 3))
svax.semilogy(np.arange(1, len(sv) + 1), sv, "-o")
svax.set_title(f"SVD of mean J (assim {assim_ind})")
svout = outdir / f"posterior_jacobian_assim_{assim_ind:03d}_svd.png"
if save:
svfig.savefig(svout, dpi=150)
plt.close(svfig)
else:
plt.show()
if partial_deriv:
outpath = outdir / f"posterior_jacobian_assim_{assim_ind:03d}_{tool_label}_partial_deriv.png"
else:
outpath = outdir / f"posterior_jacobian_assim_{assim_ind:03d}_{tool_label}.png"
if save:
fig.savefig(outpath, dpi=200)
plt.close(fig)
return outpath
else:
plt.show()
return outdir
def plot_posterior_jacobian_assim_org(
post_jac: list[np.ndarray] | np.ndarray,
assim_ind: int,
grid_axes: dict,
outdir: Path,
show_svd: bool = False,
cmap: str = "viridis",
save: bool = True,
partial_deriv:bool = False,
) -> Path:
outdir.mkdir(parents=True, exist_ok=True)
# stack ensemble -> (nens, ndata, nparams)
jac_stack = np.stack(post_jac, axis=0)
nens, ndata, nparams = jac_stack.shape
# infer nx,nz from grid_axes
nx = int(np.asarray(grid_axes["x_centers"]).size)
nz = int(np.asarray(grid_axes["z_centers"]).size)
nm = nx * nz
if nparams != 2 * nm:
raise ValueError(f"nparams ({nparams}) != 2 * nx * nz ({2*nm}). Check grid_axes or posterior_jacobian shape.")
# L2 sensitivity per parameter for each member, then ensemble mean
sens_per_member = np.sqrt(np.sum(jac_stack**2, axis=1)) # (nens, nparams)
sens_mean = np.mean(sens_per_member, axis=0) # (nparams,)
# split m and z, reshape to (nz, nx) for _plot_field_panel which expects field_nz_nx
sens_m = sens_mean[:nm].reshape((nx, nz), order="C").T # -> (nz, nx)
sens_z = sens_mean[nm:].reshape((nx, nz), order="C").T # -> (nz, nx)
# plotting: 2x2 grid (m map, z map, optional SVD, empty or colorbars placed)
fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True)
ax_m = axes[0]
ax_z = axes[1]
# sensible clim across both maps
vmin = min(sens_m.min(), sens_z.min())
vmax = max(sens_m.max(), sens_z.max())
# reuse your helper to plot field panels (expects field_nz_nx)
if partial_deriv: # in optimizer space
var_name_1 = "log rh bounded"
var_name_2 = "latent_ratio"
else: # from simulator in physical space
var_name_1 = "rh"
var_name_2 = "rv"
im_m = _plot_field_panel(ax_m, sens_m, grid_axes, f"Assim {assim_ind}: sensitivity ({var_name_1})", cmap, vmin=vmin, vmax=vmax)
im_z = _plot_field_panel(ax_z, sens_z, grid_axes, f"Assim {assim_ind}: sensitivity ({var_name_2})", cmap, vmin=vmin, vmax=vmax)
# add colorbars using empty axis if layout reserved, else use figure colorbar
# put a single shared colorbar in reserved bottom-right axis for consistent size
cb = fig.colorbar(im_m, ax=[ax_m, ax_z], fraction=0.046, pad=0.02)
cb.set_label('sensitivity')
fig.suptitle(f"Posterior Jacobian diagnostics (assim {assim_ind})", fontsize=14)
if partial_deriv:
outpath = outdir / f"posterior_jacobian_assim_{assim_ind:03d}_partial_deriv.png"
else:
outpath = outdir / f"posterior_jacobian_assim_{assim_ind:03d}.png"
if save:
fig.savefig(outpath, dpi=200)
plt.close(fig)
return outpath
else:
plt.show()
return outdir
def _plot_field_panel(
ax: plt.Axes,
field_nz_nx: np.ndarray,
grid_axes: dict[str, np.ndarray | float],
title: str,
cmap: str,
vmin: float | None = None,
vmax: float | None = None,
):
x_edges = np.asarray(grid_axes["x_edges"])
z_edges = np.asarray(grid_axes["z_edges"])
well_x_ft = float(grid_axes["well_x_ft"])
well_tvd_ft = float(grid_axes["well_tvd_ft"])
mesh = ax.pcolormesh(x_edges, z_edges, field_nz_nx, shading="auto", cmap=cmap,
vmin=vmin,
vmax=vmax)
ax.scatter([well_x_ft], [well_tvd_ft], marker="x", color="red", s=55, linewidths=1.5)
ax.set_title(title)
ax.set_xlabel("X [ft]")
ax.set_ylabel("TVD [ft]")
ax.xaxis.set_major_locator(MaxNLocator(nbins=6))
ax.yaxis.set_major_locator(MaxNLocator(nbins=6))
ax.set_xlim(x_edges[0], x_edges[-1])
ax.set_ylim(z_edges[0], z_edges[-1])
ax.invert_yaxis()
# Show equivalent metric distance scales on secondary axes.
sec_x = ax.secondary_xaxis(
"top",
functions=(lambda x_ft: x_ft / METER_TO_FEET, lambda x_m: x_m * METER_TO_FEET),
)
sec_x.set_xlabel("X [m]")
sec_x.xaxis.set_major_locator(MaxNLocator(nbins=6))
sec_y = ax.secondary_yaxis(
"right",
functions=(lambda z_ft: z_ft / METER_TO_FEET, lambda z_m: z_m * METER_TO_FEET),
)
sec_y.set_ylabel("TVD [m]")
sec_y.yaxis.set_major_locator(MaxNLocator(nbins=6))
return mesh
def plot_parameters(
rh: np.ndarray,
rv: np.ndarray,
post_loss: np.ndarray,
assim_ind: int,
outdir: Path,
grid_axes: dict[str, np.ndarray | float],
name: str = 'post',
aspect_to_plot: str = 'Best',
rh_clim: tuple[float, float] | None = None,
rv_clim: tuple[float, float] | None = None,
) -> Path:
if aspect_to_plot == 'Median':
rh_plot = np.median(rh, axis=0)