-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathadvec.qmd
More file actions
1760 lines (1535 loc) · 61.9 KB
/
advec.qmd
File metadata and controls
1760 lines (1535 loc) · 61.9 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
Wave (Chapter @sec-ch-wave) and diffusion (Chapter @sec-ch-diffu)
equations are solved reliably by finite difference methods. As soon as
we add a first-order derivative in space, representing *advective*
transport (also known as *convective* transport), the numerics gets
more complicated and intuitively attractive methods no longer work
well. We shall show how and why such methods fail and provide
remedies. The present chapter builds on basic knowledge about finite
difference methods for diffusion and wave equations, including the
analysis by Fourier components, truncation error analysis (Appendix
@sec-ch-trunc), and compact difference notation.
:::{.callout-note title="Remark on terminology"}
It is common to refer to movement of a fluid as convection, while advection
is the transport of some material dissolved or suspended in the fluid.
We shall mostly choose the word advection here, but both terms are
in heavy use, and for mass transport of a substance the PDE has an
advection term, while the similar term for the heat equation is a
convection term.
:::
Much more comprehensive discussion of dispersion analysis for
advection problems can be found in the book by Duran [@Duran_2010].
This is a an excellent resource for further studies on the topic of
advection PDEs, with emphasis on generalizations to real geophysical
problems. The book by Fletcher [@FletcherI_2013] also has a good
overview of methods for advection and convection problems.
## 1D linear advection equations with constant velocity {#sec-advec-1D}
We consider the pure advection model
$$
\frac{\partial u}{\partial t} + v\frac{\partial u}{\partial x} = 0,\quad
x\in (0,L),\ t\in (0,T],
$$ {#eq-advec-1D-pde1}
$$
u(x,0) = I(x), \quad x\in (0,L),
$$ {#eq-advec-1D-pde1-I}
$$
u(0,t) = U_0, \quad t\in (0,T].
$$ {#eq-advec-1D-pde1-u}
In (@eq-advec-1D-pde1-u), $v$ is a given parameter, typically reflecting
the transport velocity of a quantity $u$ with a flow.
There is only one boundary condition (@eq-advec-1D-pde1-I) since
the spatial derivative is only first order in the PDE (@eq-advec-1D-pde1-u).
The information at $x=0$ and the initial condition get
transported in the positive $x$ direction
if $v>0$ through the domain.
It is easiest to find the solution of (@eq-advec-1D-pde1-u) if we remove the
boundary condition and consider a process on the
infinite domain $(-\infty, \infty)$. The solution is simply
$$
u(x,t) = I(x-vt)\tp
$$ {#eq-advec-1D-pde1-sol}
This is also the solution we expect locally in a finite domain before boundary
conditions have reflected or modified the wave.
A particular feature of the solution (@eq-advec-1D-pde1-sol) is that
$$
u(x_i, t_{n+1}) = u(x_{i-1}, t_n),
$$ {#eq-advec-1D-pde1-uprop1}
if $x_i=i\Delta x$ and $t_n=n\Delta t$ are points in a uniform mesh.
We see this relation from
\begin{align}
u(i\Delta x, (n+1)\Delta t) &= I(i\Delta x - v(n+1)\Delta t) \nonumber \\
&= I((i-1)\Delta x - vn\Delta t - v\Delta t + \Delta x) \nonumber \\
&= I((i-1)\Delta x - vn\Delta t) \nonumber \\
&= u((i-1)\Delta x, n\Delta t), \nonumber
\end{align}
provided $v = \Delta x/\Delta t$. So, whenever we see a scheme that
collapses to
$$
u^{n+1}**i = u**{i-1}^n,
$$ {#eq-advec-1D-pde1-uprop2}
for the PDE in question, we have in fact a scheme that reproduces the
analytical solution, and many of the schemes to be presented possess
this nice property!
Finally, we add that a discussion of appropriate boundary conditions
for the advection PDE in multiple dimensions is a challenging topic beyond
the scope of this text.
## Simplest scheme: forward in time, centered in space
### Method {#sec-advec-1D-FTCS}
A first attempt to solve a PDE like (@eq-advec-1D-pde1-u) will normally
be to look for a time-discretization scheme that is explicit so we avoid
solving systems of linear equations. In space, we anticipate that
centered differences are most accurate and therefore best. These
two arguments lead us to a Forward Euler scheme in time and
centered differences in space:
$$
[D_t^+ u + vD_{2x} u = 0]^n_i
$$
Written out, we see that this expression implies that
$$
u^{n+1} = u^n - \half C (u^n_{i+1}-u_{i-1}^n),
$$
with $C$ as the Courant number
$$
C = \frac{v\Delta t}{\Delta x}\tp
$$
### Implementation
A solver function for our scheme goes as follows.
```python
import numpy as np
def solver_FECS(I, U0, v, L, dt, C, T, user_action=None):
Nt = int(round(T / float(dt)))
t = np.linspace(0, Nt * dt, Nt + 1) # Mesh points in time
dx = v * dt / C
Nx = int(round(L / dx))
x = np.linspace(0, L, Nx + 1) # Mesh points in space
dx = x[1] - x[0]
dt = t[1] - t[0]
C = v * dt / dx
u = np.zeros(Nx + 1)
u_n = np.zeros(Nx + 1)
for i in range(0, Nx + 1):
u_n[i] = I(x[i])
if user_action is not None:
user_action(u_n, x, t, 0)
for n in range(0, Nt):
for i in range(1, Nx):
u[i] = u_n[i] - 0.5 * C * (u_n[i + 1] - u_n[i - 1])
u[0] = U0
if user_action is not None:
user_action(u, x, t, n + 1)
u_n, u = u, u_n
def solver(I, U0, v, L, dt, C, T, user_action=None, scheme="FE", periodic_bc=True):
Nt = int(round(T / float(dt)))
t = np.linspace(0, Nt * dt, Nt + 1) # Mesh points in time
dx = v * dt / C
Nx = int(round(L / dx))
x = np.linspace(0, L, Nx + 1) # Mesh points in space
dx = x[1] - x[0]
dt = t[1] - t[0]
C = v * dt / dx
print("dt=%g, dx=%g, Nx=%d, C=%g" % (dt, dx, Nx, C))
u = np.zeros(Nx + 1)
u_n = np.zeros(Nx + 1)
u_nm1 = np.zeros(Nx + 1)
integral = np.zeros(Nt + 1)
for i in range(0, Nx + 1):
u_n[i] = I(x[i])
u[0] = U0
integral[0] = dx * (0.5 * u_n[0] + 0.5 * u_n[Nx] + np.sum(u_n[1:-1]))
if user_action is not None:
user_action(u_n, x, t, 0)
for n in range(0, Nt):
if scheme == "FE":
if periodic_bc:
i = 0
u[i] = u_n[i] - 0.5 * C * (u_n[i + 1] - u_n[Nx])
u[Nx] = u[0]
for i in range(1, Nx):
u[i] = u_n[i] - 0.5 * C * (u_n[i + 1] - u_n[i - 1])
elif scheme == "LF":
if n == 0:
if periodic_bc:
i = 0
u_n[i] = u_n[Nx]
for i in range(1, Nx + 1):
u[i] = u_n[i] - C * (u_n[i] - u_n[i - 1])
else:
if periodic_bc:
i = 0
u[i] = u_nm1[i] - C * (u_n[i + 1] - u_n[Nx - 1])
for i in range(1, Nx):
u[i] = u_nm1[i] - C * (u_n[i + 1] - u_n[i - 1])
if periodic_bc:
u[Nx] = u[0]
elif scheme == "UP":
if periodic_bc:
u_n[0] = u_n[Nx]
for i in range(1, Nx + 1):
u[i] = u_n[i] - C * (u_n[i] - u_n[i - 1])
elif scheme == "LW":
if periodic_bc:
i = 0
u[i] = (
u_n[i]
- 0.5 * C * (u_n[i + 1] - u_n[Nx - 1])
+ 0.5 * C * (u_n[i + 1] - 2 * u_n[i] + u_n[Nx - 1])
)
for i in range(1, Nx):
u[i] = (
u_n[i]
- 0.5 * C * (u_n[i + 1] - u_n[i - 1])
+ 0.5 * C * (u_n[i + 1] - 2 * u_n[i] + u_n[i - 1])
)
if periodic_bc:
u[Nx] = u[0]
else:
raise ValueError('scheme="%s" not implemented' % scheme)
if not periodic_bc:
u[0] = U0
integral[n + 1] = dx * (0.5 * u[0] + 0.5 * u[Nx] + np.sum(u[1:-1]))
if user_action is not None:
user_action(u, x, t, n + 1)
u_nm1, u_n, u = u_n, u, u_nm1
print("I:", integral[n + 1])
return integral
def run_FECS(case):
"""Special function for the FECS case."""
if case == "gaussian":
def I(x):
return np.exp(-0.5 * ((x - L / 10) / sigma) ** 2)
elif case == "cosinehat":
def I(x):
return np.cos(np.pi * 5 / L * (x - L / 10)) if x < L / 5 else 0
L = 1.0
sigma = 0.02
legends = []
def plot(u, x, t, n):
"""Animate and plot every m steps in the same figure."""
plt.figure(1)
if n == 0:
lines = plot(x, u)
else:
lines[0].set_ydata(u)
plt.draw()
plt.figure(2)
m = 40
if n % m != 0:
return
print(
"t=%g, n=%d, u in [%g, %g] w/%d points" % (t[n], n, u.min(), u.max(), x.size)
)
if np.abs(u).max() > 3: # Instability?
return
plt.plot(x, u)
legends.append("t=%g" % t[n])
plt.ion()
U0 = 0
dt = 0.001
C = 1
T = 1
solver(I=I, U0=U0, v=1.0, L=L, dt=dt, C=C, T=T, user_action=plot)
plt.legend(legends, loc="lower left")
plt.savefig("tmp.png")
plt.savefig("tmp.pdf")
plt.axis([0, L, -0.75, 1.1])
plt.show()
def run(scheme="UP", case="gaussian", C=1, dt=0.01):
"""General admin routine for explicit and implicit solvers."""
if case == "gaussian":
def I(x):
return np.exp(-0.5 * ((x - L / 10) / sigma) ** 2)
elif case == "cosinehat":
def I(x):
return np.cos(np.pi * 5 / L * (x - L / 10)) if 0 < x < L / 5 else 0
L = 1.0
sigma = 0.02
global lines # needs to be saved between calls to plot
def plot(u, x, t, n):
"""Plot t=0 and t=0.6 in the same figure."""
plt.figure(1)
global lines
if n == 0:
lines = plt.plot(x, u)
plt.axis([x[0], x[-1], -0.5, 1.5])
plt.xlabel("x")
plt.ylabel("u")
plt.axes().set_aspect(0.15)
plt.savefig("tmp_%04d.png" % n)
plt.savefig("tmp_%04d.pdf" % n)
else:
lines[0].set_ydata(u)
plt.axis([x[0], x[-1], -0.5, 1.5])
plt.title("C=%g, dt=%g, dx=%g" % (C, t[1] - t[0], x[1] - x[0]))
plt.legend(["t=%.3f" % t[n]])
plt.xlabel("x")
plt.ylabel("u")
plt.draw()
plt.savefig("tmp_%04d.png" % n)
plt.figure(2)
eps = 1e-14
if abs(t[n] - 0.6) > eps and abs(t[n] - 0) > eps:
return
print(
"t=%g, n=%d, u in [%g, %g] w/%d points" % (t[n], n, u.min(), u.max(), x.size)
)
if np.abs(u).max() > 3: # Instability?
return
plt.plot(x, u)
plt.draw()
if n > 0:
y = [I(x_ - v * t[n]) for x_ in x]
plt.plot(x, y, "k--")
if abs(t[n] - 0.6) < eps:
filename = ("tmp_%s_dt%s_C%s" % (scheme, t[1] - t[0], C)).replace(".", "")
np.savez(filename, x=x, u=u, u_e=y)
plt.ion()
U0 = 0
T = 0.7
v = 1
codecs = dict(flv="flv", mp4="libx264", webm="libvpx", ogg="libtheora")
import glob
import os
for name in glob.glob("tmp_*.png"):
os.remove(name)
for ext in codecs:
name = "movie.%s" % ext
if os.path.isfile(name):
os.remove(name)
if scheme == "CN":
integral = solver_theta(I, v, L, dt, C, T, user_action=plot, FE=False)
elif scheme == "BE":
integral = solver_theta(I, v, L, dt, C, T, theta=1, user_action=plot)
else:
integral = solver(
I=I, U0=U0, v=v, L=L, dt=dt, C=C, T=T, scheme=scheme, user_action=plot
)
plt.figure(2)
plt.axis([0, L, -0.5, 1.1])
plt.xlabel("$x$")
plt.ylabel("$u$")
plt.axes().set_aspect(0.5) # no effect
plt.savefig("tmp1.png")
plt.savefig("tmp1.pdf")
plt.show()
for codec in codecs:
cmd = "ffmpeg -i tmp_%%04d.png -r 25 -vcodec %s movie.%s" % (codecs[codec], codec)
os.system(cmd)
print("Integral of u:", integral.max(), integral.min())
def solver_theta(I, v, L, dt, C, T, theta=0.5, user_action=None, FE=False):
"""
Full solver for the model problem using the theta-rule
difference approximation in time (no restriction on F,
i.e., the time step when theta >= 0.5).
Vectorized implementation and sparse (tridiagonal)
coefficient matrix.
"""
import time
t0 = time.perf_counter() # for measuring the CPU time
Nt = int(round(T / float(dt)))
t = np.linspace(0, Nt * dt, Nt + 1) # Mesh points in time
dx = v * dt / C
Nx = int(round(L / dx))
x = np.linspace(0, L, Nx + 1) # Mesh points in space
dx = x[1] - x[0]
dt = t[1] - t[0]
C = v * dt / dx
print("dt=%g, dx=%g, Nx=%d, C=%g" % (dt, dx, Nx, C))
u = np.zeros(Nx + 1)
u_n = np.zeros(Nx + 1)
u_nm1 = np.zeros(Nx + 1)
integral = np.zeros(Nt + 1)
for i in range(0, Nx + 1):
u_n[i] = I(x[i])
integral[0] = dx * (0.5 * u_n[0] + 0.5 * u_n[Nx] + np.sum(u_n[1:-1]))
if user_action is not None:
user_action(u_n, x, t, 0)
diagonal = np.zeros(Nx + 1)
lower = np.zeros(Nx)
upper = np.zeros(Nx)
b = np.zeros(Nx + 1)
diagonal[:] = 1
lower[:] = -0.5 * theta * C
upper[:] = 0.5 * theta * C
if FE:
diagonal[:] += 4.0 / 6
lower[:] += 1.0 / 6
upper[:] += 1.0 / 6
upper[0] = 0
lower[-1] = 0
diags = [0, -1, 1]
import scipy.sparse
import scipy.sparse.linalg
A = scipy.sparse.diags(
diagonals=[diagonal, lower, upper],
offsets=[0, -1, 1],
shape=(Nx + 1, Nx + 1),
format="csr",
)
for n in range(0, Nt):
b[1:-1] = u_n[1:-1] + 0.5 * (1 - theta) * C * (u_n[:-2] - u_n[2:])
if FE:
b[1:-1] += 1.0 / 6 * u_n[:-2] + 1.0 / 6 * u_n[:-2] + 4.0 / 6 * u_n[1:-1]
b[0] = u_n[Nx]
b[-1] = u_n[0] # boundary conditions
b[0] = 0
b[-1] = 0 # boundary conditions
u[:] = scipy.sparse.linalg.spsolve(A, b)
if user_action is not None:
user_action(u, x, t, n + 1)
integral[n + 1] = dx * (0.5 * u[0] + 0.5 * u[Nx] + np.sum(u[1:-1]))
u_n, u = u, u_n
t1 = time.perf_counter()
return integral
if __name__ == "__main__":
run(scheme="LW", case="gaussian", C=1, dt=0.01)
```
### Test cases
The typical solution $u$ has the shape of $I$ and is transported at
velocity $v$ to the right (if $v>0$). Let us consider two different
initial conditions, one smooth (Gaussian pulse) and one non-smooth
(half-truncated cosine pulse):
$$
u(x,0) = Ae^{-\half\left(\frac{x-L/10}{\sigma}\right)^2},
$$
$$
u(x,0) = A\cos\left(\frac{5\pi}{L}\left( x - \frac{L}{10}\right)\right),\quad
x < \frac{L}{5} \hbox{ else } 0\tp
$$ {#eq-advec-1D-case_gaussian}
The parameter $A$ is the maximum value of the initial condition.
Before doing numerical simulations, we scale the PDE
problem and introduce $\bar x = x/L$ and $\bar t= vt/L$,
which gives
$$
\frac{\partial\bar u}{\partial \bar t} +
\frac{\partial\bar u}{\partial\bar x} = 0\tp
$$
The unknown $u$ is scaled by the maximum value of the initial condition:
$\bar u = u/\max |I(x)|$ such that $|\bar u(\bar x, 0)|\in [0,1]$.
The scaled problem is solved by setting $v=1$, $L=1$, and $A=1$.
From now on we drop the bars.
To run our test cases and plot the solution, we make the function
```python
def run_FECS(case):
"""Special function for the FECS case."""
if case == "gaussian":
def I(x):
return np.exp(-0.5 * ((x - L / 10) / sigma) ** 2)
elif case == "cosinehat":
def I(x):
return np.cos(np.pi * 5 / L * (x - L / 10)) if x < L / 5 else 0
L = 1.0
sigma = 0.02
legends = []
def plot(u, x, t, n):
"""Animate and plot every m steps in the same figure."""
plt.figure(1)
if n == 0:
lines = plot(x, u)
else:
lines[0].set_ydata(u)
plt.draw()
plt.figure(2)
m = 40
if n % m != 0:
return
print(
"t=%g, n=%d, u in [%g, %g] w/%d points" % (t[n], n, u.min(), u.max(), x.size)
)
if np.abs(u).max() > 3: # Instability?
return
plt.plot(x, u)
legends.append("t=%g" % t[n])
plt.ion()
U0 = 0
dt = 0.001
C = 1
T = 1
solver(I=I, U0=U0, v=1.0, L=L, dt=dt, C=C, T=T, user_action=plot)
plt.legend(legends, loc="lower left")
plt.savefig("tmp.png")
plt.savefig("tmp.pdf")
plt.axis([0, L, -0.75, 1.1])
plt.show()
def run(scheme="UP", case="gaussian", C=1, dt=0.01):
"""General admin routine for explicit and implicit solvers."""
if case == "gaussian":
def I(x):
return np.exp(-0.5 * ((x - L / 10) / sigma) ** 2)
elif case == "cosinehat":
def I(x):
return np.cos(np.pi * 5 / L * (x - L / 10)) if 0 < x < L / 5 else 0
L = 1.0
sigma = 0.02
global lines # needs to be saved between calls to plot
def plot(u, x, t, n):
"""Plot t=0 and t=0.6 in the same figure."""
plt.figure(1)
global lines
if n == 0:
lines = plt.plot(x, u)
plt.axis([x[0], x[-1], -0.5, 1.5])
plt.xlabel("x")
plt.ylabel("u")
plt.axes().set_aspect(0.15)
plt.savefig("tmp_%04d.png" % n)
plt.savefig("tmp_%04d.pdf" % n)
else:
lines[0].set_ydata(u)
plt.axis([x[0], x[-1], -0.5, 1.5])
plt.title("C=%g, dt=%g, dx=%g" % (C, t[1] - t[0], x[1] - x[0]))
plt.legend(["t=%.3f" % t[n]])
plt.xlabel("x")
plt.ylabel("u")
plt.draw()
plt.savefig("tmp_%04d.png" % n)
plt.figure(2)
eps = 1e-14
if abs(t[n] - 0.6) > eps and abs(t[n] - 0) > eps:
return
print(
"t=%g, n=%d, u in [%g, %g] w/%d points" % (t[n], n, u.min(), u.max(), x.size)
)
if np.abs(u).max() > 3: # Instability?
return
plt.plot(x, u)
plt.draw()
if n > 0:
y = [I(x_ - v * t[n]) for x_ in x]
plt.plot(x, y, "k--")
if abs(t[n] - 0.6) < eps:
filename = ("tmp_%s_dt%s_C%s" % (scheme, t[1] - t[0], C)).replace(".", "")
np.savez(filename, x=x, u=u, u_e=y)
plt.ion()
U0 = 0
T = 0.7
v = 1
codecs = dict(flv="flv", mp4="libx264", webm="libvpx", ogg="libtheora")
import glob
import os
for name in glob.glob("tmp_*.png"):
os.remove(name)
for ext in codecs:
name = "movie.%s" % ext
if os.path.isfile(name):
os.remove(name)
if scheme == "CN":
integral = solver_theta(I, v, L, dt, C, T, user_action=plot, FE=False)
elif scheme == "BE":
integral = solver_theta(I, v, L, dt, C, T, theta=1, user_action=plot)
else:
integral = solver(
I=I, U0=U0, v=v, L=L, dt=dt, C=C, T=T, scheme=scheme, user_action=plot
)
plt.figure(2)
plt.axis([0, L, -0.5, 1.1])
plt.xlabel("$x$")
plt.ylabel("$u$")
plt.axes().set_aspect(0.5) # no effect
plt.savefig("tmp1.png")
plt.savefig("tmp1.pdf")
plt.show()
for codec in codecs:
cmd = "ffmpeg -i tmp_%%04d.png -r 25 -vcodec %s movie.%s" % (codecs[codec], codec)
os.system(cmd)
print("Integral of u:", integral.max(), integral.min())
def solver_theta(I, v, L, dt, C, T, theta=0.5, user_action=None, FE=False):
"""
Full solver for the model problem using the theta-rule
difference approximation in time (no restriction on F,
i.e., the time step when theta >= 0.5).
Vectorized implementation and sparse (tridiagonal)
coefficient matrix.
"""
import time
t0 = time.perf_counter() # for measuring the CPU time
Nt = int(round(T / float(dt)))
t = np.linspace(0, Nt * dt, Nt + 1) # Mesh points in time
dx = v * dt / C
Nx = int(round(L / dx))
x = np.linspace(0, L, Nx + 1) # Mesh points in space
dx = x[1] - x[0]
dt = t[1] - t[0]
C = v * dt / dx
print("dt=%g, dx=%g, Nx=%d, C=%g" % (dt, dx, Nx, C))
u = np.zeros(Nx + 1)
u_n = np.zeros(Nx + 1)
u_nm1 = np.zeros(Nx + 1)
integral = np.zeros(Nt + 1)
for i in range(0, Nx + 1):
u_n[i] = I(x[i])
integral[0] = dx * (0.5 * u_n[0] + 0.5 * u_n[Nx] + np.sum(u_n[1:-1]))
if user_action is not None:
user_action(u_n, x, t, 0)
diagonal = np.zeros(Nx + 1)
lower = np.zeros(Nx)
upper = np.zeros(Nx)
b = np.zeros(Nx + 1)
diagonal[:] = 1
lower[:] = -0.5 * theta * C
upper[:] = 0.5 * theta * C
if FE:
diagonal[:] += 4.0 / 6
lower[:] += 1.0 / 6
upper[:] += 1.0 / 6
upper[0] = 0
lower[-1] = 0
diags = [0, -1, 1]
import scipy.sparse
import scipy.sparse.linalg
A = scipy.sparse.diags(
diagonals=[diagonal, lower, upper],
offsets=[0, -1, 1],
shape=(Nx + 1, Nx + 1),
format="csr",
)
for n in range(0, Nt):
b[1:-1] = u_n[1:-1] + 0.5 * (1 - theta) * C * (u_n[:-2] - u_n[2:])
if FE:
b[1:-1] += 1.0 / 6 * u_n[:-2] + 1.0 / 6 * u_n[:-2] + 4.0 / 6 * u_n[1:-1]
b[0] = u_n[Nx]
b[-1] = u_n[0] # boundary conditions
b[0] = 0
b[-1] = 0 # boundary conditions
u[:] = scipy.sparse.linalg.spsolve(A, b)
if user_action is not None:
user_action(u, x, t, n + 1)
integral[n + 1] = dx * (0.5 * u[0] + 0.5 * u[Nx] + np.sum(u[1:-1]))
u_n, u = u, u_n
t1 = time.perf_counter()
return integral
if __name__ == "__main__":
run(scheme="LW", case="gaussian", C=1, dt=0.01)
```
### Bug?
Running either of the test cases, the plot becomes a mess, and
the printout of $u$ values in the `plot` function reveals that
$u$ grows very quickly. We may reduce $\Delta t$ and make it
very small, yet the solution just grows.
Such behavior points to a bug in the code.
However, choosing a coarse mesh and performing one time step by
hand calculations produces the same numbers as the code, so
the implementation seems to be correct.
The hypothesis is therefore that the solution is unstable.
## Analysis of the scheme {#sec-advec-1D-FTCS-anal}
It is easy to show that a typical Fourier component
$$
u(x,t)= B\sin (k(x-ct))
$$
is a solution of our PDE for any spatial wave length $\lambda = 2\pi /k$
and any amplitude $B$. (Since the PDE to be investigated by this method
is homogeneous and linear, $B$ will always cancel out, so we tend to skip
this amplitude, but keep it here in the beginning for completeness.)
A general solution may be viewed as a collection of long and
short waves with different amplitudes. Algebraically, the work
simplifies if we introduce the complex Fourier component
$$
u(x,t)=\Aex e^{ikx},
$$
with
$$
\Aex=Be^{-ikv\Delta t} = Be^{-iCk\Delta x}\tp
$$
Note that $|\Aex| \leq 1$.
It turns out that many schemes also allow a Fourier wave component as
solution, and we can use the numerically computed values of $\Aex$
(denoted $A$) to learn about the
quality of the scheme. Hence, to analyze the difference scheme we have just
implemented, we look at how it treats the Fourier component
$$
u_q^n = A^n e^{ikq\Delta x}\tp
$$
Inserting the numerical component in the scheme,
$$
[D_t^+ A e^{ikq\Delta x} + v D_{2x}A e^{ikq\Delta x} = 0]^n_q,
$$
and making use of (@eq-form-exp-fd1c-center)
results in
$$
[e^{ikq\Delta x} (\frac{A-1}{\Delta t} + v\frac{1}{\Delta x}i\sin (k\Delta x)) = 0]^n_q,
$$
which implies
$$
A = 1 - iC\sin(k\Delta x)\tp
$$
The numerical solution features the formula $A^n$. To find out whether
$A^n$ means growth in time, we rewrite $A$ in polar form: $A=A_re^{i\phi}$,
for real numbers $A_r$ and $\phi$,
since we then have $A^n = A_r^ne^{i\phi n}$. The magnitude of $A^n$ is
$A_r^n$. In our case, $A_r = (1 + C^2\sin^2(kx))^{1/2} > 1$, so
$A_r^n$ will increase in time, whereas the
exact solution will not. Regardless of $\Delta t$, we get unstable
numerical solutions.
## Leapfrog in time, centered differences in space
### Method {#sec-advec-1D-leapfrog}
Another explicit scheme is to do a "leapfrog" jump over $2\Delta t$ in
time and combine it with central differences in space:
$$
[D_{2t} u + vD_{2x} u = 0]_i^n,
$$
which results in the updating formula
$$
u^{n+1}_i = u^{n-1}**i - C(u**{i+1}^n-u_{i-1}^n)\tp
$$
A special scheme is needed to compute $u^1$, but we leave that problem for
now. Anyway, this special scheme can be found in
[`advec1D.py`](https://github.com/devitocodes/devito_book/tree/main/src/advec/advec1D.py).
### Implementation
We now need to work with three time levels and must modify our solver a bit:
```python
Nt = int(round(T/float(dt)))
t = np.linspace(0, Nt*dt, Nt+1) # Mesh points in time
...
u = np.zeros(Nx+1)
u_1 = np.zeros(Nx+1)
u_2 = np.zeros(Nx+1)
...
for n in range(0, Nt):
if scheme == 'FE':
for i in range(1, Nx):
u[i] = u_1[i] - 0.5*C*(u_1[i+1] - u_1[i-1])
elif scheme == 'LF':
if n == 0:
for i in range(1, Nx):
...
else:
for i in range(1, Nx+1):
u[i] = u_2[i] - C*(u_1[i] - u_1[i-1])
u_2, u_1, u = u_1, u, u_2
```
### Running a test case
Let us try a coarse mesh such that the smooth Gaussian initial condition
is represented by 1 at mesh node 1 and 0 at all other nodes. This
triangular initial condition should then be advected to the right.
Choosing scaled variables as $\Delta t=0.1$, $T=1$, and $C=1$ gives
the plot in Figure @fig-advec-1D-case-gaussian-fig-LFCS, which
is in fact identical to the exact solution (!).
{#fig-advec-1D-case-gaussian-fig-LFCS width="500px"}
### Running more test cases
We can run two types of initial conditions for $C=0.8$: one very
smooth with a Gaussian function (Figure @fig-advec-1D-LF-fig1-C08) and
one with a discontinuity in the first derivative (Figure
@fig-advec-1D-LF-fig2-C08). Unless we have a very fine mesh, as in
the left plots in the figures, we get small ripples behind the main
wave, and this main wave has the amplitude reduced.
{#fig-advec-1D-LF-fig1-C08 width="100%"}
{#fig-advec-1D-LF-fig2-C08 width="100%"}
### Analysis
We can perform a Fourier analysis again. Inserting the numerical
Fourier component in the Leapfrog scheme, we get
$$
A^2 - i2C\sin(k\Delta x) A - 1 = 0,
$$
and
$$
A = -iC\sin(k\Delta x) \pm \sqrt{1-C^2\sin^2(k\Delta x)}\tp
$$
Rewriting to polar form, $A=A_re^{i\phi}$, we see that $A_r=1$, so the
numerical component is neither increasing nor decreasing in time, which is
exactly what we want. However, for $C>1$, the square root can become
complex valued, so stability is obtained only as long as $C\leq 1$.
:::{.callout-warning title="Stability"}
For all the working schemes to be presented in this chapter, we
get the stability condition $C\leq 1$:
$$
\Delta t \leq \frac{\Delta x}{v}\tp
$$
This is called the CFL condition and applies almost always to successful
schemes for advection problems. Of course, one can use Crank-Nicolson or
Backward Euler schemes for increased and even unconditional
stability (no $\Delta t$ restrictions), but these have other
less desired damping problems.
:::
We introduce $p=k\Delta x$. The amplification factor now reads
$$
A = -iC\sin p \pm \sqrt{1-C^2\sin^2 p},
$$
and is to be compared to the exact amplification factor
$$
\Aex = e^{-ikv\Delta t} = e^{-ikC\Delta x} = e^{-iCp}\tp
$$
Section @sec-advec-1D-disprel compares numerical amplification factors
of many schemes with the exact expression.
## Upwind differences in space {#sec-advec-1D-FTUP}
Since the PDE reflects transport of information along with a flow in
positive $x$ direction, when $v>0$, it could be natural to go (what is called)
upstream and not
downstream in the spatial derivative to collect information about the
change of the function. That is, we approximate
$$
\frac{\partial u}{\partial x}(x_i,t_n)\approx [D^-_x u]^n_i = \frac{u^n_{i} - u^n_{i-1}}{\Delta x}\tp
$$
This is called an *upwind difference* (the corresponding difference in the
time direction would be called a backward difference, and we could use that
name in space too, but *upwind* is the common name for a difference against
the flow in advection problems). This spatial approximation does magic
compared to
the scheme we had with Forward Euler in time and centered difference in space.
With an upwind difference,
$$
[D^+_t u + vD^-_x u = 0]^n_i,
$$ {#eq-advec-1D-upwind}
written out as
$$
u^{n+1}_i = u^n_i - C(u^{n}**{i}-u^{n}**{i-1}),
$$
gives a generally popular and robust scheme that is stable if $C\leq 1$.
As with the Leapfrog scheme, it becomes exact if $C=1$, exactly as shown in
Figure @fig-advec-1D-case-gaussian-fig-LFCS. This is easy to see since
$C=1$ gives the property (@eq-advec-1D-pde1-uprop2).
However, any $C<1$ gives a significant reduction in the amplitude of the
solution, which is a purely numerical effect, see Figures
@fig-advec-1D-UP-fig1-C08 and @fig-advec-1D-UP-fig2-C08.
Experiments show, however, that
reducing $\Delta t$ or $\Delta x$, while keeping $C$ reduces the
error.
{#fig-advec-1D-UP-fig1-C08 width="100%"}
{#fig-advec-1D-UP-fig2-C08 width="100%"}
The amplification factor can be computed using the
formula (@eq-form-exp-fd1-bw),
$$
\frac{A - 1}{\Delta t} + \frac{v}{\Delta x}(1 - e^{-ik\Delta x}) = 0,
$$
which means
$$
A = 1 - C(1 - \cos(p) - i\sin(p))\tp
$$
For $C<1$ there is, unfortunately,
non-physical damping of discrete Fourier components, giving rise to reduced
amplitude of $u^n_i$ as in Figures @fig-advec-1D-UP-fig1-C08
and @fig-advec-1D-UP-fig2-C08. The damping seen
in these figures is quite severe. Stability requires $C\leq 1$.
:::{.callout-note title="Interpretation of upwind difference as artificial diffusion"}
One can interpret the upwind difference as extra, artificial diffusion
in the equation. Solving
$$
\frac{\partial u}{\partial t} + v\frac{\partial u}{\partial x}
= \nu\frac{\partial^2 u}{\partial x^2},
$$
by a forward difference in time and centered differences in space,
$$
D^+**t u + vD**{2x} u = \nu D_xD_x u]^n_i,
$$
actually gives the upwind scheme (@eq-advec-1D-upwind) if
$\nu = v\Delta x/2$. That is, solving the PDE $u_t + vu_x=0$
by centered differences in space and forward difference in time is
unsuccessful, but by adding some artificial diffusion $\nu u_{xx}$,
the method becomes stable:
$$
\frac{\partial u}{\partial t} + v
\frac{\partial u}{\partial x} = \left(\dfc + \frac{v\Delta x}{2}\right)
\frac{\partial^2 u}{\partial x^2}\tp
$$
:::
## Periodic boundary conditions {#sec-advec-1D-periodic-BC}
So far, we have given the value on the left boundary, $u_0^n$, and used
the scheme to propagate the solution signal through the domain.
Often, we want to follow such signals for long time series, and periodic
boundary conditions are then relevant since they enable a signal that
leaves the right boundary to immediately enter the left boundary and propagate
through the domain again.
The periodic boundary condition is
$$
u(0,t) = u(L,t),\quad u_0^n = u_{N_x}^n\tp
$$
It means that we in the first equation, involving $u_0^n$, insert $u_{N_x}^n$,
and that we in the last equation, involving $u^{n+1}_{N_x}$ insert $u^{n+1}_0$.
Normally, we can do this in the simple way that `u_1[0]` is updated as
`u_1[Nx]` at the beginning of a new time level.
In some schemes we may need $u^{n}_{N_x+1}$ and $u^{n}_{-1}$. Periodicity
then means that these values are equal to $u^n_1$ and $u^n_{N_x-1}$,
respectively. For the upwind scheme, it is sufficient to set
`u_1[0]=u_1[Nx]` at a new time level before computing `u[1]`. This ensures
that `u[1]` becomes right and at the next time level `u[0]` at the current
time level is correctly updated.
For the Leapfrog scheme we must update `u[0]` and `u[Nx]` using the scheme:
```python
if periodic_bc:
i = 0
u[i] = u_2[i] - C*(u_1[i+1] - u_1[Nx-1])
for i in range(1, Nx):
u[i] = u_2[i] - C*(u_1[i+1] - u_1[i-1])
if periodic_bc:
u[Nx] = u[0]
```
## Implementation
### Test condition
Analytically, we can show that the integral in space under the $u(x,t)$ curve
is constant:
\begin{align*}
\int_0^L \left(\frac{\partial u}{\partial t} + v\frac{\partial u}{\partial x}
\right) dx &= 0\\
\frac{\partial }{\partial t} \int_0^L udx &=
- \int_0^L v\frac{\partial u}{\partial x}dx\\
\frac{\partial u}{\partial t} \int_0^L udx &=
[v u]_0^L =0
\end{align*}
as long as $u(0)=u(L)=0$. We can therefore use the property
$$
\int_0^L u(x,t)dx = \hbox{const}
$$
as a partial verification during the simulation. Now, any numerical method
with $C\neq 1$ will deviate from the constant, expected value, so