Repository navigation
Expand file tree
/
Copy pathtopographic.m
More file actions
1935 lines (1759 loc) · 106 KB
/
Copy pathtopographic.m
File metadata and controls
1935 lines (1759 loc) · 106 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
% Code corresponding to a multimodal and layered topographic paradigm stochastic
% model with mean flow interaction for studying regime switching, included as an
% additional repository case study for the paper "Bridging Prediction and
% Attribution: Identifying Forward and Backward Causal Influence Ranges Using
% Assimilative Causal Inference".
%
% Authors: Marios Andreou, Nan Chen.
%
% Code Information: Application of conditional Assimilative Causal Inference
% (ACI) and of the associated forward and backward Causal Influence Range (CIR)
% metrics to a stochastic, truncated, layered topographic model for studying
% blocked/unblocked regime switching of a barotropic quasi-geostrophic flow with
% large-scale zonal mean-flow and small-scale potential-vorticity interactions:
%
% dv_1/dt = -d_1·v_1 - (β-u)·v_2 - ω_1·u + (σ_1/sqrt(2))·dot(W_1),
% dv_2/dt = -d_1·v_2 + (β-u)·v_1 + (σ_1/sqrt(2))·dot(W_2),
% dv_3/dt = -d_2·v_3 - (β/2-2u)·v_4 - (ω_2/2)·u + (σ_2/sqrt(2))·dot(W_3),
% dv_4/dt = -d_2·v_4 + (β/2-2u)·v_3 + (σ_2/sqrt(2))·dot(W_4),
% dv_5/dt = -d_3·v_5 - (β/3-3u)·v_6 - (ω_3/(3^(p+1)·sqrt(2)))·u + (σ_3/sqrt(2))·dot(W_5),
% dv_6/dt = -d_3·v_6 + (β/3-3u)·v_5 + (σ_3/sqrt(2))·dot(W_6),
% du/dt = -d_u·u + ω_1·v_1 + 2·ω_2·v_3 + (ω_3/(3^(p-1)·sqrt(2)))·v_5 + σ_u·dot(W_7).
%
% This model is obtained from the barotropic quasi-geostrophic equations for a
% large-scale zonal mean flow over a layered topography on a rotational β-plane,
% defined by a system of PDEs for the large-scale zonal mean flow (positive =
% eastward) and small-scale zero-mean potential vorticity and streamfunction on
% a periodic spatial domain, driven by a scalar, constant-in-time, zero-mean
% topography function:
% ➤ https://doi.org/10.1017/CBO9780511616778
% ➤ https://doi.org/10.1017/S002211208700034X
% ➤ https://doi.org/10.1007/978-1-4612-4650-3
% ➤ https://doi.org/10.1007/s003329900065
% This baseline model provides a conceptual closed system describing the
% anisotropic interactions between large and small scales through the
% geophysical effects of the zonal mean flow, the β-plane, and the topography,
% while maintaining the important quadratic invariants of the flow (kinetic
% energy and large-scale enstrophy) in the absence of damping/dissipation and
% (stochastic) forcing:
% ➤ https://doi.org/10.1080/03091928508245436
% ➤ https://doi.org/10.1073/pnas.1510465112
% ➤ https://doi.org/10.1175/1520-0469(1996)053%3C0887:SEEATT%3E2.0.CO;2
% ➤ https://doi.org/10.1175/JAS-D-16-0192.1
% This nonlinear coupling between the small-scale vortical modes and large-scale
% mean flow happens through the topographic stress in the PDEs, which is
% necessary to enforce conservation of the system’s total (kinetic) energy
% and it is the direct analogue in periodic geometry of the change in time of
% angular momentum due to mountain torque in spherical geometry.
%
% After assuming a layered topography in a fixed direction on these PDEs, where,
% without loss of generality under an appropriate scaling/rotation, for this
% case study we consider one aligned with the y-direction, that is l = (1, 0)ᵀ,
% which can be thought of as an analogue to a long north-south ridge, then the
% small-scale nonlinear self-interaction terms vanish identically, while the
% nonlinear coupling of the small-scale flow with the large-scale zonal mean
% flow due to topographic stress remains and is responsible for much of the
% reduced-order model's complex behaviour. With this simplifying assumption, by
% then adopting a Fourier-mode expansion/ansatz for the small-scale
% streamfunction and topography, as is usually done in the literature for this
% model and periodic spatial domain, we can recover the layered topographic ODEs
% in the Fourier space from the original barotropic quasi-geostrophic PDEs:
% ➤ https://doi.org/10.1007/s003329900065
% ➤ https://doi.org/10.1016/j.jcp.2013.10.025
% Due to the real-valued nature of the streamfunction and topography, their
% Fourier coefficients enjoy the conjugate symmetry property (k mode is the
% complex conjugate of the -k mode) due to the reality condition of the Fourier
% transform.
%
% Following this layered topography assumption and Fourier-basis expansion, by
% then considering a finite-Fourier truncation of the small-scale streamfunction
% and topography, while compensating for the information lost in this Galerkin
% approximation by adding extra dissipation in the form of Ekman damping (to
% modulate the low-wavenumber modes as is commonly done in geophysical fluid
% dynamics, see "Rick Salmon. Lectures on Geophysical Fluid Dynamics." and
% "Andrew Majda and Xiaoming Wang. Nonlinear Dynamics and Statistical Theories
% for Basic Geophysical Flows.") and additive stochastic noise (to approximate
% the influence of the truncated high-wavenumber Rossby modes on the retained
% low-wavenumber modes, while preserving the relevant energy/enstrophy structure
% of the system), we then arrive at the stochastic, truncated, layered
% topographic equations.
%
% To obtain the final form studied in this script, i.e. the seven-dimensional
% real-valued system outlined above, we follow the same procedure as described
% in the following papers:
% ➤ https://doi.org/10.1063/1.5122199 (paper where the exact same truncated,
% real-valued model is studied
% extensively and the choice of the model
% parameter values used in this script,
% like the β-plane and choice of
% topography, is thoroughly justified)
% ➤ https://doi.org/10.1063/5.0154777
% ➤ https://doi.org/10.1175/JAS-D-16-0192.1
% ➤ https://doi.org/10.1016/j.jcp.2013.10.025
% Specifically, after expanding the small-scale streamfunction and topography in
% Fourier modes and truncate to just the wavenumbers k=±1,±2,±3, and then rotate
% the real and imaginary streamfunction coefficients by 45 degrees, one finally
% obtains the seven-dimensional real-valued system from above. Note that the
% obtained model, before the added dissipation and stochastic forcing, is
% similar to the Charney and DeVore model for nonlinear atmospheric
% regime-transition:
% ➤ https://doi.org/10.1175/1520-0469(1979)036%3C1205:MFEITA%3E2.0.CO;2
% ➤ https://doi.org/10.1175/1520-0469(2004)061%3C1406:AMFARB%3E2.0.CO;2
% ➤ https://doi.org/10.1063/1.4984627
% The resulting system is also a conditional Gaussian nonlinear system (CGNS)
% for the posterior u | (v_1,...,v_6); see Appendix G of the paper. The
% unobserved scalar variable u is the large-scale zonal mean flow, while the six
% observed variables v_1,...,v_6 encode the real and imaginary parts of the
% first three retained topographic/Rossby streamfunction modes ψ_1, ψ_2, and
% ψ_3. The original ψ_k complex modes can be recovered from these by:
% Re(ψ_k) = (v_{2k}-v_{2k-1})/(2·sqrt(2)),
% Im(ψ_k) = -(v_{2k}+v_{2k-1})/(2·sqrt(2)), k=1,2,3,
% due to the 45-degree rotation of the real and imaginary parts of the
% streamfunction. Under the assumption of zero mean with respect to the spatial
% average, i.e. we work with anomaly variables spatially, then the zeroth-order
% Fourier modes of the streamfunction and topography are equal to zero (since
% these coincide with said spatial average).
%
% As noted, Ekman damping and additive stochastic noise approximate the
% interaction with the truncated high-wavenumber Rossby modes, preserve the
% relevant energy/enstrophy structure after the Galerkin truncation, and induce
% statistically representative blocked/unblocked regime switching. In terms of
% the physical context concerning the seven-dimensional system studied in this
% script (based on the chosen model parameter values, which are adapted from
% https://doi.org/10.1063/1.5122199, in which proper justifications are also
% provided):
% ➤ The ψ_k are only self-coupled through the small-scale mean-flow
% interaction by topographic stress.
% ➤ Regardless of the wavenumber cutoff in the Galerkin truncation, the
% truncated energy and enstrophy are still conserved under the system
% through Galerkin projection (see "Andrew Majda and Xiaoming Wang.
% Nonlinear Dynamics and Statistical Theories for Basic Geophysical Flows.")
% ➤ The adopted topography in this case study includes small-scale
% disturbances (k = ±2, ±3), which based on the layered topographic
% functions determine the meridional flows, on top of the large-scale basic
% topographic or Rossby mode (k = ±1).
% ➤ p controls the smoothness of the higher-order modes (in this case just the
% third-order one), i.e. the features of the small-scale topography which
% alter the streamfunctions. We consider p = 1 in this case study. For p = 2
% and uniform topographic strengths/Fourier coefficients, then the
% third-order mode of the streamfunction possesses only 10% of the total
% energy when compared to the effects of the leading two Fourier modes,
% therefore, only weak effects exist in the small-scale topography, while
% for p = 0 then all topography modes are nearly equally important
% (energy-wise). Also, due to the chosen parameter values in this case
% study, the energy in the noise part, σ^2_k/(2·d_k), is roughly 30% as
% large as the energy in the deterministic signal, ω^2_k/(2·d_k), as to
% compensate for the finite-mode truncation.
% ➤ The extra stochasticity, while it compensates for the omission of the
% truncated small-scale, high-wavenumber modes and allows for a well-posed
% ACI study, it also improves the system's mixing rate, since the mixing of
% the deterministic system is extremely slow and the dynamical behaviour can
% strongly depend on the initial value instead of the underlying causal
% structure of the system. With the chosen parameter values, the system
% represents a time scale of relaxation time of roughly 80 time units, which
% allows for a relatively slow, but not infinitely so, mixing of the system.
% Furthermore, since we want to take into account both the conservation of
% energy and enstrophy into the ACI and CIR study, the Ekman drag damping
% and random noise are added to effectively reach the Gaussian invariant
% measure, since the resulting system belongs to the physics-constrained
% nonlinear model family (due to energy conservation), while also having a
% skew-symmetric linear operator:
% ➤ https://doi.org/10.1175/JAS-D-16-0192.1
% ➤ https://doi.org/10.1088/0951-7715/26/1/201
% ➤ https://doi.org/10.1007/978-3-319-32217-9
%
% In this script, ACI and its forward and backward CIR metrics are employed to
% study the following conditional causal relationships:
% u(t) → ψ_1 | (ψ_2,ψ_3),
% u(t) → ψ_2 | (ψ_1,ψ_3),
% u(t) → ψ_3 | (ψ_1,ψ_2),
% over time t∈[0,T], where the target streamfunction mode pair can be chosen
% freely by the user (with the remaining modes being resolved under conditional
% ACI). Therefore, u is treated as the latent candidate cause, the selected ψ_k
% mode (defined from the real-valued, rotated (v_{2k-1},v_{2k}) pair; see above)
% is the target observed effect, and the remaining two streamfunction mode pairs
% (likewise defined by their respective (v_{2k'},v_{2k'-1}) pairs) are assumed
% to be resolved conditioning variables (and assumed to be observable as well).
% Operationally, for conditional ACI purposes, the non-target ψ_{k'} modes can
% be inserted into the model coefficients using their observed/simulated time
% series, with the Bayesian update for the state estimation of u using only the
% observations from the selected target observed channel ψ_k mode (i.e. the
% bivariate pair (v_{2k-1},v_{2k})). This is the explicit model shortcut for
% conditional ACI: The contribution of the conditioning streamfunction modes is
% resolved as a prescribed forcing during Bayesian inference, leaving the
% uncertainty reduction in the state estimation of u(t) attributable to the
% selected target ψ_k solely. As noted in the original ACI paper,
% https://doi.org/10.1038/s41467-026-68568-0, this is equivalent to "letting the
% marginal uncertainty of the conditioning ψ_{k'} modes in the likelihood to
% grow to infinity", which is equivalent to setting the elements corresponding
% to those modes, and specifically their real-valued components
% (v_{2k'},v_{2k'-1}) since we work with the rotated, real-valued,
% seven-dimensional representation model from above, in the inverse of the
% observational noise Grammian matrix to zero during state estimation. This
% effectively removes the influence of the conditioning modes from the Bayesian
% update of u(t) while still retaining: (a) Their influence in the dynamics and
% (b) the observational contributions from the selected target ψ_k mode (i.e.
% the pair (v_{2k-1},v_{2k})). This latter "masking" procedure is implemented in
% this script for calculating the conditional ACI and CIR metrics for
% explicitness.
%
% This additional case study can use the conditional ACI and CIR metrics to
% assess over time which topographic mode pair most strongly informs the state
% estimation of the large-scale mean flow u during regime switching (blocked and
% unblocked), if we were to assume full-state observability of the system thus
% allowing the additional study of the conditional causal relationships
% ψ_k(t) → u | (ψ_{k'},ψ_{k''}) for k,k',k''∈{1,2,3} and k≠k'≠k''; the
% large-scale mode ψ_1 can be associated with topographic/Rossby-wave precursors
% to dynamical bifurcation-like transitions with distinct early warning signals,
% while the smaller-scale disturbances ψ_2 and ψ_3 can induce less predictable,
% noise-induced switching behaviour. But, here we instead study the conditional
% causal relationships u(t) → ψ_k | (ψ_{k'},ψ_{k''}). Nevertheless, the
% subsequent script can be easily adapted for this former line of investigation
% with the appropriate modifications since the underlying real-valued seven
% dimensional system is also a CGNS for the posterior (ψ_1,ψ_2,ψ_3) | u. Forward
% CIR analysis of the u-causal relationships assesses how long the current
% mean-flow state u(t) remains predictively informative for the future target
% streamfunction mode, while backward CIR analysis attributes the current target
% mode ψ_k(T) to past states of u. This script's analyses are not included in
% the paper or its appendix, but is included in the repository as an additional
% case study for the interested reader.
%
% This script also implements the following optional studies and analyses:
%
% (i) Optional calculation of the exact objective forward CIR using the
% ε-average definition of the subjective forward CIR, together with
% an exact-vs-approximate objective forward CIR comparison plot.
% (ii) Optional calculation of the exact objective backward CIR using the
% ε-average definition of the subjective backward CIR, together with
% an exact-vs-approximate objective backward CIR comparison plot.
% (iii) Optional calculation of the normalised forward CIR metric δ^f(T';t)
% and its heatmap over natural time t and lagged observational time
% after t, T'-t.
% (iv) Optional calculation of the normalised complete backward CIR metric,
% lim_{T'→T^-} δ^b(t;T'), using the discrete-time adaptive-lag online
% smoother approximation from Appendix G of the paper, and its heatmap
% over observational time T and backward lag T-t. Here T denotes the
% current online-smoother observation time, not the terminal
% simulation time.
%
% The exact objective forward and backward CIRs are defined in Eqs. (10) and
% (18) of the paper, respectively, as ε-average integrals of the corresponding
% subjective CIRs, while their computationally efficient approximations are
% correspondingly defined in Eqs. (12) and (20), as time integrals of the
% corresponding CIR relative-entropy-based metrics (specifically, their L1-to-L∞
% ratio). These approximations become exact under the monotonicity conditions
% described in the paper for the respective CIR metrics, which hold to a
% satisfactory degree for general complex dynamical systems. In general, they
% act as lower- and upper-bounding approximations to the exact CIRs,
% respectively.
%
% Written and tested in MATLAB R2024b.
%
% MATLAB Toolbox and M-file Requirements:
%
% Code used to obtain the required m-file scripts and MATLAB toolboxes:
% [fList, pList] = matlab.codetools.requiredFilesAndProducts('topographic.m');
%
% M-file Scripts:
% ➤ topographic.m
% ➤ progress_bar.m
% ➤ simps.m (https://www.mathworks.com/matlabcentral/fileexchange/25754-simpson-s-rule-for-numerical-integration)
% ➤ shared_helper.m
%
% Data:
% ➤ N/A - The script utilises synthetic observations simulated by the model
%
% Toolboxes:
% ➤ Statistics and Machine Learning Toolbox
% ➤ Econometrics Toolbox
%
% GitHub Repository: https://github.com/marandmath/FBCIR_code
% MIT License Information: https://github.com/marandmath/FBCIR_code/blob/main/LICENSE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% USER CONTROLS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Fixing the random seed for reproducibility across each simulation.
rng(60)
% Total number of time steps within the given time interval.
N = 500000;
% Numerical integration time step.
dt = 0.005;
% Total simulation time.
T = N*dt;
% Plotting time window for the initial simulation results figures.
time_start_plot = 0;
time_end_plot = T;
% This threshold is used to treat small relative-entropy-based CIR-metric maxima
% at each time as non-causal so as to avoid operationally inflated objective
% forward and backward CIR lengths (both exact and approximate), as well as
% optional normalised CIR-metric heatmaps, caused by normalising floating-point
% noise when dividing by the L∞ norm of the respective relative-entropy-based
% CIR metric.
RE_metric_threshold = 1e-8;
% Optional repository diagnostics; see the script's header for details. Set any
% flag to false to skip only that extra calculation/plot.
calculate_and_plot_exact_objective_forward_CIR = false;
calculate_and_plot_exact_objective_backward_CIR = false;
calculate_and_plot_normalised_forward_CIR_metric = false;
calculate_and_plot_normalised_backward_CIR_metric = false;
% Optional normalised CIR metric (forward and complete backward CIR metrics)
% heatmap display-lag windows for optimal plotting. Defining them before the CIR
% metric loops so that we retain only the necessary displayed metric rows for
% this optionally plotted heatmap instead of a full O(N²) cache, without
% changing the actual mathematical logic or displayed metric values.
% The smaller current-time-centred lagged observational time window for optimal
% plotting (avoiding O(N²) memory-heavy plots) of the normalised forward CIR
% metric heatmap,
% δ^f(T';t)/max{δ^f(T';t): T'∈[t,T]},
% over the natural time t in the ACI and CIR analysis window
% [analysis_time_start,analysis_time_end] and lagged observational time after t,
% T'-t ∈ [0,lag_obs_time_end_plot], where:
% lag_obs_time_end_plot = T'-t ∈ [0,analysis_time_end-analysis_time_start].
% Note that, by definition of the forward CIR metric, T'∈[t,T] at each t.
lag_obs_time_end_plot = 5;
% The smaller natural-time-centred, current-observational-time-based backward
% lag window for optimal plotting (avoiding O(N²) memory-heavy plots) of the
% normalised complete backward CIR metric heatmap,
% lim_{T'→T^-} δ^b(t;T')/max_t{lim_{T'→T^-} δ^b(t;T')},
% over the observational time T in the ACI and CIR analysis window
% [analysis_time_start,analysis_time_end] and backward lag before T,
% T-t ∈ [0,back_lag_time_end_plot], where:
% back_lag_time_end_plot = T-t ∈ [0,analysis_time_end-analysis_time_start].
% Note that the t-maximum in the normalised complete backward CIR metric is
% taken over the retained natural-time window (shortened by lag_bound; see
% "BACKWARD CIR" section of the script below), while still considering the
% ACI and CIR analysis window of [analysis_time_start,analysis_time_end], i.e.
% t ∈ [T-lag_bound,T]
% = [min{analysis_time_start, analysis_time_end-lag_bound},analysis_time_end]
% = [{earliest retained t closer to t=0},analysis_time_end] ⊆ [analysis_time_start,analysis_time_end].
% Note that, by definition of the (complete) backward CIR metric through a fixed
% but arbitrary observational time T, T-t is the backward lag before the current
% observational time T.
back_lag_time_end_plot = 5;
% To understand the "ACI and CIR analysis window/interval" concept from above,
% see the beginning of the "ACI ANALYSIS" section below for details and context.
% Conditional topographic causal relationship to study. Choose exactly one of
% the three conditional links for each run; the same conditional ACI and CIR
% implementation is used after changing only the target and conditioning
% observed streamfunction-mode pairs during the conditional ACI and CIR
% analysis. Available options: "u_to_psi_1_given_psi_2_psi_3",
% "u_to_psi_2_given_psi_1_psi_3", and "u_to_psi_3_given_psi_1_psi_2".
conditional_relationship_to_study = "u_to_psi_1_given_psi_2_psi_3";
% Choosing the target effect observed channel indices (and by extension the
% conditioning/non-target indices as well) used by conditional ACI, as well as
% the associated plotting titles, based on the conditional relationship to be
% studied, with the observed vector ordered as (v_1,v_2,v_3,v_4,v_5,v_6), with
% (v_{2k-1},v_{2k}) corresponding to the real and imaginary parts of the
% retained topographic streamfunction mode ψ_k, k=1,2,3.
if conditional_relationship_to_study == "u_to_psi_1_given_psi_2_psi_3"
% Conditional causal relationship u(t) → ψ_1 | (ψ_2,ψ_3).
selected_target_obs_indices = 1:2;
selected_forward_relationship_title = 'u(t) \rightarrow ψ_1 | (ψ_2,ψ_3)';
selected_backward_relationship_title = 'u \rightarrow ψ_1(T) | (ψ_2,ψ_3)';
elseif conditional_relationship_to_study == "u_to_psi_2_given_psi_1_psi_3"
% Conditional causal relationship u(t) → ψ_2 | (ψ_1,ψ_3).
selected_target_obs_indices = 3:4;
selected_forward_relationship_title = 'u(t) \rightarrow ψ_2 | (ψ_1,ψ_3)';
selected_backward_relationship_title = 'u \rightarrow ψ_2(T) | (ψ_1,ψ_3)';
elseif conditional_relationship_to_study == "u_to_psi_3_given_psi_1_psi_2"
% Conditional causal relationship u(t) → ψ_3 | (ψ_1,ψ_2).
selected_target_obs_indices = 5:6;
selected_forward_relationship_title = 'u(t) \rightarrow ψ_3 | (ψ_1,ψ_2)';
selected_backward_relationship_title = 'u \rightarrow ψ_3(T) | (ψ_1,ψ_2)';
else
error('Unknown conditional_relationship_to_study value. Use "u_to_psi_1_given_psi_2_psi_3", "u_to_psi_2_given_psi_1_psi_3", or "u_to_psi_3_given_psi_1_psi_2".')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MODEL SETUP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Dimension of the full observational vector, with the non-target topographic
% streamfunction modes to be resolved under conditional ACI, and the chosen ψ_k
% mode pair being the target effect to be studied. The real-valued
% observed/resolved vector is ordered as ((v_1,v_2),(v_3,v_4),(v_5,v_6)) in this
% script, corresponding to the complex-valued streamfunction Fourier modes
% (ψ_1,ψ_2,ψ_3), respectively. The latent candidate cause u is scalar and is
% therefore stored using single-index arrays throughout the filtering,
% smoothing, and conditional ACI and CIR calculations.
modes = 3;
obs_dim = 2*modes;
% Throughout the script, x is used for the observed variables (v_1,...,v_6) and
% y is used to denote the latent variable u, so as to be consistent with the
% CGNS notation from Appendix G of the paper. As for conditional ACI, using the
% notation from Appendix A of the paper, the target effect variable is
% x_A = ψ_k, while the conditioning non-target variables x_B are the remaining
% two streamfunction modes, x_B = (ψ_{k'},ψ_{k''}) for k,k',k''∈{1,2,3} and
% k≠k'≠k'' (all encoded through the real-valued, rotated coordinates
% (v_1,...,v_6) in this script).
% Physical state variables of the seven-dimensional topographic model. The
% variable u denotes the unobserved large-scale zonal mean-flow candidate cause,
% while v denotes the real-valued observed rotated streamfunction coordinates
% (v_1,...,v_6) encoding ψ_1, ψ_2, and ψ_3.
v = zeros(obs_dim, N+1);
u = zeros(1, N+1);
% β-plane/Coriolis parameter controlling Rossby-wave propagation.
beta = 2;
% Common Ekman damping parameter for u and all retained streamfunction modes,
% i.e. d_u = d_1 = d_2 = d_3 = d.
d = 1/40;
% Smoothness parameter controlling the strength of the third topographic mode.
p = 1;
% Topographic strength parameter used to define H_k = strength·sqrt(2)/2^k.
topographic_strength = 2;
% Topographic Fourier-mode amplitudes and the corresponding ω_k = H_k/sqrt(2).
H = topographic_strength*sqrt(2)./2.^(1:modes);
omega_k = H/sqrt(2);
% Additive/state-independent noise/diffusion amplitudes in the rotated
% streamfunction coordinates. The matrix S_x below includes the extra 1/sqrt(2)
% factor coming from decomposing the complex streamfunction modes into real and
% imaginary parts.
sigma_v = [
1/(20*sqrt(2));
1/(20*sqrt(2));
1/(20*sqrt(2));
1/(20*sqrt(2));
1/(20*3^p*sqrt(2));
1/(20*3^p*sqrt(2))
];
% Additive/state-independent noise/diffusion amplitude in the large-scale mean
% flow u.
sigma_u = 1/(20*sqrt(2));
% CGNS representation with u latent and v = (v_1,...,v_6) observed; the "^x" and
% "^y" superscripts used in this script denote the observable (i.e. v) and
% unobservable (i.e. u) processes, respectively, and are used solely for
% consistency with the notation in Appendix G of the paper.
% dv = [L^x(t,v)·u + f^x(t,v)]dt + S^x(t,v)·dW_x,
% du = [L^y(t,v)·u + f^y(t,v)]dt + S^y(t,v)·dW_y.
% Observable coefficient matrix: Feedback of u in v.
L_x = zeros(obs_dim, N+1);
% Forcing in the observable process.
f_x = zeros(obs_dim, N+1);
% Noise feedback matrix in the observable process.
S_x = diag(sigma_v)/sqrt(2);
% Unobservable coefficient matrix: Feedback of u in u.
L_y = -d;
% Forcing in the unobservable process.
f_y = zeros(1, N+1);
% Noise feedback matrix in the unobservable process.
S_y = sigma_u;
% Set the initial conditions accordingly through u(1) and v(:,1), if necessary.
% The default initial conditions are set to zero, which is a valid choice for
% this model.
% Initiating the time-dependent model components.
L_x(:, 1) = [
v(2, 1) - omega_k(1);
-v(1, 1);
2*v(4, 1) - omega_k(2)/2;
-2*v(3, 1);
3*v(6, 1) - omega_k(3)/(sqrt(2)*3^(p+1));
-3*v(5, 1)
];
f_x(:, 1) = [
-d*v(1, 1) - beta*v(2, 1);
-d*v(2, 1) + beta*v(1, 1);
-d*v(3, 1) - beta*v(4, 1)/2;
-d*v(4, 1) + beta*v(3, 1)/2;
-d*v(5, 1) - beta*v(6, 1)/3;
-d*v(6, 1) + beta*v(5, 1)/3
];
f_y(1) = omega_k(1)*v(1, 1) + 2*omega_k(2)*v(3, 1) + omega_k(3)*v(5, 1)/(sqrt(2)*3^(p-1));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%% GENERATING THE TRUE SIGNALS %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Used for the text-based progress bar.
start_time = tic;
for j = 2:N+1
% Text-based progress bar.
progress_bar('Simulation of the Topographic Model', j-1, N, start_time);
% Wiener increments.
dW_v = sqrt(dt)*randn(obs_dim, 1);
dW_u = sqrt(dt)*randn;
% Euler-Maruyama update of the state variables based on the dynamical model.
v(:, j) = v(:, j-1) + (L_x(:, j-1)*u(j-1) + f_x(:, j-1))*dt + S_x*dW_v;
u(j) = u(j-1) + (L_y*u(j-1) + f_y(j-1))*dt + S_y*dW_u;
% Updating the time-dependent model components.
L_x(:, j) = [
v(2, j) - omega_k(1);
-v(1, j);
2*v(4, j) - omega_k(2)/2;
-2*v(3, j);
3*v(6, j) - omega_k(3)/(sqrt(2)*3^(p+1));
-3*v(5, j)
];
f_x(:, j) = [
-d*v(1, j) - beta*v(2, j);
-d*v(2, j) + beta*v(1, j);
-d*v(3, j) - beta*v(4, j)/2;
-d*v(4, j) + beta*v(3, j)/2;
-d*v(5, j) - beta*v(6, j)/3;
-d*v(6, j) + beta*v(5, j)/3
];
f_y(j) = omega_k(1)*v(1, j) + 2*omega_k(2)*v(3, j) + omega_k(3)*v(5, j)/(sqrt(2)*3^(p-1));
end
% Observed physical state vector of the topographic model, ordered as
% (v_1,v_2,v_3,v_4,v_5,v_6), with (v_{2k-1},v_{2k}) corresponding to ψ_k for
% k=1,2,3, for the purposes of plotting, diagnostics, and conditional ACI and
% CIR analysis for the latent candidate cause u.
observed_state = v;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%% PLOTTING MODEL DIAGNOSTICS %%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
plot_idx = round(time_start_plot/dt)+1:round(time_end_plot/dt)+1;
plot_time = (plot_idx - 1)*dt;
% Real and imaginary parts of the retained topographic streamfunction modes,
% reconstructed from the real-valued, rotated coordinates v_1,...,v_6.
psi_real = [
(v(2, :) - v(1, :))/(2*sqrt(2));
(v(4, :) - v(3, :))/(2*sqrt(2));
(v(6, :) - v(5, :))/(2*sqrt(2))
];
psi_imag = [
-(v(2, :) + v(1, :))/(2*sqrt(2));
-(v(4, :) + v(3, :))/(2*sqrt(2));
-(v(6, :) + v(5, :))/(2*sqrt(2))
];
% 2D phase-space projection plots illustrating the topographic
% streamfunction-mode geometry and its interaction with the large-scale zonal
% mean flow u.
figure('WindowState', 'maximized');
for mode_idx = 1:modes
subplot(2, 3, mode_idx)
plot(psi_real(mode_idx, plot_idx), psi_imag(mode_idx, plot_idx), 'k', LineWidth=1)
xlabel(sprintf('Re(ψ_%d)', mode_idx))
ylabel(sprintf('Im(ψ_%d)', mode_idx))
title(sprintf('Phase Plot (Re(ψ_%d),Im(ψ_%d))', mode_idx, mode_idx))
box on
grid on
fontsize(16, 'points')
subplot(2, 3, mode_idx + modes)
plot(u(plot_idx), psi_real(mode_idx, plot_idx), 'k', LineWidth=1)
xlabel('u')
ylabel(sprintf('Re(ψ_%d)', mode_idx))
title(sprintf('Phase Plot (u,Re(ψ_%d))', mode_idx))
box on
grid on
fontsize(16, 'points')
end
% Time series, time-averaged marginal PDFs, and ACFs of the latent large-scale
% zonal mean flow u and the retained topographic streamfunction modes.
figure('WindowState', 'maximized');
diagnostic_series = [u; psi_real(1, :); psi_imag(1, :); psi_real(2, :); psi_imag(2, :); psi_real(3, :); psi_imag(3, :)];
diagnostic_labels = {'u', 'Re(ψ_1)', 'Im(ψ_1)', 'Re(ψ_2)', 'Im(ψ_2)', 'Re(ψ_3)', 'Im(ψ_3)'};
diagnostic_colours = {[0 0.247 0.541], 'k', 'k', [0.850 0.325 0.098], [0.850 0.325 0.098], 'm', 'm'};
acf_lag_count = min(round((time_end_plot - time_start_plot)/(4*dt)), length(plot_idx)-1);
acf_lag_time = (0:acf_lag_count)*dt;
for diag_idx = 1:length(diagnostic_labels)
subplot(length(diagnostic_labels), 4, 4*(diag_idx-1) + [1, 2])
plot(plot_time, diagnostic_series(diag_idx, plot_idx), 'Color', diagnostic_colours{diag_idx}, LineWidth=1)
if diag_idx == length(diagnostic_labels)
xlabel('t')
end
ylabel(diagnostic_labels{diag_idx})
title(['Time Series of ', diagnostic_labels{diag_idx}], 'Interpreter', 'tex')
box on
grid on
fontsize(16, 'points')
subplot(length(diagnostic_labels), 4, 4*(diag_idx-1) + 3)
pdf_grid = linspace(min(diagnostic_series(diag_idx, plot_idx)), max(diagnostic_series(diag_idx, plot_idx)), 250);
tavg_pdf = ksdensity(diagnostic_series(diag_idx, plot_idx), pdf_grid);
plot(pdf_grid, tavg_pdf, 'Color', diagnostic_colours{diag_idx}, LineWidth=1)
hold on
mean_diagnostic = mean(diagnostic_series(diag_idx, plot_idx));
std_diagnostic = std(diagnostic_series(diag_idx, plot_idx));
plot(pdf_grid, normpdf(pdf_grid, mean_diagnostic, std_diagnostic), 'g--', LineWidth=1)
xlabel(diagnostic_labels{diag_idx})
ylabel(['p(', diagnostic_labels{diag_idx}, ')'])
title(['PDF of ', diagnostic_labels{diag_idx}], 'Interpreter', 'tex')
if diag_idx == 1
legend('Empirical', 'Gaussian Fit', Location='best')
end
box on
grid on
fontsize(16, 'points')
subplot(length(diagnostic_labels), 4, 4*diag_idx)
acf_values = autocorr(diagnostic_series(diag_idx, plot_idx), NumLags=acf_lag_count);
plot(acf_lag_time, acf_values, 'Color', diagnostic_colours{diag_idx}, LineWidth=1)
xlabel('Lag Time')
ylabel('ACF')
title(['ACF of ', diagnostic_labels{diag_idx}], 'Interpreter', 'tex')
box on
grid on
fontsize(16, 'points')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FILTERING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Inverse of the observational noise Grammian matrix defining the weight of the
% observational influence on the Bayesian update of the unobserved scalar u(t);
% noisier observations have less impact on the posterior uncertainty reduction
% of u(t). Using this fact, for conditional ACI, this matrix is also the
% precision mask that selects which observable streamfunction mode pair is
% allowed to reduce the posterior uncertainty of u(t) and therefore be
% considered the effect in the candidate causal link: Based on the ordering
% (v_1,v_2,v_3,v_4,v_5,v_6), selected_target_obs_indices = 1:2 corresponds to
% target ψ_1, resolved (ψ_2,ψ_3) (u(t) → ψ_1 | (ψ_2,ψ_3));
% selected_target_obs_indices = 3:4 corresponds to target ψ_2, resolved
% (ψ_1,ψ_3) (u(t) → ψ_2 | (ψ_1,ψ_3)); and selected_target_obs_indices = 5:6
% corresponds to target ψ_3, resolved (ψ_1,ψ_2) (u(t) → ψ_3 | (ψ_1,ψ_2)).
% Setting the elements corresponding to the resolved conditioning streamfunction
% modes in this matrix to zero simulates setting the marginal uncertainty of
% the corresponding real-valued, rotated (v_{2k-1},v_{2k}) variables in the
% likelihood to infinity (e.g. if selected_target_obs_indices = 1:2, so we
% resolve (v_3,...,v_6) or (ψ_2,ψ_3), then only S_xoS_x_inv(1,1) and
% S_xoS_x_inv(2,2) are nonzero, which corresponds to 1/(σ_3/sqrt(2))^2 → 0, ...,
% 1/(σ_6/sqrt(2))^2 → 0 and similarly for the (v_3,...,v_6) correlations in the
% corresponding off-diagonal elements of S_xoS_x_inv, which are already zero due
% to the independent additive noise in the dynamics, as in this limiting regime
% the resolved conditioned (v_3,...,v_6) can be thought of as diffuse or flat
% Bayesian priors). Therefore, we remove the direct observational uncertainty
% reduction for u(t) from these streamfunction modes while still retaining:
% (a) That from the target observed streamfunction mode pair and (b) the
% conditioning streamfunction modes' influence in the dynamics of u(t).
S_xoS_x_inv = zeros(obs_dim, obs_dim);
for target_idx = selected_target_obs_indices
S_xoS_x_inv(target_idx, target_idx) = 1/S_x(target_idx, target_idx)^2;
end
% Grammian of the unobservable process noise feedback.
S_yoS_y = S_y^2;
% Posterior filter mean of the latent variable u.
filter_mean = zeros(1, N+1);
% Initial value of the posterior filter mean.
filter_mean(1) = u(1); mu0 = filter_mean(1);
% Posterior filter covariance matrix of the latent variable u.
filter_cov = zeros(1, N+1);
% Initial value of the posterior filter covariance. Choosing a positive definite
% matrix to preserve the positive-definiteness of the posterior covariance
% matrices over time.
filter_cov(1) = 0.1; R0 = filter_cov(1);
% Used for the text-based progress bar.
start_time = tic;
for j = 2:N+1
% Text-based progress bar.
progress_bar('Filter Algorithm', j-1, N, start_time);
dx_obs = observed_state(:, j) - observed_state(:, j-1);
filter_gain_aux = R0*L_x(:, j-1)';
% Update the posterior filter mean and posterior filter covariance using the
% optimal nonlinear filter state estimation equations for CGNSs; see Theorem
% 2.1 in Section 2.1.2 of the Supplementary Information in the original ACI
% paper, https://doi.org/10.1038/s41467-026-68568-0.
mu = mu0 + (L_y*mu0 + f_y(j-1))*dt ...
+ filter_gain_aux*S_xoS_x_inv*(dx_obs - (L_x(:, j-1)*mu0 + f_x(:, j-1))*dt);
R = R0 + (L_y*R0 + R0*L_y' + S_yoS_y)*dt ...
- (filter_gain_aux*S_xoS_x_inv*filter_gain_aux')*dt;
filter_mean(j) = mu; mu0 = filter_mean(j);
filter_cov(j) = R; R0 = filter_cov(j);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SMOOTHING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Posterior smoother mean of the latent variable u.
smoother_mean = zeros(1, N+1);
% Posterior smoother covariance matrix of the latent variable u.
smoother_cov = zeros(1, N+1);
% Smoother runs backwards: "Initial" values of the smoother statistics (i.e. at
% the last time instant T) are the corresponding posterior filter statistics.
smoother_mean(N+1) = filter_mean(N+1); muT = smoother_mean(N+1);
smoother_cov(N+1) = filter_cov(N+1); RT = smoother_cov(N+1);
% Auxiliary matrices used for the calculation of the online smoother for this
% CGNS. The online smoother is required for the calculation of the subjective
% and objective forward and backward CIR lengths of the selected topographic
% model conditional causal relationship at each time t∈[0,T]. Notation used is
% consistent with that of the original CGNS online smoother work:
% ➤ https://doi.org/10.1007/s00332-026-10271-x
% and the accompanying martingale-free introduction to CGNSs paper:
% ➤ https://doi.org/10.3390/e27010002
E_j_matrices = zeros(1, N+1);
F_j_matrices = zeros(1, obs_dim, N+1);
G_y_j = L_y + S_yoS_y/filter_cov(N+1);
C_jj = 1 - G_y_j*dt;
E_j_matrices(N+1) = C_jj;
F_j_matrices(:, :, N+1) = G_y_j*filter_cov(N+1)*L_x(:, N+1)'*S_xoS_x_inv*dt;
% Used for the text-based progress bar.
start_time = tic;
for j = N:-1:1
% Text-based progress bar.
progress_bar('Smoother Algorithm', N-j+1, N, start_time);
% Calculation of the online smoother auxiliary matrices.
G_y_j = L_y + S_yoS_y/filter_cov(j);
C_jj = 1 - G_y_j*dt;
E_j_matrices(j) = C_jj;
F_j_matrices(:, :, j) = G_y_j*filter_cov(j)*L_x(:, j)'*S_xoS_x_inv*dt;
% Auxiliary matrices for the posterior smoother mean and covariance updates.
A_j = L_y;
B_j = S_yoS_y;
% Update the posterior smoother mean and posterior smoother covariance using
% the optimal nonlinear smoother state estimation backward equations for
% CGNSs; see Theorem 2.2 in Section 2.1.2 of the Supplementary Information
% in the original ACI paper, https://doi.org/10.1038/s41467-026-68568-0.
mu = muT - (L_y*muT + f_y(j) - B_j/filter_cov(j)*(filter_mean(j) - muT))*dt;
R = RT - ((A_j + B_j/filter_cov(j))*RT + RT*(A_j + B_j/filter_cov(j))' - B_j)*dt;
% Alternative and equivalent discrete-time smoother update equations for
% CGNSs using the online smoother auxiliary matrices. See the
% martingale-free introduction to CGNSs paper for more details:
% ➤ https://doi.org/10.3390/e27010002
% dx_obs = observed_state(:, j+1) - observed_state(:, j);
% E_j = E_j_matrices(j);
% F_j = F_j_matrices(:, :, j);
% mu = filter_mean(j) ...
% + E_j*(muT - (1 + L_y*dt)*filter_mean(j) - f_y(j)*dt) ...
% + F_j*(dx_obs - (L_x(:, j)*filter_mean(j) + f_x(:, j))*dt);
% R = filter_cov(j) ...
% + E_j*(RT*E_j' - (1 + L_y*dt)*filter_cov(j)) ...
% - F_j*L_x(:, j)*filter_cov(j)*dt;
smoother_mean(j) = mu; muT = smoother_mean(j);
smoother_cov(j) = R; RT = smoother_cov(j);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%% PLOTTING FILTER AND SMOOTHER RESULTS %%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Time series of the posterior filter and smoother Gaussian statistics of the
% latent candidate cause u after the conditional ACI precision masking (based
% on the chosen conditional causal relationship).
figure('WindowState', 'maximized');
plot(plot_time, u(plot_idx), 'b', LineWidth=1, DisplayName='Truth')
hold on
plot(plot_time, filter_mean(plot_idx), 'g', LineWidth=1, DisplayName='Filter')
plot(plot_time, smoother_mean(plot_idx), 'r', LineWidth=1, DisplayName='Smoother')
filter_upper = filter_mean(plot_idx) + 2*sqrt(filter_cov(plot_idx));
filter_lower = filter_mean(plot_idx) - 2*sqrt(filter_cov(plot_idx));
smoother_upper = smoother_mean(plot_idx) + 2*sqrt(smoother_cov(plot_idx));
smoother_lower = smoother_mean(plot_idx) - 2*sqrt(smoother_cov(plot_idx));
patch([plot_time, fliplr(plot_time)], [filter_lower, fliplr(filter_upper)], ...
'g', FaceAlpha=0.2, LineStyle='none', DisplayName='±2Std Filter')
patch([plot_time, fliplr(plot_time)], [smoother_lower, fliplr(smoother_upper)], ...
'r', FaceAlpha=0.2, LineStyle='none', DisplayName='±2Std Smoother')
xlabel('t')
ylabel('u')
title(sprintf('Time Series of u and of its Filter and Smoother Posterior Statistics (%s)', selected_forward_relationship_title))
legend(Location='best')
box on
grid on
fontsize(16, 'points')
% Comparison of the time-averaged low-order statistical diagnostics for the
% posterior state estimates of u (filter and smoother after the conditional ACI
% masking based on the chosen conditional causal relationship); normalised RMSE
% (NRMSE) and Pearson correlation coefficient.
nrmse_filter = rmse(u(plot_idx), filter_mean(plot_idx))/std(u(plot_idx));
nrmse_smoother = rmse(u(plot_idx), smoother_mean(plot_idx))/std(u(plot_idx));
relative_nrmse_change = 100*(nrmse_filter - nrmse_smoother)/nrmse_filter;
fprintf('Relative percentage change in smoother NRMSE from filter NRMSE for u in %s = %0.2f%% (+ = decreased, better)\n', strrep(selected_forward_relationship_title, '\rightarrow', '→'), relative_nrmse_change);
corr_filter_matrix = corrcoef(u(plot_idx), filter_mean(plot_idx));
corr_smoother_matrix = corrcoef(u(plot_idx), smoother_mean(plot_idx));
corr_filter = corr_filter_matrix(1, 2);
corr_smoother = corr_smoother_matrix(1, 2);
relative_corr_change = corr_smoother - corr_filter;
fprintf('Difference/Δ in smoother correlation from filter correlation for u in %s = %0.2f (+ = increased, better)\n', strrep(selected_forward_relationship_title, '\rightarrow', '→'), relative_corr_change);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ACI ANALYSIS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The topographic simulation is intentionally long so that the model displays
% multiple representative blocked/unblocked regime-switching episodes. As such,
% while the filter and smoother are first computed on the full trajectory or
% simulation window, the subsequent more expensive online-smoother-based
% conditional ACI and CIR calculations and analyses are restricted to the
% selected regime-switching window of choice for each conditional causal
% relationship based on the default random seed of rng(60). Since we do not run
% a full conditional ACI and CIR analysis on the entire simulation window, the
% chosen analysis window includes a buffer of time before and after the plotting
% window, as to accommodate for the fact that we will initiate the online
% smoother CGNS algorithm not from the start of the simulation but instead from
% a time instant usually much later than that. As a result, to account for this
% approach for computational efficiency, we add 10 time units before the period
% that is plotted, time_start_plot, and 10 time units after it, time_end_plot.
% Therefore, if for example we want to plot the period of 250 time units between
% 500–750, we should set:
% • analysis_time_start = 490
% • analysis_time_end = 760
if conditional_relationship_to_study == "u_to_psi_1_given_psi_2_psi_3"
% Conditional causal relationship u(t) → ψ_1 | (ψ_2,ψ_3).
% analysis_time_start = time_start_plot;
% analysis_time_end = time_end_plot;
analysis_time_start = 490;
analysis_time_end = 760;
elseif conditional_relationship_to_study == "u_to_psi_2_given_psi_1_psi_3"
% Conditional causal relationship u(t) → ψ_2 | (ψ_1,ψ_3).
% analysis_time_start = time_start_plot;
% analysis_time_end = time_end_plot;
analysis_time_start = 1990;
analysis_time_end = 2260;
elseif conditional_relationship_to_study == "u_to_psi_3_given_psi_1_psi_2"
% Conditional causal relationship u(t) → ψ_3 | (ψ_1,ψ_2).
% analysis_time_start = time_start_plot;
% analysis_time_end = time_end_plot;
analysis_time_start = 490;
analysis_time_end = 760;
end
% Crop the full simulation to the buffered analysis window. The ±10 buffer is
% handled by the plotting indices below; it is used only to properly: (a)
% initialise the conditional ACI and CIR calculations before the
% displayed/plotted interval due to not starting from t=0 (the -10), and (b) to
% avoid edge effects in the online smoother calculations due to saturation of
% observational information close to the end of the plotted interval (the +10).
analysis_crop_end = min(analysis_time_end, T);
analysis_idx = round(analysis_time_start/dt)+1:round(analysis_crop_end/dt)+1;
time_start_plot = analysis_time_start + 10;
time_end_plot = analysis_time_end - 10;
% From here onward, plot_idx is "local" or "relative" and to be used on the
% shortened "_s" arrays/variables below and analysis ACI and CIR arrays, while
% plot_time keeps the original physical time values for the plotting axes.
plot_idx = round((time_start_plot - analysis_time_start)/dt)+1:round((time_end_plot - analysis_time_start)/dt)+1;
plot_time = analysis_time_start + (plot_idx - 1)*dt;
% Theoretically, since the partially-observed stochastic dynamical system
% studied in this script is a real-valued CGNS, then the posterior filter and
% smoother covariances should remain, almost surely over the space of
% observable sample paths, finite, real-valued, symmetric, and positive
% semi-definite (PSD) at all times (or positive definite (PD) at all times if
% the filter covariance at the initial time t=0 is positive definite as well):
% ➤ https://doi.org/10.3390/e27010002
% ➤ https://doi.org/10.1007/978-3-662-10028-8
% However, due to finite numerical floating-point precision and/or because of
% discretisation errors (since we solve the continuous-time CGNS posterior
% filter/smoother state estimation equations in discrete time using the
% Euler-Maruyama method and a discretisation time step of dt=Δt), then the
% produced posterior filter/smoother covariances may violate these mathematical
% properties at some time instants. This is especially true for stiff update
% equations which might require very small time steps dt=Δt and for the smoother
% covariance, which is calculated backwards in time using the inverse of the
% filter covariance, and is therefore more prone to numerical instabilities.
% Still, these violations are extremely rare and usually occur only at one or
% two time instants, while also being very negligible. Still, to avoid script
% errors of this type to terminate the execution of the code, we regularise the
% posterior filter and/or smoother covariances only when such a finite numerical
% instability makes them non-real, non-symmetric, or non-PSD, and before any of
% the relative-entropy-based ACI and CIR calculations. This is achieved through
% a finite real-symmetric PD projection via a machine-scale eigenvalue or
% variance lift on the posterior covariance only whenever it is necessary. Valid
% posterior covariances over time remain unchanged. Also, for transparency and
% as a diagnostic summary, a brief report of the instances of these corrections
% and of any non-finite values is printed to the console for the user's
% information; a non-finite covariance naturally raises a clear error because it
% cannot be regularised without an intrusive intervention to the underlying
% mathematical, theoretical, and operational logic of the ACI and CIR framework.
filter_cov = shared_helper('regularise_posterior_covariance_history', filter_cov, dt, 'Filter');
smoother_cov = shared_helper('regularise_posterior_covariance_history', smoother_cov, dt, 'Smoother');
% Shortening all time-dependent variables of interest in the MATLAB workspace to
% the period of interest (±10 time units added as mentioned at the start of this
% section). We add '_s' to the names of these variables to denote this fact.
N_s = length(analysis_idx) - 1;
v_s = v(:, analysis_idx);
u_s = u(analysis_idx);
observed_state_s = observed_state(:, analysis_idx);
L_x_s = L_x(:, analysis_idx);
f_x_s = f_x(:, analysis_idx);
f_y_s = f_y(analysis_idx);
E_j_matrices_s = E_j_matrices(analysis_idx);
F_j_matrices_s = F_j_matrices(:, :, analysis_idx);
filter_mean_s = filter_mean(analysis_idx);
filter_cov_s = filter_cov(analysis_idx);
smoother_mean_s = smoother_mean(analysis_idx);
smoother_cov_s = smoother_cov(analysis_idx);
% Calculating the ACI metric for the selected conditional relationship at each
% time in the plotting window (after the ±10 buffer of the analysis window),
% i.e. the relative entropy from the posterior smoother to the filter of u(t)
% after the conditional ACI masking of the resolved non-target streamfunction
% modes:
% P(p_t^{s|(ψ_2,ψ_3)}(u|ψ_1), p_t^{f|(ψ_2,ψ_3)}(u|ψ_1)) (u(t) → ψ_1 | (ψ_2,ψ_3)),
% P(p_t^{s|(ψ_1,ψ_3)}(u|ψ_2), p_t^{f|(ψ_1,ψ_3)}(u|ψ_2)) (u(t) → ψ_2 | (ψ_1,ψ_3)), or
% P(p_t^{s|(ψ_1,ψ_2)}(u|ψ_3), p_t^{f|(ψ_1,ψ_2)}(u|ψ_3)) (u(t) → ψ_3 | (ψ_1,ψ_2)),
% which, due to the Gaussianity of these modified posterior distributions, all
% three of these divergences are given by the signal-dispersion formula; see
% Appendix G of the paper.
signal_smoother_filter = 0.5*(smoother_mean_s(plot_idx) - filter_mean_s(plot_idx)).^2./filter_cov_s(plot_idx);
cov_ratio_smoother_filter = smoother_cov_s(plot_idx)./filter_cov_s(plot_idx);
dispersion_smoother_filter = 0.5*(cov_ratio_smoother_filter - log(cov_ratio_smoother_filter) - 1);
ACI_metric = signal_smoother_filter + dispersion_smoother_filter;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD CIR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Implementation of the fixed-lag online smoother for CGNSs; see Appendix G of
% the paper and original CGNS online smoother paper for the theoretical and
% implementation details:
% ➤ https://doi.org/10.1007/s00332-026-10271-x
% The fixed-lag online smoother distributions,
% p(u(t_j)|target(s<=t_n); conditioning), after the conditional ACI masking of
% the resolved non-target streamfunction modes where the target is the selected
% corresponding ψ_k-mode pair and the conditioning variables are the pairs
% corresponding to the remaining two modes (ψ_{k'},ψ_{k''}) k≠k'≠k'', are needed
% to evaluate the forward CIR metric (and by extension the subjective and
% objective forward CIRs) for the selected topographic model conditional
% relationship as a function of the lagged observational time t_n<=T at each
% fixed natural time t_j. In the following implementation, the relative entropy
% from the complete smoother distribution p(u(t_j)|target(s<=t_N); conditioning)
% to the lagged smoother distribution p(u(t_j)|target(s<=t_n); conditioning) is
% calculated at each natural time t_j (in the analysis window) for all lagged
% observational times t_j<=t_n<=t_N=T (where t_N=T=analysis_time_end),
% P^j_n := P(p(u(t_j)|target(s<=t_N); conditioning), p(u(t_j)|target(s<=t_n); conditioning)),
% where both posterior distributions are Gaussian for this CGNS. See Appendix G
% of the paper for the background, notations, and details.
% The fixed-lag parameter is set equal to the total number of observations,
% N = ⌈T/Δt⌉, such that at each time instant the full backward algorithm is
% carried out. This is because each conditional ACI masked online smoother
% distribution, p(u(t_j)|target(s<=t_n); conditioning), is needed for the
% calculation of the subjective and objective forward CIRs; see Appendix G of
% the paper. (N_s+1 due to the "initial" condition in the analysis window.)
fixed_lag = N_s+1;
% Saving the online smoother mean, online smoother covariance matrices, and
% update matrices in a cell array where each row is another cell array with as
% many columns as the cardinal number of the current row. Using such nested cell
% arrays efficiently simulates staggered arrays in MATLAB. This approach
% efficiently preserves space in memory without defining unnecessarily large
% high-order tensors to store the online smoother estimations and update
% matrices. In these nested cell arrays, the first/parent index corresponds to
% n∈{j,j+1,...,N}, for the current selected target streamfunction-mode
% observation ψ_k^n = ψ_k(t_n), while the second/child index corresponds to
% j∈{0,1,...,N}, for the time instant t_j at which we carry out the online
% smoother state estimation for u^j = u(t_j).
online_fixed_mean = cell(N_s+1, 1);
online_fixed_cov = cell(N_s+1, 1);
update_matrices_fixed = cell(N_s-1, 1);
for n = 1:(N_s-1)
update_matrices_fixed{n} = zeros(1, n+1);
online_fixed_mean{n} = zeros(1, n);
online_fixed_cov{n} = zeros(1, n);
end
for n = N_s:N_s+1
online_fixed_mean{n} = zeros(1, n);
online_fixed_cov{n} = zeros(1, n);
end
% Need to do the first two observations manually.
% A single observation (n=1).
online_fixed_mean{1}(1) = filter_mean_s(1);
online_fixed_cov{1}(1) = filter_cov_s(1);
% Two observations (n=2).
online_fixed_mean{2}(2) = filter_mean_s(2);
online_fixed_cov{2}(2) = filter_cov_s(2);
if fixed_lag == 0