-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLecture1.html
More file actions
1332 lines (1083 loc) · 56.5 KB
/
Copy pathLecture1.html
File metadata and controls
1332 lines (1083 loc) · 56.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="favicon.png" type="image/x-icon">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/default.min.css">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
<script>
MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']]
},
options: {
renderActions: {
addMenu: []
}
},
svg: {
fontCache: 'global',
scale: 1.0
}
};
document.addEventListener("DOMContentLoaded", () => {
const sidebar = document.querySelector('.sidebar');
const main = document.querySelector('.main-content');
const wrapper = document.createElement('div');
wrapper.className = 'layout';
sidebar.parentNode.insertBefore(wrapper, sidebar);
wrapper.appendChild(sidebar);
wrapper.appendChild(main);
});
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js" async></script>
</head>
<body>
<div class="sidebar">
<img src="Logo_NS-blackboard-Expand.png" alt="Sidebar Image">
<nav>
<ul class="nav-menu">
<li><a href="index.html">Welcome to NFYK22003U</a></li>
<ul class="sub-menu">
<li><a href="CourseInformation.html">Course Information</a></li>
</ul>
<li><a href="Welcome.html">Scope and Sequence</a></li>
<ul class="sub-menu">
<li><a href="CoursePrerequisitesExam.html">Prerequisites Exam</a></li>
<li><a href="IntroductiontoPythonProgramming.html">Introduction to Python Programming</a></li>
<li><a href="MathsSpeedrun.html">Maths Speedrun</a></li>
</ul>
<li>
<a href="Lecture1.html">Lecture 1 – Introduction and Transport Processes</a></li>
<ul class="sub-menu">
<li><a href="Project1.html">Project 1 – Oxygen Budget</a></li>
</ul>
<li><a href="Lecture2.html">Lecture 2 – The Dynamics of Rotating Planets</a></li>
<ul class="sub-menu">
<li><a href="Project2.html">Project 2 – The Sverdrup Relation</a></li>
</ul>
<li><a href="Lecture3.html">Lecture 3 – Origin of Carbon and Water on Earth</a></li>
<li><a href="Lecture4.html">Lecture 4 – The Gulfstream</a></li>
<ul class="sub-menu">
<li><a href="Project3.html">Project 3 – Western Boundary Currents</a></li>
</ul>
<li><a href="Lecture5.html">Lecture 5 – Carbon and Plankton</a></li>
<li><a href="Lecture6.html">Lecture 6 – Quasi-Geostrophy</a></li>
<li><a href="Lecture7.html">Lecture 7 – Theory of the Ventilated Thermocline</a></li>
<ul class="sub-menu">
<li><a href="Project4.html">Project 4 – Shadow Zone</a></li>
</ul>
<li><a href="Lecture8.html">Lecture 8 – Waves</a></li>
<li><a href="Lecture9.html">Lecture 9 – Atmospheric Thermodynamics</a></li>
<ul class="sub-menu">
<li><a href="Project5.html">Project 5 – Hadley Cell</a></li>
</ul>
<li><a href="Lecture10.html">Lecture 10 – Surface and Abyssal Circulation</a></li>
<ul class="sub-menu">
<li><a href="Project6.html">Project 6 – Overturning</a></li>
</ul>
<li><a href="Lecture11.html">Lecture 11 – Ocean Mixing and Overturning Circulation</a></li>
<li><a href="Lecture12.html">Lecture 12 – Stability of the Atlantic Meridional Overturning Circulation</a></li>
<ul class="sub-menu">
<li><a href="Project7.html">Project 7 – Oscillations</a></li>
<li><a href="TestExam.html">Test Exam</a></li>
</ul>
<li><a href="Lecture13.html">Lecture 13 – Applications of Machine Learning in CFD and GFD</a></li>
<ul class="sub-menu">
<li><a href="SailbyNightPhysics.html">Sail by Night Physics</a></li>
</ul>
<li><a href="Appendix.html">Appendix</a></li>
<li><a href="References.html">References</a></li>
</li>
</ul>
</nav>
</div>
<div class="main-content">
<!-- TOC goes here -->
<!--<div class="toc-sidebar" id="toc">-->
<!--<div class="toc-title">☰ Contents</div>-->
<!--<ul id="toc-list"></ul>-->
<!--</div>-->
<h1>Lecture 1 – Introduction and Transport Processes</h1>
<h2>Biological Carbon Pump</h2>
<ul>
<li>Process where \( \mathrm{CO_2} \) from the atmosphere is absorbed by surface ocean phytoplankton through photosynthesis and transferred to deeper ocean layers via sinking organic particles</li>
<li>The Biological Carbon Pump leads to an increase of \( \mathrm{DIC} \) in the ocean’s interior over the concentration that would result from only the solubility pump</li>
<li>It regulates atmospheric \( \mathrm{CO_2} \) levels and influences Earth’s climate over geological timescales</li>
</ul>
<div style="text-align: center;">
<img src="Figures/Lecture1_BiologicalCarbonPump1.png" alt="BiologicalCarbonPump1" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<img src="Figures/Lecture1_BiologicalCarbonPump2.png" alt="BiologicalCarbonPump2" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<div class="figure-caption">(Illustration by Charin Park, © Woods Hole Oceanographic Institution)</div>
</div>
<h2>The Solubility Pump</h2>
<ul>
<li>Physical process of solving \(\mathrm{CO_2}\) in ocean water</li>
<li>\(\mathrm{CO_2}\) and water react to form \(\mathrm{H_2CO_3}\) (carbonic acid)</li>
<li>Since \(\mathrm{H_2CO_3}\) is a weak acid and has two \(\mathrm{H^+}\), it can act as a buffer</li>
<li>90% of dissolved inorganic carbon (DIC) is bicarbonate \(\mathrm{HCO_3^-}\)</li>
</ul>
\(\begin{align}
CO_2 + H_2O &\rightarrow 2H + CO_3^{2-} \\
H + CO_3^{2-} &\rightarrow HCO_3^{-}
\end{align}\)
<h2>Turbulence</h2>
<img src="Figures/Lecture1_TurbulenceJet.png" alt="TurbulenceJet" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<div class="figure-caption">(The flow field in turbulent round free jets from birth to death. Credit: Ball et al. (2012))</div>
<h2>Reynolds-Averaged Navier-Stokes (RANS)</h2>
Reynolds averaging is quite easy to understand. It means decomposing a statistically observable quantity into an average part and a fluctuation part:
$$
f = \overline{f} + f'
$$
Since the flow is already unsteady at this point, we cannot guarantee that the value of the fluctuation is much smaller than the average part.
The Navier–Stokes equation for incompressible flow can be written as:
$$
\underbrace{\frac{\partial \vec{u}}{\partial t}}_{\text{Local acceleration}} + \underbrace{(\vec{u} \cdot \nabla) \vec{u}}_{\text{Advection}} = \underbrace{-\frac{1}{\rho} \nabla P}_{\text{Pressure force}} + \underbrace{g \vec{k}}_{\text{Gravity}} + \underbrace{\nu \nabla^2 \vec{u}}_{\text{Viscous diffusion}}
$$
$g \vec{k}$ with typically $
\vec{k} =
\begin{pmatrix}
0 \\
0 \\
1
\end{pmatrix}
$ defines gravity as a vector field acting downward (if you use $-g \vec{k}$, then $\vec{k}$ points upward)
For any field variable (velocity $\vec{u}$, pressure $P$, or scalar tracer $T$), we decompose it into a mean and a fluctuating part:
$$
\vec{u} = \bar{\vec{u}} + \vec{u}' \quad \text{and} \quad P = \bar{P} + P' \quad \text{and} \quad T = \bar{T} + T'
$$
Where:
<ul>
<li>$\bar{\vec{u}}$: time-averaged (mean) velocity</li>
<li>$\vec{u}'$: turbulent fluctuation (zero mean: $\overline{\vec{u}'} = 0$)</li>
<li>Similarly for $P$ and $T$</li>
</ul>
Apply thetime-average operator to the NS equation.
The nonlinear advection term becomes:
$$
\overline{(\vec{u} \cdot \nabla)\vec{u}} = (\bar{\vec{u}} \cdot \nabla)\bar{\vec{u}} + \nabla \cdot \overline{\vec{u}' \vec{u}'}
$$
This introduces a <span class="doubleUnderline">Reynolds stress tensor</span>:
$$
\overline{u_i' u_j'} \quad \Rightarrow \quad \text{new unknowns!}
$$
This term represents the averaged effect of turbulent fluctuations in fluid flow, where $u'_i$ and $u'_j$ are the velocity fluctuations in the $i$-th and $j$-th directions respectively.<br>
So the <span class="doubleUnderline">Reynolds-averaged Navier–Stokes (RANS)</span> equation becomes:
$$
\frac{\partial \bar{\vec{u}}}{\partial t} + (\bar{\vec{u}} \cdot \nabla)\bar{\vec{u}} = -\frac{1}{\rho} \nabla \bar{P} + g\vec{k} + \nu \nabla^2 \bar{\vec{u}} - \nabla \cdot \overline{\vec{u}' \vec{u}'}
$$
The term $-\nabla \cdot \overline{\vec{u}' \vec{u}'}$ is the turbulent momentum transport, and it leads directly to the turbulence closure problem.
<h2>The Tracer Equation</h2>
Take a scalar quantity like temperature $T$, salinity, or concentration $C$, governed by the advection-diffusion equation:
$$
\frac{\partial T}{\partial t} + \vec{u} \cdot \nabla T = k \nabla^2 T + S
$$
The $S$ in the equation above means source, it can be tracer such as heating H, DIC, etc.<br>
Apply Reynolds decomposition: $T = \bar{T} + T'$, $\vec{u} = \bar{\vec{u}} + \vec{u}'$, and average the equation:
$$
\overline{\frac{\partial T}{\partial t}} + \overline{(\vec{u} \cdot \nabla T)} = k \nabla^2 \bar{T} + \bar{S}
$$
That gives:
$$
\frac{\partial \bar{T}}{\partial t} + \bar{\vec{u}} \cdot \nabla \bar{T} + \nabla \cdot \overline{\vec{u}' T'} = k \nabla^2 \bar{T} + \bar{S}
$$
Substituting turbulent closure:
$$
\frac{\partial \bar{T}}{\partial t} + \bar{\vec{u}} \cdot \nabla \bar{T} = \left( k + k_{\text{turb}} \right) \nabla^2 \bar{T} + \bar{S}
$$
Or compactly:
$$
T_t = -\vec{u} \cdot \nabla T + (k + k_{\text{turb}}) \nabla^2 T + S
$$
Which is exactly your final boxed form:
$$
T_t = -\vec{u} \cdot \nabla T + k_{\text{turb}} \nabla^2 T + S
$$
In 3D Cartesian coordinates:
<ul>
<li>$T(x, y, z, t)$: scalar field (e.g. temperature)</li>
<li>$\vec{u} = (u, v, w)$: velocity components in $x, y, z$</li>
<li>$\nabla T = \left( \frac{\partial T}{\partial x}, \frac{\partial T}{\partial y}, \frac{\partial T}{\partial z} \right)$</li>
<li> $\nabla^2 T = \frac{\partial^2 T}{\partial x^2} + \frac{\partial^2 T}{\partial y^2} + \frac{\partial^2 T}{\partial z^2}$</li>
</ul>
$$
\frac{\partial T}{\partial t} + u \frac{\partial T}{\partial x} + v \frac{\partial T}{\partial y} + w \frac{\partial T}{\partial z} = k_{\text{turb}} \left( \frac{\partial^2 T}{\partial x^2} + \frac{\partial^2 T}{\partial y^2} + \frac{\partial^2 T}{\partial z^2} \right) + S
$$
\(\therefore\)
\(\boxed{T_t = - \mathbf{u} \cdot \nabla T + k \cdot \nabla^2 T + S(\text{source})}\) <br>
Tracer-Equation after Reynolds averaging: \(\boxed{T_t = - \mathbf{u} \cdot \nabla T + k_{turb} \cdot \nabla^2 T + S(\text{source})}\)<br>
\(k_{turb}\) = turbulent diffusivity (depends on size and strength of waves or eddies)
<img src="Figures/Lecture1_NablaTerms.png" alt="NablaTerms" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import imageio.v3 as iio
import os
# Parameters
nx, ny = 50, 50
dx, dy = 1.0, 1.0
dt = 0.01
k = 0.1
nt = 500
u = 1.0
d = 0.5
# Grid
x = np.linspace(0, (nx-1)*dx, nx)
y = np.linspace(0, (ny-1)*dy, ny)
X, Y = np.meshgrid(x, y, indexing='ij')
# Initial tracer field
T_initial = np.exp(-((X-25)**2 + (Y-25)**2)/50)
S = np.zeros((nx, ny))
S[20:30, 20:30] = 0.1
# Laplacian
def laplacian(T, dx, dy):
return (
(np.roll(T, -1, axis=0) - 2*T + np.roll(T, 1, axis=0)) / dx**2 +
(np.roll(T, -1, axis=1) - 2*T + np.roll(T, 1, axis=1)) / dy**2
)
# Boundary conditions
def apply_boundary_conditions(T):
T[0, :] = T[1, :]
T[-1, :] = T[-2, :]
T[:, 0] = T[:, 1]
T[:, -1] = T[:, -2]
return T
# Precompute frames
T_advect_list, T_diffuse_list, T_source_list, T_full_list = [], [], [], []
T_advect = T_initial.copy()
T_diffuse = T_initial.copy()
T_source = T_initial.copy()
T_full = T_initial.copy()
for n in tqdm(range(nt), desc="Precomputing frames"):
# Advection
dTdx = (np.roll(T_advect, -1, axis=0) - np.roll(T_advect, 1, axis=0)) / (2*dx)
dTdy = (np.roll(T_advect, -1, axis=1) - np.roll(T_advect, 1, axis=1)) / (2*dy)
advect = -(u * dTdx + d * dTdy)
T_advect += dt * advect
T_advect = apply_boundary_conditions(T_advect)
T_advect_list.append(T_advect.copy())
# Diffusion
diffuse = k * laplacian(T_diffuse, dx, dy)
T_diffuse += dt * diffuse
T_diffuse = apply_boundary_conditions(T_diffuse)
T_diffuse_list.append(T_diffuse.copy())
# Source
T_source += dt * S
T_source = apply_boundary_conditions(T_source)
T_source_list.append(T_source.copy())
# Full
dTdx_full = (np.roll(T_full, -1, axis=0) - np.roll(T_full, 1, axis=0)) / (2*dx)
dTdy_full = (np.roll(T_full, -1, axis=1) - np.roll(T_full, 1, axis=1)) / (2*dy)
advect_full = -(u * dTdx_full + d * dTdy_full)
diffuse_full = k * laplacian(T_full, dx, dy)
T_full += dt * (advect_full + diffuse_full + S)
T_full = apply_boundary_conditions(T_full)
T_full_list.append(T_full.copy())
# Save frames as images
if not os.path.exists('frames'):
os.makedirs('frames')
fig, axes = plt.subplots(2, 2, figsize=(14, 10), facecolor='none')
titles = ['Advection Only', 'Diffusion Only', 'Source Only', 'Full Model']
pcm_list = []
for ax, title in zip(axes.flat, titles):
pcm = ax.pcolormesh(X, Y, np.zeros_like(T_initial), shading='nearest', cmap='coolwarm', vmin=0, vmax=1)
ax.set_title(title, color='#d6ebff')
ax.set_xlabel('x', color='#d6ebff')
ax.set_ylabel('y', color='#d6ebff')
ax.set_facecolor('none')
ax.tick_params(colors='#d6ebff')
for spine in ax.spines.values():
spine.set_edgecolor('#d6ebff')
pcm_list.append(pcm)
fig.patch.set_alpha(0.0)
# Add colorbar
cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.7])
cbar = fig.colorbar(pcm_list[-1], cax=cbar_ax)
cbar.set_label('Tracer Concentration', color='#d6ebff')
cbar.ax.yaxis.set_tick_params(color='#d6ebff')
plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='#d6ebff')
filenames = []
for i in tqdm(range(nt), desc='Saving frames'):
fields = [T_advect_list[i], T_diffuse_list[i], T_source_list[i], T_full_list[i]]
for pcm, T in zip(pcm_list, fields):
pcm.set_array(T.ravel())
fname = f'frames/frame_{i:04d}.png'
plt.savefig(fname, dpi=100, transparent=True)
filenames.append(fname)
plt.close()
# Create GIF from saved frames
print('Creating GIF...')
frames = [iio.imread(fname) for fname in filenames]
iio.imwrite('Lecture1_TracerFieldEvolution.gif', frames, duration=1/30, loop=0) # 30 fps, infinite replay
# Clean up
for fname in filenames:
os.remove(fname)
os.rmdir('frames')
print("Saved as transparent tracer_evolution.gif!")</code></pre>
</div>
<img src="Figures/Lecture1_TracerFieldEvolution.gif" alt="TracerFieldEvolution" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
It should be noted that we can’t solve $\overline{\vec{u}' T'}$ directly — this is the turbulence closure problem.
So we use an <span class="doubleUnderline">eddy diffusivity model (Prandtl 1926)</span>:
$$
\overline{u'_i T'} \approx -k_t \frac{\partial \bar{T}}{\partial x_i}
$$
This is like <span class="doubleUnderline">Fick’s Law</span>, where turbulent transport is down the gradient.
<h2>Dissolved Inorganic carbonate</h2>
The total concentration of carbon in dissolved inorganic form in seawater, referred to as dissolved inorganic carbon (DIC), is defined as the sum of the concentrations of the three carbonate species:
$$
\text{DIC} = [\mathrm{CO}_2^*] + [\mathrm{HCO}_3^-] + [\mathrm{CO}_3^{2-}]
$$
Surface observations reveal comparable values of DIC, varying from less than 2000 $\mu\text{mol kg}^{-1}$ in the tropics to more than 2100 $\mu\text{mol kg}^{-1}$ in the high latitudes.
Most of the surface DIC is accounted for by $[\text{HCO}_3^-]$, followed by $[\text{CO}_3^{2-}]$, while $[\text{CO}_2^*]$ accounts for less than 1%.
The patterns of DIC and its carbon components are not identical over the globe: there is a general increase in DIC, $[\text{HCO}_3^-]$ and $[\text{CO}_2^*]$ with latitude, but an opposing decrease in $[\text{CO}_3^{2-}]$.
<h3>Bonus: Rubber Ducks Used as Tracers</h3>
<img src="Figures/Lecture1_RubberDuckCurrents.png" alt="RubberDuckCurrents" style="margin-top: 1.5em; max-width: 100%; display: block;">
We can model the ducks as ‘tracer particles’ in the ocean.
The term ‘tracer particles’ refers to small objects that move with a fluid without really changing how it behaves.
They are very common: examples include leaves on the surface of a river and, fortunately, rubber ducks in the ocean.
We can do simulations that try to track the amount of these particles in different parts of the ocean.<br>
Reference: <a href="https://visualpde.com/visual-stories/ducks.html">Ocean spills</a><br>
Any floating object can serve as a makeshift drift meter, as long as it is known where the object entered the ocean and where it was retrieved.
The path of the object can then be inferred, providing information about the movement of surface currents.
If the time of release and retrieval are known, the speed of currents can also be determined.
Oceanographers have long used drift bottles
(a floating “message in a bottle” or a radio-transmitting device set adrift in the ocean)
to track the movement of currents.
Many objects have inadvertently become drift meters when ships lose cargo at sea.
In January 1992, a shipping mishap turned into an unexpected scientific breakthrough when the cargo ship Ever Laurel lost a container carrying 29,000 plastic toys—mostly rubber ducks—into the Pacific Ocean.
<img src="Figures/Lecture1_HongKongRubberDuck.png" alt="HongKongRubberDuck" style="margin-top: 1.5em; max-width: 100%; display: block;">
<div class="figure-caption">(The rubber duck by Dutch artist Florentijn Hofman still standing in Hong Kong’s Victoria Harbour. Photo: Xinhua.)</div>
<h2>Autocorrelation</h2>
<p>Many climate data contain autocorrelation, we often can’t avoid it.</p>
<strong>Autocovariance Function (ACF)</strong>
<p>The autocovariance function \(\gamma(\tau)\) is the <a href="https://link.springer.com/referenceworkentry/10.1007/978-0-387-32833-1_85">covariance</a> of a time series with itself
at another time by a time lag (or lead) \(\tau\). For a time series \(x(t)\)
with \(t_1\) and \(t_N\) as the starting and end points of the time series, \(x'(t)\) means remove the mean → it's the anomaly at time \(t\), the ACF is defined as:
\[
\gamma(\tau) = \frac{1}{(t_N - \tau) - t_1} \sum_{t = t_1}^{t_N - \tau} x'(t) \cdot x'(t + \tau)
\]
At lag \(\tau = 1\), assuming \(t_1 = 0\), \(t_N = N\):
\[
\gamma(1) = \frac{1}{N - 1} \left( x'(0) \cdot x'(1) + x'(1) \cdot x'(2) + x'(2) \cdot x'(3) + \dots + x'(N - 1) \cdot x'(N) \right)
\]
At lag \(\tau = 2\):
\[
\gamma(2) = \frac{1}{N - 2} \left( x'(0) \cdot x'(2) + x'(1) \cdot x'(3) + x'(2) \cdot x'(4) + \dots + x'(N - 2) \cdot x'(N) \right)
\]
At lag \(\tau = N - 1\):
\[
\gamma(N - 1) = x'(0) \cdot x'(N - 1) + x'(1) \cdot x'(N)
\]
At lag \(\tau = 0\):
\[
\gamma(0) = \overline{x'^2} = \text{variance}
\]
[Pf] Using Mathematical Induction, <br>
Base Case \(\tau = 0\): \(\gamma(0) = \frac{1}{N} \sum_{t=0}^{N - 1} x'(t) \cdot x'(t) = \frac{1}{N} \sum_{t=0}^{N - 1} (x'(t))^2\)<br>
Assume the formula holds for arbitrary \(k\), where \(0 \leq k < N - 1\):
\(
\gamma(k) = \frac{1}{N - k} \sum_{t=0}^{N - k - 1} x'(t) \cdot x'(t + k)
\)<br>
\(\Rightarrow \gamma(k + 1) = \frac{1}{N - (k + 1)} \sum_{t = 0}^{N - (k + 1) - 1} x'(t) \cdot x'(t + k + 1)
= \frac{1}{N - k - 1} \sum_{t = 0}^{N - k - 2} x'(t) \cdot x'(t + k + 1)\)<br>
\(\Rightarrow \gamma(\tau) = \frac{1}{N - \tau} \sum_{t=0}^{N - \tau - 1} x'(t) \cdot x'(t + \tau)
\quad \forall\ \tau \in [0, N - 1]\)<br>
\(\because\) The total length is \(t_N - t_1 + 1\), \( t + \tau \leq t_N \Rightarrow t \leq t_N - \tau\)<br>
\(\therefore \boxed{\gamma(\tau) = \frac{1}{(t_N - \tau) - t_1} \sum_{t = t_1}^{t_N - \tau} x'(t) \cdot x'(t + \tau)}\)
</p>
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">def autocovariance(x, lag):
x = np.asarray(x)
x_mean = np.mean(x)
N = len(x)
return np.sum((x[:N-lag] - x_mean) * (x[lag:] - x_mean)) / (N - lag)</code></pre>
</div>
There is also the <code>np.correlate()</code> function that computes the cross-correlation of two 1-dimensional sequences.
It should be noticed that the definition of correlation above is not unique and sometimes correlation may be defined differently,
the <code>np.correlate()</code> function uses \(c(\tau) = \sum_{t = t_1}^{t_N - \tau} x(t + \tau) \cdot \bar{y}(t)
\) to compute the autocovariance and does not include the
\(
\frac{1}{(t_N - \tau) - t_1}
\) factor, so we have to make some adjustments to convert to autocorrelation.
<p>The autocorrelation \(\rho(\tau)\) is defined as the normalized autocovariance:\[ \rho(\tau) = \frac{\gamma(\tau)}{\gamma(0)} \]This gives the autocovariance at lag \(\tau\) divided by the variance of the time series, yielding a value between \(-1\) and \(1\).</p>
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">def autocorrelation(x, lag):
x = np.asarray(x)
x_mean = np.mean(x)
x_var = np.var(x)
N = len(x)
return np.sum((x[:N-lag] - x_mean) * (x[lag:] - x_mean)) / ((N - lag) * x_var)</code></pre>
</div>
<strong>Durbin-Watson Test</strong>
<p>The Durbin-Watson test statistic assesses the autocorrelation of residuals in a regression, it is defined as:
\[
DW = \frac{\sum_{t=2}^{T} (e_t - e_{t-1})^2}{\sum_{t=1}^{T} e_t^2}
\]The null hypothesis of the test is that there is no serial correlation in the residuals.The test statistic is approximately equal to \( 2 \cdot (1 - r) \), where \( r \) is the sample autocorrelation of the residuals.
For \( r = 0 \), there is no serial correlation, the test statistic equals 2.
This statistic will always be between 0 and 4
<ul>
<li>The closer to 0, the more evidence for positive serial correlation (residuals persist)</li>
<li>The closer to 4, the more evidence for negative serial correlation (residuals alternate)</li>
</ul>
The ideal value is exactly 2, which indicates independence of residuals. Durbin and Watson have established upper limit \(d_U\) and lower limit \(d_L\) for the significance level of which are appropriate to the hypothesis of zero first-order autocorrelation against the alternative hypothesis of positive first-order autocorrelation.
</p>
<img src="Figures/Lecture1_DWTest.png" alt="DWTest.png" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<h2>Anomaly Calculation</h2>
<p>An anomaly is the difference between an actual value and some long-term average value.
Anomalies can be computed by removing the mean
\[
x' = x - \bar{x}
\]
This isolates deviations from the mean and highlights variability around a baseline.
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">x = series - np.mean(series)</code></pre>
</div>
</p>
<strong>Example: Autocorrelation in El Niño-Southern Oscillation (ENSO) Data</strong>
<p>ENSO (El Niño-Southern Oscillation) is a periodic fluctuation (every 2–7 years) in wind and sea surface temperature over the tropical eastern Pacific Ocean. It affects the global climate and is a major driver of Earth's interannual climate variability, causing various climate anomalies.
Using the <a href="https://www.kaggle.com/datasets/shabanamir/enso-data">ENSO-related standardized monthly climate data (1950–2024)</a> available on Kaggle,
some examples of autocorrelation can be illustrated.</p>
<p>Take a quick look at the actual structure of <code>ENSO.csv</code> first</p>
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">import pandas as pd
df = pd.read_csv('ENSO.csv', header=None)
# Show shape and first few rows
print("Shape of the file:", df.shape)
print(df.head())</code></pre>
</div>
<pre style="font-family: 'Courier New', Courier, monospace; color: #aaccee; background: transparent; border: none; padding: 1em 0; margin: 0;">
Shape of the file: (883, 22)
0 1 2 3 4 \
0 Date Year Month Global Temperature Anomalies Nino 1+2 SST
1 1/1/1950 1950 JAN -0.2 NaN
2 2/1/1950 1950 FEB -0.26 NaN
3 3/1/1950 1950 MAR -0.08 NaN
4 4/1/1950 1950 APR -0.16 NaN
5 6 7 8 \
0 Nino 1+2 SST Anomalies Nino 3 SST Nino 3 SST Anomalies Nino 3.4 SST
1 NaN NaN NaN NaN
2 NaN NaN NaN NaN
3 NaN NaN NaN NaN
4 NaN NaN NaN NaN
9 ... 12 13 14 15 16 \
0 Nino 3.4 SST Anomalies ... TNI PNA OLR SOI Season (2-Month)
1 NaN ... 0.624 -3.65 NaN NaN DJ
2 NaN ... 0.445 -1.69 NaN NaN JF
3 NaN ... 0.382 -0.06 NaN NaN FM
4 NaN ... 0.311 -0.23 NaN NaN MA
17 18 19 20 21
0 MEI.v2 Season (3-Month) ONI Season (12-Month) ENSO Phase-Intensity
1 NaN DJF -1.5 1950-1951 ML
2 NaN JFM -1.3 1950-1951 ML
3 NaN FMA -1.2 1950-1951 ML
4 NaN MAM -1.2 1950-1951 ML
[5 rows x 22 columns]</pre>
<p>
The primary indicators for ENSO are ONI (Oceanic Niño Index) and MEI.v2.
ONI is the 3-month average SST anomaly in the Nino 3.4 region, it is the preferred indicator by NOAA.
To be considered an El Niño/La Niña event, the SST anomalies in the Nino 3.4 region must meet the following criteria and remain at or above/below these levels for a minimum of five consecutive months
<ul>
<li><strong>El Niño</strong> → anomalies at or above +0.5°C</li>
<li><strong>La Niña</strong> → anomalies at or below -0.5°C</li>
<li><strong>Neutral</strong> → anomalies between -0.5°C and +0.5°C</li>
</ul>
<p>The threshold is further divided into:
<ul>
<li><strong>Weak</strong> → 0.5°C to 0.9°C SST anomaly</li>
<li><strong>Moderate</strong> → 1.0°C to 1.4°C</li>
<li><strong>Strong</strong> → 1.5°C to 1.9°C</li>
<li><strong>Very Strong</strong> → ≥ 2.0°C</li>
</ul>
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.dates as mdates
import numpy as np
from matplotlib.colors import Normalize
from matplotlib.cm import get_cmap, ScalarMappable
# Load CSV with no header, and use row 0 as column names
df = pd.read_csv('ENSO.csv', header=0)
# Convert 'Date' column (column 0) to datetime
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df = df.dropna(subset=['Date']) # Drop rows where date couldn't be parsed
df.set_index('Date', inplace=True)
# Convert ONI column to numeric
df['ONI'] = pd.to_numeric(df['ONI'], errors='coerce')
df = df.dropna(subset=['ONI'])
# Extract time and ONI
dates = df.index
oni = df['ONI'].values
# Create colormap and normalization
cmap = get_cmap('coolwarm')
norm = Normalize(vmin=oni.min(), vmax=oni.max()) # Based on ONI value range, or other ways
# Plot setup
fig, ax = plt.subplots(figsize=(15, 5), dpi=300)
fig.patch.set_alpha(0.0)
ax.set_facecolor('none')
# Plot ONI with gradient line
for i in range(len(oni) - 1):
ax.plot(dates[i:i+2], oni[i:i+2],
color=cmap(norm(oni[i])), linewidth=2)
# Add color bar
sm = ScalarMappable(norm=norm, cmap=cmap)
sm.set_array([])
cbar = fig.colorbar(sm, ax=ax, pad=0.02)
cbar.set_label('ONI Value', color='#d6ebff')
cbar.ax.yaxis.set_tick_params(color='#d6ebff')
plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='#d6ebff')
# Horizontal ENSO thresholds
x = matplotlib.dates.date2num(dates)
levels = [
(2.0, 'very strong', 'red'),
(1.5, 'strong', 'red'),
(1.0, 'moderate', 'red'),
(0.5, 'weak', 'red'),
(-0.5, 'weak', 'blue'),
(-1.0, 'moderate', 'blue'),
(-1.5, 'strong', 'blue'),
]
for level, label, color in levels:
ax.axhline(y=level, color=color, linestyle=':', linewidth=1)
ax.text(x[-1], level, f' {label}', color=color, va='center')
# Custom legend
line_red = matplotlib.lines.Line2D([0], [0], label='El Niño (ONI > 0.5)', color='red')
line_blue = matplotlib.lines.Line2D([0], [0], label='La Niña (ONI < -0.5)', color='blue')
legend = ax.legend(handles=[line_red, line_blue])
# Style legend text
for text in legend.get_texts():
text.set_color('#d6ebff')
# Axes labels and title
ax.set_xlabel("Years", color="#d6ebff")
ax.set_ylabel("ONI", color="#d6ebff")
ax.set_title("ENSO and ONI Relation", fontsize=14, color="#d6ebff")
# Axis ticks and spines
ax.tick_params(colors="#d6ebff")
for label in ax.get_xticklabels():
label.set_color('#d6ebff')
for label in ax.get_yticklabels():
label.set_color('#d6ebff')
for spine in ax.spines.values():
spine.set_color("#d6ebff")
# Grid
ax.grid(True, linestyle='--', linewidth=0.5, color='#3c5c78', alpha=0.5)
plt.tight_layout()
plt.show()</code></pre>
</div>
<img src="Figures/Lecture1_ENSOandONIRelation.png" alt="ENSOandONIRelation.png" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<p>Loop through all numeric variables in <code>ENSO.csv</code>, apply seasonal averaging and detrend each with a linear fit, compute the residual autocorrelation, and rank the variables by their Durbin-Watson statistic.</p>
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">import numpy as np
import pandas as pd
from statsmodels.stats.stattools import durbin_watson
from scipy import stats
# Load dataset
df = pd.read_csv('ENSO.csv')
# Filter numeric variables only
numeric_cols = df.select_dtypes(include='number').columns
results = []
for var in numeric_cols:
series = df[var].dropna().values
if len(series) < 120: # skip very short or incomplete variables
continue
series = series[:(len(series) // 3) * 3] # trim to full seasons
seasonal = np.mean(series.reshape(-1, 3), axis=1)
time = np.arange(len(seasonal))
# Trend and residuals
trend = np.polyval(np.polyfit(time, seasonal, 1), time)
residuals = seasonal - trend
# Durbin-Watson test on residuals
dw = durbin_watson(residuals)
results.append((var, dw))
# Sort by closeness to DW = 2 (least autocorrelated)
results_sorted_by_distance = sorted(results, key=lambda x: abs(x[1] - 2))
# Sort by actual DW value (to show most autocorrelated: smallest DWs)
results_sorted_by_value = sorted(results, key=lambda x: x[1])
# Show least autocorrelated
print("\nTop 5 least autocorrelated (residuals):")
for name, dw in results_sorted_by_distance[:5]:
print(f"{name:30s} DW: {dw:.3f}")
# Show most autocorrelated
print("\nTop 5 most autocorrelated (residuals):")
for name, dw in results_sorted_by_distance[-5:][::-1]:
print(f"{name:30s} DW: {dw:.3f}")</code></pre>
</div>
<pre style="font-family: 'Courier New', Courier, monospace; color: #aaccee; background: transparent; border: none; padding: 1em 0; margin: 0;">
Top 5 least autocorrelated (residuals):
PNA DW: 1.678
Nino 1+2 SST DW: 1.668
Year DW: 2.386
Nino 3 SST DW: 1.209
Nino 3.4 SST DW: 0.813
Top 5 most autocorrelated (residuals):
Nino 4 SST Anomalies DW: 0.349
TNI DW: 0.354
ONI DW: 0.369
MEI.v2 DW: 0.405
Nino 3.4 SST Anomalies DW: 0.425</pre>
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from statsmodels.stats.stattools import durbin_watson
# --- Load dataset and scan numeric variables ---
df = pd.read_csv('ENSO.csv')
numeric_cols = df.select_dtypes(include='number').columns
dw_results = []
# --- Compute DW statistics for all variables ---
for var in numeric_cols:
series = df[var].dropna().values
if len(series) < 120:
continue
series = series[:(len(series) // 3) * 3]
seasonal = np.mean(series.reshape(-1, 3), axis=1)
time = np.arange(len(seasonal))
trend = np.polyval(np.polyfit(time, seasonal, 1), time)
residuals = seasonal - trend
dw = durbin_watson(residuals)
dw_results.append((var, seasonal, time, trend, residuals, dw))
# --- Sort by DW distance from 2 ---
sorted_by_dw = sorted(dw_results, key=lambda x: abs(x[5] - 2))
least_autocorr = sorted_by_dw[:3]
most_autocorr = sorted_by_dw[-3:]
# --- Plotting grid for each group ---
def plot_var(axs, row, label, seasonal, time, trend, residuals):
lags = np.arange(len(seasonal)) - len(seasonal) // 2
# 1. Time Series
axs[row, 0].plot(time, seasonal, '#6d9a26', linewidth=2, label=label)
axs[row, 0].plot(time, trend, '#ffe1ec', linewidth=1.5)
axs[row, 0].set_title(f"{label} Time Series")
axs[row, 0].set_ylabel("Value")
axs[row, 0].grid(True)
# 2. Full Autocorrelation
corr = np.correlate(
seasonal - seasonal.mean(),
(seasonal - seasonal.mean()) / (len(seasonal) * np.var(seasonal)),
mode='same'
)
axs[row, 1].plot(lags, corr, '#6d9a26', linewidth=2)
axs[row, 1].set_title("Full Autocorr")
axs[row, 1].set_xlim(-80, 80)
axs[row, 1].set_ylim(-0.4, 1)
axs[row, 1].grid(True)
# 3. Residual Autocorrelation (Zoomed Positive)
resid_corr = np.correlate(
residuals / np.std(residuals),
residuals / (np.std(residuals) * len(residuals)),
mode='same'
)
half = len(seasonal) // 2
axs[row, 2].plot(lags[half:], corr[half:], '#6d9a26', linewidth=2, label='Original')
axs[row, 2].plot(lags[half:], resid_corr[half:], '#ffe1ec', linewidth=2, label='Residuals')
axs[row, 2].set_title("Residual Autocorr")
axs[row, 2].set_xlim(0, 80)
axs[row, 2].set_ylim(-0.4, 1)
axs[row, 2].grid(True)
axs[row, 2].legend()
# --- Plot all in a 3x3 grid for least and most autocorrelated variables ---
fig, axs = plt.subplots(6, 3, figsize=(18, 20))
fig.suptitle("Comparison of Least and Most Autocorrelated Variables", fontsize=16)
for i, (name, seasonal, time, trend, resids, dw) in enumerate(least_autocorr):
plot_var(axs, i, f"{name} (DW={dw:.2f})", seasonal, time, trend, resids)
for i, (name, seasonal, time, trend, resids, dw) in enumerate(most_autocorr):
plot_var(axs, i + 3, f"{name} (DW={dw:.2f})", seasonal, time, trend, resids)
# Axis labels
for ax in axs[:, 0]:
ax.set_xlabel("Time (Season Index)")
for ax in axs[:, 1]:
ax.set_xlabel("Lag")
for ax in axs[:, 2]:
ax.set_xlabel("Lag")
plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()</code></pre>
</div>
<img src="Figures/Lecture1_Autocorrelation.png" alt="Autocorrelation.png" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<h2>Noise</h2>
This is how the spectrum is supposed to look like in paleoclimate studies :-)
<img src="Figures/Lecture1_Spectrum.png" alt="Spectrum" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<div class="figure-caption">(Patch-work spectral estimate using instrumental and proxy records of surface temperature variability, and insolation at \(65^\circ\,N\).
Credit: Huybers, P., Curry, W. Links between annual, Milankovitch and continuum temperature variability. <i>Nature 441</i>, 329–332 (2006).)</div>
The term <strong><span class="doubleUnderline">Fast Fourier Transform (FFT)</span></strong>, used for plotting this kind of spectrum, describes a general class of computationally efficient algorithms for calculating the Discrete Fourier Transform (DFT) and its inverse (IDFT) for sequences of any length.<br>
<ul>
<li>A direct computation of the DFT requires $O(N^2)$ operations for a sequence of length $N$.
For example, if $N = 1024$, then $N^2 \approx 10^6$.</li>
<li>FFT reduces this cost dramatically to $O(N \log N)$.
For $N = 1024$, $N \log N \approx 3000$</li>
</ul>
The main idea behind any FFT algorithm is to look for repetitive patterns in the calculation of DFT/IDFT and store results of calculations that can be repeatedly reused later to reduce the total amount of calculations needed. In this sense, FFT trades computational (or time) complexity against storage complexity.
FFT is a widely available numerical routine and takes advantage of redundancies in the calculation and speed up the process.<br> <br>
The figure uses the log-log scale that allows us to see detail at both large and small values.<br>
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">series1_amoc = df1['AMOC_40N'].dropna()
series2_amoc = df2['AMOC_40N'].dropna()
# FFT-based spectrum function (frequency domain)
def compute_manual_spectrum(series, n=None):
if n is None:
n = len(series)
series = series[:n]
I = np.abs(np.fft.fft(series))**2 / n
P = (4 / n) * I[:n // 2]
f = np.arange(n // 2) / n
return f[1:], P[1:] # skip zero frequency
# Compute FFT spectra using full series
f1_amoc, p1_amoc = compute_manual_spectrum(series1_amoc)
f2_amoc, p2_amoc = compute_manual_spectrum(series2_amoc)
plt.figure(figsize=(8, 6), dpi = 300)
plt.loglog(f1_amoc, p1_amoc, label='CESM AMOC')
plt.loglog(f2_amoc, p2_amoc, label='Guido AMOC', color='red')
plt.xlabel("Frequency (log scale)")
plt.ylabel("Power (log scale)")
plt.title("Comparison of AMOC Spectra")
plt.legend()
plt.grid(True, which='both', linestyle='--', color = '#d6ebff')
plt.tight_layout()
plt.show()</code></pre>
</div>
<img src="Figures/Lecture1_RedBlueSpectrum.png" alt="RedBlueSpectrum.png" style="margin-top: 1.5em; border: 1px solid #3c5c78; border-radius: 6px; max-width: 100%; display: block;">
<br>
There are several other methods to chose from depending on the characteristics of your data.
<div style="font-family: 'Courier New', Courier, monospace; background-color: #001a33; color: #aaccee; padding: 16px; ">
<table style="width: 100%; border-collapse: collapse; background-color: #001a33; color: #aaccee; border: 1px solid #3c5c78;">
<thead>
<tr style="border-bottom: 2px solid #3c5c78;">
<th style="padding: 10px; border: 1px solid #3c5c78;">Method</th>
<th style="padding: 10px; border: 1px solid #3c5c78;">Math Operation</th>
<th style="padding: 10px; border: 1px solid #3c5c78;">Good for</th>
<th style="padding: 10px; border: 1px solid #3c5c78;">Bad for</th>
</tr>
</thead>
<tbody>
<tr>
<td style="padding: 8px; border: 1px solid #3c5c78;"><strong>Log</strong></td>
<td style="padding: 8px; border: 1px solid #3c5c78;">ln(x)<br>log<sub>10</sub>(x)</td>
<td style="padding: 8px; border: 1px solid #3c5c78;">
Right skewed data<br>
log<sub>10</sub>(x) is especially good at handling higher order powers of 10 (e.g., 1000, 100000)
</td>
<td style="padding: 8px; border: 1px solid #3c5c78;">
Zero values<br>
Negative values
</td>
</tr>
<tr>
<td style="padding: 8px; border: 1px solid #3c5c78;"><strong>Square root</strong></td>
<td style="padding: 8px; border: 1px solid #3c5c78;">x<sup>1/2</sup></td>
<td style="padding: 8px; border: 1px solid #3c5c78;">Right skewed data</td>
<td style="padding: 8px; border: 1px solid #3c5c78;">Negative values</td>
</tr>
<tr>
<td style="padding: 8px; border: 1px solid #3c5c78;"><strong>Square</strong></td>
<td style="padding: 8px; border: 1px solid #3c5c78;">x²</td>
<td style="padding: 8px; border: 1px solid #3c5c78;">Left skewed data</td>
<td style="padding: 8px; border: 1px solid #3c5c78;">Negative values</td>
</tr>
<tr>
<td style="padding: 8px; border: 1px solid #3c5c78;"><strong>Cube root</strong></td>
<td style="padding: 8px; border: 1px solid #3c5c78;">x<sup>1/3</sup></td>
<td style="padding: 8px; border: 1px solid #3c5c78;">
Right skewed data<br>
Negative values
</td>
<td style="padding: 8px; border: 1px solid #3c5c78;">
Not as effective at normalizing as log transform
</td>
</tr>
<tr>
<td style="padding: 8px; border: 1px solid #3c5c78;"><strong>Reciprocal</strong></td>
<td style="padding: 8px; border: 1px solid #3c5c78;">1/x</td>
<td style="padding: 8px; border: 1px solid #3c5c78;">
Making small values bigger and big values smaller
</td>
<td style="padding: 8px; border: 1px solid #3c5c78;">
Zero values<br>
Negative values
</td>
</tr>
</tbody>
</table>
</div>
<br>
<strong>Red Noise Model</strong>
<p>A red noise time series is defined as an autoregressive process where each value depends on the previous value and a white noise term:</p> <p>\[x(t) = a \cdot x(t - \Delta t) + b \cdot \epsilon(t)\]</p> <div class="code-block"> <button class="copy-btn" onclick="copyToClipboard(this)">Copy</button> <pre><code class="language-python">x[t] = a * x[t - dt] + b * epsilon[t]</code></pre> </div>
<strong>Lag-1 Autocorrelation</strong>
<p>Measure the linear correlation between adjacent time steps, indicating memory in the signal.
Multiply both sides of the red noise equation by \(x(t - \Delta t)\) and take the time average to get:</p> <p>\[\rho(\Delta t) = a\]</p> <div class="code-block"> <button class="copy-btn" onclick="copyToClipboard(this)">Copy</button> <pre><code class="language-python">rho_lag1 = a</code></pre> </div>
It is also possible to use the <code>np.corrcoef</code> that computes the Pearson correlation coefficient matrix between one or more datasets:
<div class="code-block">
<button class="copy-btn" onclick="copyToClipboard(this)">Copy</button>
<pre><code class="language-python">rho_lag1 = np.corrcoef(x[:-1], x[1:])[0, 1]</code></pre>
</div>
<p>\(
x(t) = a \cdot x(t - \Delta t) + b \cdot \epsilon(t)
\)<br>
\(\Rightarrow
x(t + \Delta t) = a \cdot x(t) + b \cdot \epsilon(t + \Delta t)
\) ,
\(
x(t + 2\Delta t) = a \cdot x(t - \Delta t) + b \cdot \epsilon(t + 2\Delta t)
\)<br>
\(\Rightarrow