-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSingleInstrumentWaveRoseAvg.m
More file actions
3018 lines (2511 loc) · 127 KB
/
Copy pathSingleInstrumentWaveRoseAvg.m
File metadata and controls
3018 lines (2511 loc) · 127 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
% SINGLEINSTRUMENT_CROSSWAVELET_EXPLICIT
%
% This function processes a single GOES satellite instrument (e.g., IR)
% by computing single–frame wavelet transforms and then computing cross–temporal
% cross–wavelets (i.e., the coherence between consecutive frames of the same instrument).
% Only the current and previous frame's transforms are held in memory.
%
% All parameters and thresholds (for spatial scaling, wavelet analysis,
% windowing, preprocessing, etc.) are defined in the "Variables Setup" section.
%% 1) VARIABLES SETUP
%----------- DATA-SOURCE MODE --------------------------------------------
useCustomFolder = true; % false ➜ normal GOES workflow
% CHOOSE YOUR CUSTOM DATA MODE
% 'sprintf' -> Generates filenames using a pattern and indices (the original "true custom" method).
% 'merg_style' -> Scans a folder for 'merg_YYYYMMDDHHmm_...' files (the new "mergir" option).
customDataMode = 'sprintf'; % <-- SET YOUR MODE HERE
customFolderPath = 'C:\Users\admin\Box\GWaves_Synthetic_G16ncfiles\Testcell2';
% spacing between consecutive frames
custom_t_seconds = 1800; % 1800 for 30-min data (like 'sprintf' example)
% Settings ONLY for 'sprintf' mode
customFilePattern = 'closedcell_IR_2waves_halfhour%d.nc'; % sprintf() pattern
customFileIndices = 0:9; % which “halfhourN” files to read
customStartDate = datetime(2704, 1, 1, 0, 0, 0); % anchor timestamp
if useCustomFolder
startDate = customStartDate;
endDate = customStartDate + seconds(custom_t_seconds)*length(customFileIndices);
else
%----------- DATE/TIME SETTINGS ---------------------------
%startDate = datetime(2023, 10, 12, 1, 0, 0); % start processing time
%endDate = datetime(2023, 10, 12, 3, 30, 0); % end processing time
startDate = datetime(2023, 10, 12, 14, 0, 0); % start processing time
%endDate = datetime(2023, 10, 11, 15, 0, 0); % start processing time
endDate = datetime(2023, 10, 12, 20, 30, 0); % end processing time
end
%----------- FOLDER/PATH SETTINGS ---------------------------
rootSepacDir = 'C:\Users\admin\Box\GWaves_2023_10_11-14_SEPAC';
sourceRoot = 'C:\Users\admin\Box\GOES2go_satellite_downloads'; % (Used in renaming)
%----------- INSTRUMENT SETTINGS ----------------------------
instrument = 'IR'; % Choose 'IR' or 'VIS'
%----------- SPATIAL SCALING & RESIZING --------------------
degrees_per_pixel = 0.04; % Degrees per pixel (typical for GOES)
km_per_degree = 111.32; % km per degree
shrinkfactor = 2; % Image is resized by this factor (2 => half the resolution)
invshrinkfactor = 1 / shrinkfactor;
original_px_km = degrees_per_pixel * km_per_degree;
%----------- WAVELET PARAMETERS -----------------------------
Angles = 0 : pi/(7*2) : pi; % Wavelet angles (in radians)
Scales = [2, 4, 8, 16, 32, 64]; % Wavelet scales in pixel units
Scales_orig = Scales; % That will anchor the Scales values in case there's a ShrinkFactor >1
NANGLES = numel(Angles); % Number of angles
NSCALES = numel(Scales); % Number of scales
CustomWavelet = false; % This flag indicates whether to use a custom (elliptical) wavelet instead of the default built-in one.
coneAngle = pi/6; % The variable coneAngle specifies the angular extent of the directional mask and influences the wavelet's sensitivity to orientation.
sigmaX = 0.05; % The parameter sigmaX defines the decay rate of the wavelet's envelope along the horizontal frequency axis (ωX), affecting its horizontal resolution.
sigmaY = 1.95; % The parameter sigmaY defines the decay rate of the wavelet's envelope along the vertical frequency axis (ωY), affecting its vertical resolution.
alpha = 0.5; % The variable alpha is an overall radial decay factor that controls how sharply the wavelet decays in the frequency domain, thereby influencing the scale (frequency) resolution independently of the directional parameters.
%----------- WINDOWING SETTINGS -----------------------------
doWindow = true; % Flag to apply windowing
windowType = 'rectangular'; % 'radial' or 'rectangular'
radius_factor = 0.6; % Parameter for window function (if used)
decay_rate = 10; % Controls steepness of window edge
%----------- SQUARE-PARTITIONING PARAMETERS ----------------
window_buffer = 0; % Number of pixels to ignore at each edge
square_size_deg = 10; % Square size (in degrees) for ROI partitioning
%----------- PREPROCESSING THRESHOLDS -----------------------
% For IR
IR_threshold = 0 ; %274; %277; % IR threshold: values below are set to NaN
IR_fillPercentile = 50; % Fill IR masked pixels with this percentile
useCumulativeMask = true; % If true we build one static mask
cumulativeIRmask = []; % Will hold the union of clouds
True_Color_IR = true; % Will display the IR video in real colors ( harder to see waves but real visuals )
% For VIS (not used if processing only IR, but kept for consistency)
VIS_lowerPercentile = 10; % VIS lower bound (percentile)
VIS_upperPercentile = 99; % VIS upper bound (percentile)
VIS_fillPercentile = 50; % Fill VIS NaN pixels with this percentile
Insolation_Correction = true; % activate the insolation grid calculation and correction
%----------- HIGH-PASS FILTER SETTINGS ----------------------
clipMinHP = -3; % Minimum value to clip after highpass filtering
clipMaxHP = 3; % Maximum value to clip after highpass filtering
lowPassFilterWidth_20 = 20;
lowPassFilterWidth_50 = 50;
lowPassFilterWidth_100 = 100;
%----------- PREPROCESSING METHOD SELECTION -----------------
switch upper(instrument)
case 'IR'
methodName = 'highpass_50_sqrt';
case 'VIS'
methodName = 'none';
otherwise
error('Unknown instrument: %s', instrument);
end
%----------- WAVE-ROSE & PEAK DETECTION ---------------------
nAngles_fineFactor = 4; % Factor to refine angular resolution in the rose plot
nScales_fineFactor = 4; % Factor to refine scale resolution in the rose plot
peakDetectionFactor = 1; % Threshold factor (mean + factor*std) for peak detection
%contourArray = [95 97 99]; % [Used as either percentiles or absolute values for contouring]
%ArrayMode = 'percentile'; % 'percentile' or 'absolute'
%----------- IMAGE ANNOTATIONS & OUTPUT ---------------------
saverose = true; % Flag to save the wave–rose image
DisplayValuePower = 4*10^-2;
DisplayValueCoherence = 1;
DisplayValuePhase = [-pi;pi];
DisplayValueSpeed = [-15;15];
%----------- ADVECTION CORRECTION SETTINGS -----------------
doAdvectionEstimation = true; % Set to true to estimate mean advection
scalesForAdvection = [4, 8, 16, 32]; % Use these pixel scales for advection estimation (central scales)
cohThreshold = 0.2; % Only use (scale,angle) bins where coherence (or its square root) is >= 0.2
amplitudeThreshold = 0; % (Optional) ignore bins with amplitude below this threshold
%----------- SPEED CORRECTION SETTINGS -------------------
% you can either play with the parameters or use a specific calibration Matrix
beta = 0.8; % Weight for smoothing toward baseline trend
decayFactor = 0.55; % Amplitude decay applied to baseline smoothing
decaySharpness = 1.2; % Controls how sharply the baseline trend decays with scale
upperCutoff = 16; % Upper trusted scale
%nyquistScales= Scales_orig(1:2); % Scales that are likely to be hit by nyquist issue
nyquistScales= Scales_orig(:,Scales_orig<=8); % Scales that are likely to be hit by nyquist issue
matrixMode = true;
calibrationMatrix = [
2, 0.50;
4, 0.50;
8, 0.50;
16, 0.40;
32, 0.335;
64, 0.17;
128, 0.083;
];
%----------- SPEED CORRECTION MODE -------------------------
% Choose which large-scale speed limiter you want to use
% 'classic' -> limitSpeedByScale
% 'azimuthal' -> limitSpeedByScale_Azimuthal
% 'both' -> produce both outputs; the one set in primaryCorrection
% is propagated to downstream (advection + global)
correctionMode = 'classic'; % 'classic' | 'azimuthal' | 'both'
primaryCorrection = 'classic'; % only used when correctionMode = 'both'
%----------- SYNTHETIC DATA SETTINGS ----------------------
syntheticWaveMode = false; % If true, superimpose a synthetic wave on a fixed base image
driftMode = false; % If true, apply a drift shift each frame using circshift
% Drift parameters (in m/s) rather than pixels/frame:
drift_speed_m_s = 15; % e.g. 10 m/s
driftAngleDeg = 45+90; % e.g. 45 degrees (0 = right, 90 = up) // the image is inverted !!
% Parameters for the synthetic wave:
cphase = 15; % Phase speed (m/s)
wavelength = 2*150e3; % Wavelength in meters
direction = 235; % Propagation from direction in degrees
zamplitude = 100; % Vertical amplitude (m)
PBLdepth = 1000; % Boundary layer depth (m)
dB_dzPBL = 0.1; % dB / (dZ/PBLdepth) | Change of brightness with zamplitude
T_cloud_K = 280; % cloud selection threshold (IR Kelvin)
% Parameters for the spatial amplitude window (wave packet)
packet_center_x = -400e3;
packet_center_y = -400e3;
packet_width_x = 4*400e3;
packet_width_y = 4*300e3;
% Synthetic wave scaling factor for spatial coordinates
% This factor modifies DX, which represents the real-world distance per pixel.
% A smaller DX means that each pixel covers a smaller physical distance,
% effectively "zooming in" and making the wave pattern appear larger in the image.
% Conversely, a larger DX means that each pixel covers a larger real-world distance,
% making the wave pattern appear smaller and more compressed.
%
% Example:
% - DXFactor = 1 means the default scaling (1:1 with pixel size).
% - DXFactor = 1/4 means the wave features are stretched, appearing 4x larger.
% - DXFactor = 4 means the wave features are shrunk, appearing 4x smaller.
DXFactor = 1;
% Seconds between frames (important for drift or wave stepping)
time_resolution = 1800;
%----------- PEAK-DETECTION/Brightness decay SETTINGS -----------------------------------
speed_min_threshold = 14; % [m s-1] absolute floor
speed_std_factor = 2; % N·σ above local mean
maxPeaksPerROI = 3; % safety cap (set [] for unlimited)
clevfactor_real = 1.5; % divides contour levels (real)
clevfactor_imag = 2; % divides contour levels (imag)
contourOption = 'percentile'; % 'percentile' | '3sigma'
contourArray = [50 60 70]; % if 'percentile'
%-------------------Shrink Factor Settings Update-----------------------------------------
if shrinkfactor ~= 1
pixel_size_km = original_px_km * shrinkfactor;
Scales = Scales_orig / shrinkfactor; % already in your code
scalesForAdvection = scalesForAdvection / shrinkfactor;
else
pixel_size_km = original_px_km;
end
% convert thresholds/tables keyed in original pixels
nyquistScales_post = nyquistScales / shrinkfactor; % e.g. [2 4 8] -> [1 2 4] if s=2
upperCutoff_post = upperCutoff / shrinkfactor; % e.g. 16 -> 8
calibrationMatrix_post = [calibrationMatrix(:,1)/shrinkfactor, calibrationMatrix(:,2)];
assignin('base','calibrationMatrix',calibrationMatrix_post); % if your function reads from base
%% 2) RETRIEVE FILE LIST
% Raw data is assumed to be in:
% <rootSepacDir>\INSTRUMENT\Data
if useCustomFolder
% --- Logic for handling different custom data modes ---
switch lower(customDataMode)
case 'sprintf'
% The original "true custom" method
fprintf("Using 'sprintf' mode to generate file list.\n");
dataDir = customFolderPath;
fNames = arrayfun(@(k) sprintf(customFilePattern,k), customFileIndices, 'uni',0);
fTimes = customStartDate + seconds(custom_t_seconds) * (0:numel(fNames)-1);
case 'merg_style'
% The new method for 'merg' or AllenCell style files
fprintf("Using 'merg_style' mode to parse filenames.\n");
dataDir = customFolderPath;
% Find all files matching the merg pattern with .nc extension
fileList = dir(fullfile(dataDir, 'merg_*.nc'));
if isempty(fileList)
error('No files matching ''merg_*.nc'' found in %s', dataDir);
end
fNames = {fileList.name}; % Get filenames (usually sorted by OS)
% Parse timestamps directly from the filenames
fTimes = NaT(1, numel(fNames)); % Pre-allocate a datetime array
for i = 1:numel(fNames)
dateStr = extractBetween(fNames{i}, '_', '_');
if isempty(dateStr)
warning('Could not parse timestamp from filename: %s. Skipping.', fNames{i});
continue;
end
fTimes(i) = datetime(dateStr{1}, 'InputFormat', 'yyyyMMddHHmm');
end
% Remove any files that failed to parse
validFiles = ~isnat(fTimes);
fNames = fNames(validFiles);
fTimes = fTimes(validFiles);
% Sort files by parsed time to ensure correct order
[fTimes, sortIdx] = sort(fTimes);
fNames = fNames(sortIdx);
otherwise
error("Unknown customDataMode: '%s'. Please choose 'sprintf' or 'merg_style'.", customDataMode);
end
% --- Common logic for ALL custom modes ---
% Update the main startDate and endDate based on the files that were actually found
% if ~isempty(fTimes)
% startDate = fTimes(1);
% endDate = fTimes(end);
% end
% Try to detect the variable name only once from the first valid file
if ~isempty(fNames)
info = ncinfo(fullfile(dataDir,fNames{1}));
varList = {info.Variables.Name};
if any(strcmp(varList,'CMI')), varName = 'CMI';
elseif any(strcmp(varList,'Rad')), varName = 'Rad';
elseif any(strcmp(varList,'Tb')), varName = 'Tb';
else varName = varList{1}; % Fallback to the first variable
end
else
varName = ''; % No files found
end
else
% This is the original logic for the normal GOES workflow (unchanged)
dataDir = fullfile(rootSepacDir, upper(instrument), 'Data');
if ~exist(dataDir, 'dir')
error('Data directory for %s not found: %s', instrument, dataDir);
end
[fNames, fTimes, varName] = getDateRangeFiles(dataDir, startDate, endDate);
end
numFrames = numel(fTimes);
if numFrames == 0
fprintf('No frames found for %s in the given time period.\n', instrument);
return;
end
fprintf('Found %d frames for instrument %s.\n', numFrames, instrument);
if useCumulativeMask
fprintf('\n--- Pass-0 : building cumulative high-cloud mask (drift-aware) ---\n');
cumulativeIRmask = false; % au format après shrink & window
for i = 1:numFrames
% 1) raw mask from the original (un-drifted) frame
data = double( ncread( fullfile(dataDir,fNames{i}), varName ) );
% 2) apply transforms to the image
% ---- On the first frame, store base_frame & possibly precompute synthetic-wave grids ----
if i == 1
base_frame = data;
if syntheticWaveMode
[rowsF, colsF] = size(base_frame);
[X, Y] = meshgrid(1:colsF, 1:rowsF);
% Real‐world pixel size (m), factoring in DXFactor:
DX = 1000 * original_px_km * DXFactor;
Xm = (X - mean(X(:))) * DX;
Ym = (Y - mean(Y(:))) * DX * -1; % negative if Y runs downward
end
elseif syntheticWaveMode || driftMode
% If doing synthetic wave or drift, start from the same base frame each iteration:
data = base_frame;
end
% ---- Synthetic wave injection (if enabled) ----
if syntheticWaveMode
% --- meteo → math angle conversion (0° = Est, trigonometrical direction) ---
theta = deg2rad(90 - direction); % direction given in meteorological convention
% --- wave vector ---
k = (2*pi / wavelength) * cos(theta); % kx
l = (2*pi / wavelength) * sin(theta); % ky (kept for phase)
omega = cphase * (2 * pi / wavelength);
% Time for current frame
t = (i - 1) * time_resolution; % e.g. in seconds
% Evolving phase
phase = k * Xm + l * Ym - omega * t;
% Vertical displacement
dz = zamplitude * sin(phase);
% Envelope to localize wave in a region
Ampwindow = exp( -(((Xm - packet_center_x) / packet_width_x).^2 ...
+ ((Ym - packet_center_y) / packet_width_y).^2) );
dz = dz .* Ampwindow;
% --- horizontal displacement associayted to w' ---
dxy = (zamplitude / PBLdepth) * wavelength .* ...
sin(phase - pi/2) ./ DX; % scalar amplitude in px
dx = dxy .* cos(theta).* Ampwindow; % composante O-E (columns)
dy = dxy .* sin(theta).* Ampwindow; % composante S-N (lines)
% Create new coordinates for interpolation:
XI = X - dx;
YI = Y - dy;
% Warp the fixed base image:
warped_img = interp2(X, Y, base_frame, XI, YI, 'linear', 0);
% Modulate brightness with the vertical displacement (dz):
modulated_img = warped_img .* (1 + dz / PBLdepth * dB_dzPBL);
% Use the resulting image as the data for further processing:
data = modulated_img;
end
% ---- Drift shift (if enabled) ----
if driftMode && i > 1
% Determine how many meters the image should shift in the time between frames:
driftDistance_m = drift_speed_m_s * time_resolution* (i - 1); % e.g. 10 m/s * 1800 s = 18000 m
% Convert to pixel shift
driftDistance_km = driftDistance_m / 1000;
pxShift = driftDistance_km / (original_px_km); % e.g. if pixel_size_km=9 => pxShift=2000/9
pxShift = round(pxShift); % round to nearest integer for circshift
% Break it into X shift and Y shift based on the drift angle
% (Angle=0 => shift in +X direction, 90 => shift in -Y direction, etc.)
shift_dx = pxShift * cosd(driftAngleDeg);
shift_dy = -pxShift * sind(driftAngleDeg);
% The minus sign depends on how you define the Y orientation in your matrix:
% Typically, "down" in the matrix is +Y, so if angle=90 means shift "up", that's negative row shift.
shift_dx = round(shift_dx);
shift_dy = round(shift_dy);
% circshift( data, [row_shift, column_shift] )
data = circshift(data, [shift_dy, shift_dx]);
end
thisMask = data < IR_threshold; % high clouds in *this* frame
% 3) logical union
if i == 1
cumulativeIRmask = thisMask;
else
cumulativeIRmask = cumulativeIRmask | thisMask;
end
end
fprintf('☑ cumulative mask created (%d×%d)\n', size(cumulativeIRmask));
end
%% 2.1) QUICK-LOOK VIDEO PREVIEW (custom data only)
makePreviewVideo = true; % ← flip to false to disable
if useCustomFolder && makePreviewVideo
fprintf('\n--- Generating preview movie of raw vs. pre-processed frames ---\n');
% where to save it
previewDir = fullfile(customFolderPath, 'preview');
if ~exist(previewDir, 'dir'), mkdir(previewDir); end
vidFile = fullfile(previewDir, 'CustomPreview_raw_vs_preprocessed.mp4');
% mpeg-4 works everywhere; 15 fps = ~1 s/day for 30-min spacing
vObj = VideoWriter(vidFile, 'MPEG-4');
vObj.FrameRate = 15;
open(vObj);
hFig = figure('Name','Preview – raw | pre-processed', ...
'Position',[100 100 1200 500]);
for kk = 1:numFrames
% --- read original ------------------------------------------------
fPath = fullfile(dataDir, fNames{kk});
orig = double(ncread(fPath, varName));
% --- apply EXACT same preprocessing as the main loop --------------
pre = preprocessFrame(orig, instrument, methodName, ...
fPath, fTimes(kk), ...
IR_threshold, IR_fillPercentile, ...
VIS_lowerPercentile, VIS_upperPercentile, ...
VIS_fillPercentile, ...
clipMinHP, clipMaxHP, ...
lowPassFilterWidth_20, ...
lowPassFilterWidth_50, ...
lowPassFilterWidth_100, ...
Insolation_Correction, cumulativeIRmask);
if shrinkfactor ~= 1
pre = imresize(pre, invshrinkfactor);
end
if doWindow
switch lower(windowType)
case 'radial', pre = applyRadialWindow(pre, radius_factor, decay_rate);
case 'rectangular', pre = applyRectangularWindow(pre, radius_factor, decay_rate);
end
end
% --- assemble side-by-side RGB frame ------------------------------
ax1 = subplot(1,2,1); imagesc(ax1, orig'); axis(ax1,'image','off');
title(ax1, sprintf('RAW | %s', datestr(fTimes(kk))),'FontSize',10);
colormap(gray)
ax2 = subplot(1,2,2); imagesc(ax2, pre ); axis(ax2,'image','off');
title(ax2, 'PRE-PROCESSED','FontSize',10);
colormap(gray)
drawnow;
frame = getframe(hFig);
writeVideo(vObj, frame);
end
close(vObj); close(hFig);
fprintf('☑ Preview saved ➜ %s\n', vidFile);
% optional: automatically play it
% implay(vidFile);
end
%% 3) MAIN PROCESSING LOOP (Single instrument + cross–temporal coherence)
% Rewritten to accumulate sums over the entire domain first.
% 3A) Allocate accumulators for single–frame wave–rose (i.e., power)
% and for cross–temporal coherence. We accumulate across all frames.
[rowsF, colsF] = deal([]); % Will be set after first frame is processed
power_sum = []; % For sum of |spec_full|^2 across frames
crossSpec_sum = []; % For sum of (B1 * conj(B2)) across frame pairs
B1_auto_sum = []; % For sum of |B1|^2
B2_auto_sum = []; % For sum of |B2|^2
phaseExp_sum = [];
prevWaveletSpec = []; % Will store wavelet from previous frame for cross–temporal coherence
for f_idx = 1:numFrames
% ---- Prepare basic info about this frame ----
thisTime = fTimes(f_idx);
frameDateStr = datestr(thisTime, 'yyyy_mm_dd_HHMMSS');
fprintf('\nProcessing frame [%d/%d]: %s\n', f_idx, numFrames, frameDateStr);
%singleOutDir = fullfile(rootSepacDir, 'Test');
singleOutDir = 'C:\Users\admin\Documents\GitHub\Stratocu-Waves-Jr\test';
if ~exist(singleOutDir, 'dir')
mkdir(singleOutDir);
end
singleNcFile = fullfile(singleOutDir, sprintf('FrameWavelet_%s.nc', frameDateStr));
% ---- Read the raw data from file ----
thisFileName = fNames{f_idx};
thisFullPath = fullfile(dataDir, thisFileName);
data = double(ncread(thisFullPath, varName));
% ---- On the first frame, store base_frame & possibly precompute synthetic-wave grids ----
if f_idx == 1
base_frame = data;
if syntheticWaveMode
[rowsF, colsF] = size(base_frame);
[X, Y] = meshgrid(1:colsF, 1:rowsF);
% Real‐world pixel size (m), factoring in DXFactor:
DX = 1000 * original_px_km * DXFactor;
Xm = (X - mean(X(:))) * DX;
Ym = (Y - mean(Y(:))) * DX * -1; % negative if Y runs downward
end
elseif syntheticWaveMode || driftMode
% If doing synthetic wave or drift, start from the same base frame each iteration:
data = base_frame;
end
% ---- Synthetic wave injection (if enabled) ----
if syntheticWaveMode
% --- meteo → math angle conversion (0° = Est, trigonometrical direction) ---
theta = deg2rad(90 - direction); % direction given in meteorological convention
% --- wave vector ---
k = (2*pi / wavelength) * cos(theta); % kx
l = (2*pi / wavelength) * sin(theta); % ky (kept for phase)
omega = cphase * (2 * pi / wavelength);
% Time for current frame
t = (f_idx - 1) * time_resolution; % e.g. in seconds
% Evolving phase
phase = k * Xm + l * Ym - omega * t;
% Vertical displacement
dz = zamplitude * sin(phase);
% Envelope to localize wave in a region
Ampwindow = exp( -(((Xm - packet_center_x) / packet_width_x).^2 ...
+ ((Ym - packet_center_y) / packet_width_y).^2) );
dz = dz .* Ampwindow;
% --- horizontal displacement associayted to w' ---
dxy = (zamplitude / PBLdepth) * wavelength .* ...
sin(phase - pi/2) ./ DX; % scalar amplitude in px
dx = dxy .* cos(theta).* Ampwindow; % composante O-E (columns)
dy = dxy .* sin(theta).* Ampwindow; % composante S-N (lines)
% Create new coordinates for interpolation:
XI = X - dx;
YI = Y - dy;
% Warp the fixed base image:
warped_img = interp2(X, Y, base_frame, XI, YI, 'linear', 0);
% Modulate brightness with the vertical displacement (dz):
%modulated_img = warped_img .* (1 + dz / PBLdepth * dB_dzPBL);
% Use the resulting image as the data for further processing:
%data = modulated_img;
% --- Cloud-conditional brightness modulation ---
% Sensitivity and thresholds (tune as needed)
S_B = dB_dzPBL; % slide’s S_B (same symbol you already use)
% 1) frame-mean of the warped image
Bbar = mean(warped_img(:), 'omitnan');
% 2) cloud mask (apply only to cloudy pixels)
cloudMask = warped_img < T_cloud_K;
% 3) final brightness, case-wise
B_final = warped_img; % default: unchanged
scaleTerm = S_B .* (dz ./ PBLdepth); % S_B * Δz/H_PBL
B_final(cloudMask) = warped_img(cloudMask) + ...
(warped_img(cloudMask) - Bbar) .* scaleTerm(cloudMask);
% (optional) keep values in plausible IR range if your base frame is BT:
% B_final = max(min(B_final, 320), 180);
% Use this for downstream processing:
data = B_final;
end
% ---- Drift shift (if enabled) ----
if driftMode && f_idx > 1
% Determine how many meters the image should shift in the time between frames:
driftDistance_m = drift_speed_m_s * time_resolution* (f_idx - 1); % e.g. 10 m/s * 1800 s = 18000 m
% Convert to pixel shift
driftDistance_km = driftDistance_m / 1000;
pxShift = driftDistance_km / (original_px_km); % e.g. if pixel_size_km=9 => pxShift=2000/9
pxShift = round(pxShift); % round to nearest integer for circshift
% Break it into X shift and Y shift based on the drift angle
% (Angle=0 => shift in +X direction, 90 => shift in -Y direction, etc.)
shift_dx = pxShift * cosd(driftAngleDeg);
shift_dy = -pxShift * sind(driftAngleDeg);
% The minus sign depends on how you define the Y orientation in your matrix:
% Typically, "down" in the matrix is +Y, so if angle=90 means shift "up", that's negative row shift.
shift_dx = round(shift_dx);
shift_dy = round(shift_dy);
% circshift( data, [row_shift, column_shift] )
data = circshift(data, [shift_dy, shift_dx]);
end
% ---- Preprocessing (thresholds, highpass, etc.) ----
data_pre = preprocessFrame(data, instrument, methodName, ...
thisFullPath, thisTime, ...
IR_threshold, IR_fillPercentile, ...
VIS_lowerPercentile, VIS_upperPercentile, ...
VIS_fillPercentile, clipMinHP, clipMaxHP, ...
lowPassFilterWidth_20, lowPassFilterWidth_50, lowPassFilterWidth_100, ...
Insolation_Correction,cumulativeIRmask);
% ---- Resize or window if needed ----
if shrinkfactor ~= 1
data_pre = imresize(data_pre, invshrinkfactor);
end
if doWindow
switch lower(windowType)
case 'radial'
data_pre = applyRadialWindow(data_pre, radius_factor, decay_rate);
case 'rectangular'
data_pre = applyRectangularWindow(data_pre, radius_factor, decay_rate);
end
end
% Determine the final 2D size (post‐resize):
[rowsF, colsF] = size(data_pre);
% ---- Compute wavelet transform on this processed frame ----
if CustomWavelet
waveStruct = barebonesCauchy2D_Elliptical_NoShift( ...
data_pre, Scales, Angles, ...
coneAngle, sigmaX, sigmaY, alpha);
else
waveStruct = cwtft2(data_pre, ...
'wavelet','cauchy', ...
'scales', Scales, ...
'angles', Angles);
end
% cfs: size [rowsF, colsF, NSCALES, NANGLES]
spec_full = squeeze(waveStruct.cfs);
% Optional amplitude scaling by (pi/sqrt(2)) /scale:
for iS = 1:NSCALES
spec_full(:,:,iS,:) = spec_full(:,:,iS,:) * ((pi/sqrt(2)) / Scales(iS));
end
% ---- Init accumulators if this is the first time we know rowsF, colsF ----
if isempty(power_sum)
power_sum = zeros(rowsF, colsF, NSCALES, NANGLES, 'like', spec_full);
crossSpec_sum = zeros(rowsF, colsF, NSCALES, NANGLES, 'like', spec_full);
B1_auto_sum = zeros(rowsF, colsF, NSCALES, NANGLES, 'like', spec_full);
B2_auto_sum = zeros(rowsF, colsF, NSCALES, NANGLES, 'like', spec_full);
% For phase difference averaging:
phaseExp_sum = zeros(rowsF, colsF, NSCALES, NANGLES, 'like', spec_full) + 0i;
end
% ---- Accumulate single‐frame wave–rose (power) sums ----
power_sum = power_sum + abs(spec_full).^2;
%--- Cross-temporal stuff only if we have a previous frame ---
if ~isempty(prevWaveletSpec)
crossSpec_product = prevWaveletSpec .* conj(spec_full);
crossSpec_sum = crossSpec_sum + crossSpec_product;
B1_auto_sum = B1_auto_sum + abs(prevWaveletSpec).^2;
B2_auto_sum = B2_auto_sum + abs(spec_full).^2;
% Also accumulate a sum of the phase difference:
phase_mat = angle(crossSpec_product);
phaseExp_sum = phaseExp_sum + exp(1i * phase_mat);
end
prevWaveletSpec = spec_full; % Store for next iteration
end
%% 4A) ROI-BASED SUMMARIES
% Build ROI squares.
effective_degrees_per_pixel = degrees_per_pixel * shrinkfactor;
square_size_px = round(square_size_deg / effective_degrees_per_pixel);
x_buffer_range = (window_buffer+1) : (colsF - window_buffer);
y_buffer_range = (window_buffer+1) : (rowsF - window_buffer);
adjusted_frame_width = length(x_buffer_range);
adjusted_frame_height = length(y_buffer_range);
num_squares_x = ceil(adjusted_frame_width / square_size_px);
num_squares_y = ceil(adjusted_frame_height / square_size_px);
squares = [];
idxS = 1;
for iy = 1:num_squares_y
for ix = 1:num_squares_x
x_start = floor((ix - 1) * adjusted_frame_width / num_squares_x) + 1;
y_start = floor((iy - 1) * adjusted_frame_height / num_squares_y) + 1;
x_end = floor(ix * adjusted_frame_width / num_squares_x);
y_end = floor(iy * adjusted_frame_height / num_squares_y);
if x_end > x_start && y_end > y_start
squares(idxS).x_range = x_buffer_range(x_start:x_end);
squares(idxS).y_range = y_buffer_range(y_start:y_end);
squares(idxS).index = idxS;
idxS = idxS + 1;
end
end
end
totalFrames = numFrames; % For single-frame power average
numPairs = (numFrames - 1); % For cross-temporal pairs
% For each ROI, we’ll compute:
% - Average single-frame power => (power_sum / totalFrames)
% - Coherence => crossSpec_sum / autoSpec_sums
% - Phase average => (phaseDiff_sum / numPairs)
numSquares = numel(squares);
roiPowerCell = cell(numSquares,1); % store wave–rose for power
roiCohCell = cell(numSquares,1); % store wave–rose for coherence
roiSpeedCell = cell(numSquares,1); % store wave–rose for speed (or phase)
for iROI = 1 : numSquares
xR = squares(iROI).x_range; % e.g. [x_start : x_end]
yR = squares(iROI).y_range; % e.g. [y_start : y_end]
%--------------------------
% (A) Single-frame average power
%--------------------------
localPow = power_sum(yR, xR, :, :); % subarray
sumPow = sum(sum(localPow, 1, 'omitnan'), 2, 'omitnan');
% sumPow => size [1,1,NSCALES,NANGLES], so squeeze:
sumPow = squeeze(sumPow); % => [NSCALES, NANGLES]
numPixROI = length(yR) * length(xR);
avgPower = sumPow / (totalFrames * numPixROI);
roiPowerCell{iROI} = avgPower; % store
%--------------------------
% (B) Cross-temporal coherence
%--------------------------
localCross = crossSpec_sum(yR, xR, :, :);
localB1 = B1_auto_sum(yR, xR, :, :);
localB2 = B2_auto_sum(yR, xR, :, :);
sumCross = squeeze(sum(sum(localCross, 1, 'omitnan'), 2, 'omitnan')); % => [NSCALES, NANGLES]
sumB1 = squeeze(sum(sum(localB1, 1, 'omitnan'), 2, 'omitnan'));
sumB2 = squeeze(sum(sum(localB2, 1, 'omitnan'), 2, 'omitnan'));
% Standard formula for coherence^2:
% gamma^2 = |SumCross|^2 / ( SumB1 * SumB2 )
gamma_sq = ( abs(sumCross).^2 ) ./ ( sumB1 .* sumB2 );
roiCohCell{iROI} = gamma_sq;
%--------------------------
% (C) Naive average phase difference => "speed wave–rose"
%--------------------------
localPhaseExp = phaseExp_sum(yR, xR, :, :);
% Sum over the spatial dimensions (rows and columns):
sumPhaseExp = squeeze(sum(sum(localPhaseExp, 1, 'omitnan'), 2, 'omitnan'));
numPixROI = length(yR) * length(xR);
avgPhase = angle(sumPhaseExp / (numPairs * numPixROI));
roiSpeedCell{iROI} = avgPhase;
end
%% 4B) Produce Overlaid Figures with Inset Wave–Roses
% 1) Choose a background image. For instance, the last preprocessed frame:
bgFrameIndex = numFrames; % last frame
thisFileName = fNames{bgFrameIndex};
thisFullPath = fullfile(dataDir, thisFileName);
data_bg = double(ncread(thisFullPath, varName));
data_bg_pre = preprocessFrame(data_bg, instrument, methodName, ...
thisFullPath, thisTime, ...
IR_threshold, IR_fillPercentile, ...
VIS_lowerPercentile, VIS_upperPercentile, ...
VIS_fillPercentile, clipMinHP, clipMaxHP, ...
lowPassFilterWidth_20, lowPassFilterWidth_50, lowPassFilterWidth_100, ...
Insolation_Correction,cumulativeIRmask); % do same steps as you do in the loop
if doWindow
switch lower(windowType)
case 'radial'
data_bg_pre = applyRadialWindow(data_bg_pre, radius_factor, decay_rate);
case 'rectangular'
data_bg_pre = applyRectangularWindow(data_bg_pre, radius_factor, decay_rate);
end
end
produceOverlayWaveRose('Power', roiPowerCell, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValuePower, data_bg_pre, singleOutDir, 'Global PowerWaveRose Overlay.png');
produceOverlayWaveRose('Coherence', roiCohCell, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueCoherence, data_bg_pre, singleOutDir, 'Global CoherenceWaveRose Overlay.png');
produceOverlayWaveRose('Phase', roiSpeedCell, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValuePhase, data_bg_pre, singleOutDir, 'Global PhaseWaveRose Overlay.png');
produceOverlayWaveRose('Speed', roiSpeedCell, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, 'Global SpeedWaveRose Overlay.png');
%% 4C) Final Correction of Large-Scale Speeds
% --- helpers to select limiter and tags ---------------------------------
corrfun_classic = @limitSpeedByScale;
corrfun_azimuthal = @limitSpeedByScale_Azimuthal;
% Return a function handle and a text suffix given a key
function [corrfun, tagSuffix] = pickLimiter(key, corrfun_classic, corrfun_azimuthal)
switch lower(key)
case 'classic', corrfun = corrfun_classic; tagSuffix = ''; % no suffix
case 'azimuthal', corrfun = corrfun_azimuthal; tagSuffix = ' Azimuthal'; % for titles/files
otherwise, error('Unknown correction key: %s', key);
end
end
%% 4C) Final Correction of Large-Scale Speeds (mode-aware)
% Prepare outputs we may fill depending on mode
roiSpeedCell_corrected = [];
roiSpeedCell_corrected_Azimuthal = [];
roiSpeedCell_active = []; % the one used for downstream
activeTagSuffix = ''; % affects filenames & titles
switch lower(correctionMode)
case 'classic'
[corrfun_sel, tagSuffix] = pickLimiter('classic', corrfun_classic, corrfun_azimuthal);
roiSpeedCell_corrected = corrfun_sel(roiSpeedCell, Scales, nyquistScales_post, upperCutoff_post, ...
beta, decayFactor, decaySharpness, matrixMode);
roiSpeedCell_active = roiSpeedCell_corrected;
activeTagSuffix = tagSuffix;
% One overlay only (classic)
produceOverlayWaveRose(['Speed Corrected' tagSuffix], roiSpeedCell_corrected, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, ['Global Corrected SpeedWaveRose Overlay' tagSuffix '.png']);
case 'azimuthal'
[corrfun_sel, tagSuffix] = pickLimiter('azimuthal', corrfun_classic, corrfun_azimuthal);
roiSpeedCell_corrected_Azimuthal = corrfun_sel(roiSpeedCell, Scales, nyquistScales_post, upperCutoff_post, ...
beta, decayFactor, decaySharpness, matrixMode);
roiSpeedCell_active = roiSpeedCell_corrected_Azimuthal;
activeTagSuffix = tagSuffix;
% One overlay only (azimuthal)
produceOverlayWaveRose(['Speed Corrected' tagSuffix], roiSpeedCell_active, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, ['Global Corrected SpeedWaveRose Overlay' tagSuffix '.png']);
case 'both'
% Produce both corrected products
roiSpeedCell_corrected = corrfun_classic(roiSpeedCell, Scales, nyquistScales_post, upperCutoff_post, ...
beta, decayFactor, decaySharpness, matrixMode);
roiSpeedCell_corrected_Azimuthal = corrfun_azimuthal(roiSpeedCell, Scales, nyquistScales_post, upperCutoff_post, ...
beta, decayFactor, decaySharpness, matrixMode);
produceOverlayWaveRose('Speed Corrected', roiSpeedCell_corrected, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, 'Global Corrected SpeedWaveRose Overlay.png');
produceOverlayWaveRose('Speed Corrected Azimuthal', roiSpeedCell_corrected_Azimuthal, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, 'Global Corrected Azimuthal SpeedWaveRose Overlay.png');
% Decide which one flows to downstream steps:
[corrfun_sel, activeTagSuffix] = pickLimiter(primaryCorrection, corrfun_classic, corrfun_azimuthal);
if strcmpi(primaryCorrection,'azimuthal')
roiSpeedCell_active = roiSpeedCell_corrected_Azimuthal;
else
roiSpeedCell_active = roiSpeedCell_corrected;
end
otherwise
error('Unknown correctionMode: %s', correctionMode);
end
%% 4D) ADVECTION CORRECTION ON ROI-BASED ROSES (mode-aware)
if doAdvectionEstimation
% First: un-advect the naive phase (same input as before)
[roiSpeedCell_unadv, roiResidCell, ~, ~] = ...
applyAdvectionCorrectionROI(roiSpeedCell, roiCohCell, ...
Scales, Angles, ...
scalesForAdvection, cohThreshold, ...
pixel_size_km, time_resolution);
switch lower(correctionMode)
case 'classic'
[corrfun_sel, tagSuffix] = pickLimiter('classic', corrfun_classic, corrfun_azimuthal);
roiSpeedCell_unadv_corr = corrfun_sel(roiSpeedCell_unadv, Scales, nyquistScales_post, upperCutoff_post, ...
beta, decayFactor, decaySharpness, matrixMode);
produceOverlayWaveRose(['Speed UnAdvected' tagSuffix], roiSpeedCell_unadv_corr, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, ['Global UnAdvected SpeedWaveRose Overlay' tagSuffix '.png']);
case 'azimuthal'
[corrfun_sel, tagSuffix] = pickLimiter('azimuthal', corrfun_classic, corrfun_azimuthal);
roiSpeedCell_unadv_corr = corrfun_sel(roiSpeedCell_unadv, Scales, nyquistScales_post, upperCutoff_post, ...
beta, decayFactor, decaySharpness, matrixMode);
produceOverlayWaveRose(['Speed UnAdvected' tagSuffix], roiSpeedCell_unadv_corr, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, ['Global UnAdvected SpeedWaveRose Overlay' tagSuffix '.png']);
case 'both'
% Make both overlays, then keep the primary for any later use
roi_unadv_classic = corrfun_classic(roiSpeedCell_unadv, Scales, nyquistScales_post, upperCutoff_post, ...
beta, decayFactor, decaySharpness, matrixMode);
roi_unadv_azimuthal = corrfun_azimuthal(roiSpeedCell_unadv, Scales, nyquistScales_post, upperCutoff_post, ...
beta, decayFactor, decaySharpness, matrixMode);
produceOverlayWaveRose('Speed UnAdvected', roi_unadv_classic, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, 'Global UnAdvected SpeedWaveRose Overlay.png');
produceOverlayWaveRose('Speed UnAdvected Azimuthal', roi_unadv_azimuthal, squares, num_squares_x, num_squares_y, ...
Scales, Angles, DisplayValueSpeed, data_bg_pre, singleOutDir, 'Global UnAdvected Azimuthal SpeedWaveRose Overlay.png');
% Promote the primary to a consistent name if you need it later:
if strcmpi(primaryCorrection,'azimuthal')
roiSpeedCell_unadv_corr = roi_unadv_azimuthal;
else
roiSpeedCell_unadv_corr = roi_unadv_classic;
end
end
end
%% 5) GLOBAL AVERAGE WAVE ROSES
% Aafter Section 3, we have the following accumulators:
% power_sum : sum over frames of |spec_full|^2, size [rowsF, colsF, NSCALES, NANGLES]
% crossSpec_sum : sum over consecutive-frame pairs of (B1 .* conj(B2))
% B1_auto_sum : sum over pairs of |B1|^2 (previous frame)
% B2_auto_sum : sum over pairs of |B2|^2 (current frame)
% phaseExp_sum : sum over pairs of exp(1i*phase_diff), for circular averaging
% Define total numbers:
totalFrames = numFrames; % for single-frame (power) sums
numPairs = numFrames - 1; % for cross-temporal quantities
numPixels = rowsF * colsF; % total pixels per frame
% ----- (A) Global Power Wave–Rose -----
% Average power over frames and spatial domain:
globalPower = squeeze( sum(sum(power_sum, 1, 'omitnan'), 2, 'omitnan') ) ...
/ (totalFrames * numPixels);
% Produce the global wave–rose plot:
produceAggregatedWaveRose('Power Global', globalPower, Scales, Angles, ...
singleOutDir, 'Global PowerWaveRose', saverose, DisplayValuePower);
% ----- (B) Global Coherence Wave–Rose -----
globalCross = squeeze( sum(sum(crossSpec_sum, 1, 'omitnan'), 2, 'omitnan') );
globalB1 = squeeze( sum(sum(B1_auto_sum, 1, 'omitnan'), 2, 'omitnan') );
globalB2 = squeeze( sum(sum(B2_auto_sum, 1, 'omitnan'), 2, 'omitnan') );
% Compute coherence (using standard formula: |S12|^2 / (S11*S22)):
globalCoherence = ( abs(globalCross).^2 ) ./ (globalB1 .* globalB2 );
produceAggregatedWaveRose('Coherence Global', globalCoherence, Scales, Angles, ...
singleOutDir, 'Global CoherenceWaveRose', saverose, DisplayValueCoherence);
% ----- (C) Global Speed (Phase) Wave–Rose -----
% For phase differences, we average the complex exponentials (for circular averaging)
globalPhaseExp = squeeze( sum(sum(phaseExp_sum, 1, 'omitnan'), 2, 'omitnan') );
% Average over the number of pairs and spatial domain:
globalAvgPhase = angle( globalPhaseExp / (numPairs * numPixels) );
produceAggregatedWaveRose('Speed Global', globalAvgPhase, Scales, Angles, ...
singleOutDir, 'Global SpeedWaveRose', saverose, DisplayValueSpeed);