qlroms.utils.diagnosis
Diagnostics for ql-ROM models -- shared by all test cases (KS 1D/2D, PIV wake, fenics).
Model-agnostic utilities for selecting K (number of clusters) and evaluating reconstruction quality. Works with any snapshot tensor of shape (Nx, T) or (Nx*Ny, T).
The FOM argument in the functions below never has to be an actual
full-order model: only N, dt, device and rdtype are read,
so a lightweight config (e.g. split.config.WakeConfig for pure
data-driven cases) works just as well. sweep_k_bic needs no model at
all -- it is the pure data-driven K-selection entry point.
default_forecast(model, x0, n_steps)
Closed-loop free run over the common model interface (project / step / recover).
Every diagnostic below reaches a model only through a forecast_fn with this
signature, so nothing here knows whether it is driving a ql-Galerkin, a qlOpinf,
a ql-DMD or anything else: families that do not step reduced coordinates (a
reservoir carries its own hidden state, for instance) are diagnosed by passing
their own closure instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
any qlROM exposing project_state / step / recover_state. |
required | |
x0
|
(N, 1) physical initial condition. |
required | |
n_steps
|
int
|
number of steps to advance. |
required |
Returns: (N, n_steps) recovered physical trajectory, x0 excluded.
Source code in qlroms/utils/diagnosis.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
bic_kmeans(X, centers, labels, n_params=None, eps=1e-15)
Hard-clustering BIC (Gaussian isotropic model).
BIC = n_params * log(N) - 2 * ell_hat
where ell_hat is the log-likelihood under a common isotropic Gaussian with variance sigma2 = J / (p * N) and J is the total within-cluster sum of squares.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
data matrix (N, p). |
required |
centers
|
ndarray
|
cluster centroids (K, p). |
required |
labels
|
ndarray
|
integer cluster assignment per snapshot (N,). |
required |
n_params
|
int | None
|
model complexity; defaults to K*p (centroid coordinates). |
None
|
eps
|
float
|
floor for sigma2 to prevent log(0). |
1e-15
|
Returns:
| Type | Description |
|---|---|
float
|
BIC score (lower is better). |
Source code in qlroms/utils/diagnosis.py
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 | |
sweep_k_bic(Xtrain, K_list, random_state=1)
Pure data-driven BIC sweep: score each K in K_list (lower is better) plus an elbow estimate of K_opt. No model required -- only a snapshot matrix.
Mirrors the elbow heuristic used in sweep_qlrom_diagnosis: the K whose finite-difference slope of BIC(K) is farthest from the straight line joining the sweep's first and last slopes.
Source code in qlroms/utils/diagnosis.py
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 | |
compute_projection_mse(Xtest, rom, chunk_size=20000)
A priori projection MSE: average squared residual after projecting each test snapshot onto its nearest local basis.
For each snapshot u_m the nearest centroid c_k is found and the residual
after projection is computed. The projection uses the same inner product
as project_state:
- Standard L2 (1-D KS):
a = Phi_k^T (u - c_k) - Weighted L2 (2-D KS):
a = Phi_k^T W (u - c_k)whereW = diag(wt)
The residual is computed directly as diff - U_k a to avoid catastrophic
cancellation when the projection captures nearly all variance (Pythagorean
subtraction ||diff||^2 - ||a||^2 loses all digits at high r).
Both the nearest-centroid assignment and the per-cluster residual are computed
in batches of chunk_size so peak memory stays bounded regardless of Ntest
(this is called with the full Ntrain snapshot set too -- torch.cdist on the
full (Ntest, Ndof) block internally allocates far more than the Ntest x K
output would suggest). Batching is numerically identical to computing it in
one shot; only peak memory changes.
Xtest may live on any device (e.g. a CPU-resident slice of a large trajectory); only chunk_size rows are ever moved to the ROM's device at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Xtest
|
Tensor
|
test snapshots (Ndof, Ntest), any device. |
required |
rom
|
ROM instance with |
required | |
chunk_size
|
int
|
max snapshots per batch. |
20000
|
Returns:
| Type | Description |
|---|---|
float
|
Scalar MSE averaged over test snapshots. |
Source code in qlroms/utils/diagnosis.py
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 | |
switching_fidelity_report(rom, X, stride=5, wt=None)
How faithfully the O(r) switching rules reproduce physical centroid distances.
Every stride-th snapshot is projected onto its nearest chart, and its distance vector to all K centroids is computed up to three ways: the physical ground truth from the raw snapshot (mass-weighted, sqrt(sum(wt (c - x)^2)), when a spatial weight is available), the chart-projected tshift rule, and -- when the model carries atlas maps -- the atlas rule z = Tgk a + dgk. The chart rule silently drops each far centroid's out-of-chart component, so beyond the bare argmin it scrambles the ordering of the competing charts, which the hysteresis gate and forecast_washout's overlap band both compare magnitudes over (on a K=10 run: argmin agreement 100% / 98.25% and full-ordering preservation 100% / 56.75% for atlas / chart).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rom
|
model exposing project_state plus the TransitionMaps surface (tmap/tshift, optionally Tgk/dgk): an Atlas, a qlROM, ... |
required | |
X
|
(N, T) physical snapshots; columns X[:, ::stride] are evaluated. |
required | |
stride
|
int
|
snapshot subsampling step. |
5
|
wt
|
(N,)-reshapeable spatial weight for the physical metric; None uses the model's own weight (TransitionMaps.from_model), Euclidean if it has none. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
dict with "n_snapshots" and, per available rule ("chart", "atlas"), a dict |
dict
|
with "argmin_agreement" (% of snapshots whose nearest centroid matches the |
dict
|
physical one), "spearman" ((n,) per-snapshot Spearman rank correlation of |
dict
|
the rule's distance vector vs the physical one), "spearman_median", and |
dict
|
"spearman_frac_exact" (fraction with correlation > 0.999, i.e. the full |
dict
|
centroid ordering preserved). |
Source code in qlroms/utils/diagnosis.py
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 | |
overlap_stats(rom, X, tols=(1.0, 1.1, 1.2, 1.4, 1.6))
Population of forecast_washout's overlap band over a snapshot set.
Per tolerance: the mean number of charts whose centroid distance falls within tol x the nearest-centroid distance per snapshot, and the fraction of snapshots with more than one chart in band. Distances follow the same rule esn_base.rom_distance / forecast_washout's band uses -- exact atlas distances when the model carries Tgk/dgk (unless its transitions method is 'pairwise'), else the in-chart tshift distances -- so the numbers describe exactly the population that method buffers (reference washout notebook: 47.2% multi-chart at tol=1.1 on chaotic_B at K=40).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rom
|
model exposing project_state plus the TransitionMaps surface. |
required | |
X
|
(N, T) physical snapshots. |
required | |
tols
|
overlap tolerances (>= 1), the fit_clusters / forecast_washout convention (band = dist <= tol * nearest distance). |
(1.0, 1.1, 1.2, 1.4, 1.6)
|
Returns:
| Type | Description |
|---|---|
dict
|
{tol: {"mean_charts": float, "frac_multi": float}}. |
Source code in qlroms/utils/diagnosis.py
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 | |
compare_local_global_reconstruction(Xtest, FOM, local_rom, global_rom, forecast_fn=None, save_dir=None)
Run both ROMs forward and also evaluate snapshot-by-snapshot representation.
Returns forecast trajectories (free time-stepping from IC) and representation trajectories (project-recover every FOM snapshot without time-stepping).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Xtest
|
Tensor
|
Test snapshots (Ndof, Ntest). |
required |
FOM
|
FOM instance providing device and rdtype. |
required | |
local_rom
|
Local ql-ROM (K >= 1). |
required | |
global_rom
|
Global ROM (K=1 reference). |
required | |
forecast_fn
|
forecast_fn(model, x0, n_steps) -> (Ndof, n_steps) physical
trajectory. None (default) uses |
None
|
|
save_dir
|
str | None
|
Directory to cache results; None disables caching. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
dict with keys: forecast -- Xlocal_rec, Xglobal_rec, local_rmse, global_rmse, local_err_t, global_err_t, passed representation -- Xlocal_rep, Xglobal_rep, local_rep_rmse, global_rep_rmse, local_rep_err_t, global_rep_err_t |
Source code in qlroms/utils/diagnosis.py
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 | |
sweep_qlrom_diagnosis(Xtrain, Xtest, FOM, K_list, r_list, build_model_fn, forecast_fn=None, bic_random_state=1, bic_subsample=10000, save_dir='.')
Run the full ql-ROM diagnostic suite in a single pass.
Combines sweep_k_bic + sweep_kr_reconstruction + sweep_error_timeseries. Each ROM is built once per (K, r) pair; the stepper is run once and yields both the scalar reconstruction error and the per-timestep error vector. All results are cached to a single file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
Xtrain
|
Tensor
|
Training snapshots (Ndof, Ntrain). |
required |
Xtest
|
Tensor
|
Test snapshots (Ndof, Ntest). |
required |
FOM
|
FOM instance. |
required | |
K_list
|
list[int]
|
Cluster counts to sweep (K >= 2). |
required |
r_list
|
list[int]
|
Mode counts to sweep. |
required |
build_model_fn
|
Callable(Xtrain, FOM, r, K, save_dir) -> ROM. |
required | |
forecast_fn
|
forecast_fn(model, x0, n_steps) -> (Ndof, n_steps); None uses
|
None
|
|
bic_random_state
|
int
|
RNG seed for the BIC subsample. |
1
|
bic_subsample
|
int | None
|
Snapshot subsample size BIC is scored on (None = all). Clustering itself is not fit here -- it's taken from the already-built ROM's centroids (see BIC sweep below), so this only bounds scoring cost. |
10000
|
save_dir
|
str
|
Directory for caching. |
'.'
|
Returns:
| Type | Description |
|---|---|
dict
|
dict with keys: -- BIC -- 'bic_k_values' np.ndarray(int) 'bic_values' np.ndarray(float) -- (K, r) sweep -- 'K_list' list[int] (local K values, excludes K=1) 'r_list' list[int] 'local_errors' np.ndarray (nK, nr) scalar rel-L2 'global_errors' np.ndarray (nr,) 'local_proj_mse' np.ndarray (nK, nr) test-set projection MSE 'global_proj_mse' np.ndarray (nr,) test-set projection MSE 'local_proj_mse_train' np.ndarray (nK, nr) projection MSE over the last Ntest training snapshots (not the full train set) 'global_proj_mse_train' np.ndarray (nr,) same, global ROM -- timeseries (all K at r_check) -- 'err_t' np.ndarray (nK+1, Ntest) row 0 = K=1 global 't' np.ndarray (Ntest,) 'r_timeseries' int (r used for the timeseries) -- cluster occupancy at K_opt -- 'cluster_probs' np.ndarray (K_opt,) P_train(c_k) = n_k / M 'cluster_counts' np.ndarray (K_opt,) n_k 'P_test' np.ndarray (K_opt,) P_test(c_k) 'P_qlrom_repr' np.ndarray (K_opt,) P(c_k) from qlROM a priori projection on test set 'P_qlrom_te' np.ndarray (K_opt,) P(c_k) from qlROM forward integration on test set 'P_grom_repr' np.ndarray (K_opt,) P(c_k) from gROM a priori projection on test set 'P_grom_te' np.ndarray (K_opt,) P(c_k) from gROM forward integration on test set 'kl_train' float KL(P_test || P_train) 'kl_qlrom' float KL(P_test || P_qlrom_te) 'kl_grom' float KL(P_test || P_grom_te) 'kl_ql_repr' float KL(P_test || P_qlrom_repr) [a priori representation metric] 'kl_gr_repr' float KL(P_test || P_grom_repr) [a priori representation metric] |
Source code in qlroms/utils/diagnosis.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 | |