Repository navigation
Expand file tree
/
Copy pathLecture04Explicit.jl
More file actions
1932 lines (1542 loc) · 62.3 KB
/
Copy pathLecture04Explicit.jl
File metadata and controls
1932 lines (1542 loc) · 62.3 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
### A Pluto.jl notebook ###
# v0.20.4
using Markdown
using InteractiveUtils
# ╔═╡ 254b7584-7a7e-43f8-a17d-d94b121b1416
begin
using Plots
using LinearAlgebra
end
# ╔═╡ 46ca86db-be88-4dc5-aa03-7b60d1e54f6a
md"""
# Simple ODEs
Ideally, a numerical method for solving ordinary differential equations
$$\dot x(t)=f(t,x(t)), \quad x(t_0)=x_0,$$
should be able to solve exactly those equations often posed in high-school textbooks.
Examples include:
### Zero
$$1) \quad \dot x(t)=0, \quad x(t_{0}) = x_0\\$$
### Constant
$$2) \quad \dot x(t) = \lambda, \quad x(t_0)=x_0$$
### Linear
$$3) \quad \dot x(t) =\lambda x(t), \quad x(t_0)=x_0$$
"""
# ╔═╡ 7f187f3f-0afd-401e-a384-d0ab1551e7e1
md"""
## Their solutions
If you are taking this course, it is good to know that their solutions are:
### Zero
$$1) \quad x(t)=x_0\\$$
### Constant
$$2) \quad x(t) = x_{0}+\lambda(t-t_0)$$
### Linear
$$3) \quad x(t) =x_0\exp(\lambda(t-t_0))$$
"""
# ╔═╡ 770f43c0-2768-40a1-bb8a-384601a0d0a8
md"""
## Explicit Euler attempt
Utilizing perhaps the simplest scheme
$$x_{k+1}=x_{k}+hf(x_{k}),$$
with fixed step-size $h$, we find the following:
### Zero
$$x_{k+1}=x_{k}=\dots=x_0$$
**Exact!**
### Constant
$$x_{k+1}=x_{k}+h\lambda =(x_{k-1}+h\lambda)+h\lambda=\dots=x_{0}+(k+1)h\lambda$$
**Exact!**
### Linear
$$x_{k+1}=x_{k}+h\lambda x_{k}=(1+h\lambda)x_{k}=\dots=(1+h\lambda)^{k+1}x_{0}$$
**Approximation!**
From the definition of the exponential function,
$$\exp(x)=\lim_{n\to\infty}\left(1 + \frac{x}{n}\right)^{n}$$
we find that an explicit Euler scheme approximates the term
$$\exp(\lambda(t_{k+1}-t_0))=\exp((k+1)h\lambda)=\lim_{n\to\infty}\left(1+\frac{(k+1)h\lambda}{n}\right)^{n},$$
by halting the limit sequence at $n=k+1$.
"""
# ╔═╡ f8863d59-0f81-4833-9d2f-f3a021739d26
md"""
# Accuracy
Although we as humans are error-prone, we are able to derive and calculate the analytical solution to all of the above ODEs. However, as we have now seen theoretically, a numerical method may be limited in producing accurate answers.
"""
# ╔═╡ 40c76196-753c-48f4-a310-564df338dbd5
md"""
## Truncation error
Sometimes also referred to as discretization error. An error inherent to the numerical method due to mathematical approximations.
### Example
The explicit Euler scheme can be derived by approximating the integral solution to an ODE using a simple left-hand Riemann quadrature:
$$x(t_{0}+h)=x(t_{0})+\int_{t_{0}}^{t_{0}+h}f(t,x(t))\,\mathrm{d}t\approx x(t_{0})+hf(t_0,x(t_0))$$
### Definitions
For numerical methods for ODEs we discern two error definitions:
#### Local truncation error
The local truncation error $\tau_{k}$ at step $k$ is defined as the error made by a single step of a numerical integration scheme
$$\tau_{k+1}=x_{k+1}-x_{k}(t_{k+1}),$$
where $x_k(t_{k+1})$ is defined as the analytical solution of the ODE
$$\dot x_k(t)=f(t,x_k(t)), \quad x_k(t_{k})=x_k$$
**Drawing?**
#### Global truncation error
The global truncation error $e_{k}$ at step $k$ is defined as the difference between the numerical and analytical solutions
$$e_{k+1}=x_{k+1}-x(t_{k+1})$$
**Drawing?**
#### Method order
If the local truncation error is of **asymptotic** order
$$\tau_{k+1}=O(h^{p+1}), \quad h\to0$$
for a given exponent $p$, then the numerical scheme is said to have **method order** $p$.
**What about the order of the global truncation error?** Requires some math..
"""
# ╔═╡ e78d20c8-7ef6-4fb7-855a-6db631f99f9b
md"""
### Analyzing local truncation error
Let us consider the local truncation error of the explicit Euler scheme. With help from a first-order Taylor expansion around the previous time point, we see that for $h \to 0$
$$\begin{align*}
\tau_{k+1}&=x_{k+1}-x_{k}(t_{k+1})\\
&=x_k+hf(t_k,x_{k})-\left[x_k(t_k)+hf(t_{k,}x_{k}(t_{k}))+O(h^2)\right]\\
&=x_k+hf(t_{k},x_{k})-\left[x_k+hf(t_{k},x_{k})+O(h^2)\right]\\
&=O(h^{2})
\end{align*}$$
Therefore, we find that the explicit Euler scheme has **method order** $p=1$.
**In this case, halving the step-size will quarter the error!**
"""
# ╔═╡ 51564216-03f1-4f7f-98da-5e6e47d10a77
md"""
## Round-off error
If we were to implement the explicit Euler scheme on a computer, we might expect that it should still find exact solutions to both the zero and constant ODEs above. However, this can not be expected!
Another, sometimes forgotten, source of error is numerical round-off. An unfortunate limitation when working with finite precision floating points numbers.
Problems occur due since computer representations of the reals are limited by
1) Magnitude ~ $[10^{-308},10^{308}]$
2) Precision ~ $10^{-16}$
**For IEEE 754 double-precision binary floating-point format**
### Beware
#### Catastrophic cancellation
When subtracting two nearly equal numbers, the result will suffer a loss in number of significant digits!
#### Cumulative round-off
Cumulation of many small round-off errors may be significant!
"""
# ╔═╡ 5c99d554-6741-4c0e-9783-771680e414fe
md"""
# Stability
So far, we have seen that the step-size has to be chosen in order to control the local truncation error. However, the step-size is also directly related to the stability of our numerical method.
Note, that there is a difference between the stability of the analytical solutions and the numerical solutions.
Stability theory for the solutions of ODEs is well-developed and interesting theoretical topic. However, once it has been determined that we may expect stable analytical solutions, we should be interested in if the same holds for our numerical approximations.
"""
# ╔═╡ 5c226710-54fc-4bee-8e71-5a0d0061c0f0
md"""
## A curious example
We might think that so far, everything has gone well, so what could go wrong?
A surprising phenomenon appears in certain types of equations. Consider the following example
$$\dot x(t) = -50(x(t)-\cos(t)), \quad x(0)=x_{0}.$$
Plotting its solution curves, we find:
"""
# ╔═╡ eee070f2-f671-4217-9a39-38d492a4a7a7
begin
function analytical(t, a)
out = 2501.0 * a * exp(-50.0 * t)
out -= 2500.0 * exp(-50.0 * t)
out += 50.0 * sin(t)
out += 2500.0 * cos(t)
out /= 2501
return out
end
_a = 10.0 .^ collect(0:1:50)
_a = [-_a;_a]
_t = collect(0.0:0.01:1.5)
_s = [analytical(t, a) for t in _t, a in _a]
plot(_t, _s, label="", ylim=(0,1.5))
end
# ╔═╡ 1c5e654d-4699-4a00-9ba5-f5da72969d35
md"""
It is clear to see that all solution curves have a rapid transient phase towards the equilibrium solution $x(t) \approx \cos(t)$.
Imagine that we were to solve this equation using the explicit Euler scheme. If, by chance, we choose an initial condition $x_{0}\neq 1$, then the numerical solution curve would produce a "bumpy ride".
"""
# ╔═╡ 63489e4c-624f-4f03-8045-6b94e4876b10
md"""
## Stiffness
This phenomenon is called **stiffness** and its definition is not universally agreed upon.
Stiff equations are:
1) Problems for which explicit methods don't work
2) Problems for which certain numerical methods are numerically unstable
3) Problems for which the step-size has to be taken extremely small
Stiffness appears when the solution curves are "very stable".
"""
# ╔═╡ 48813f57-3029-4c91-814e-3603954d4c00
md"""
## Stability analysis
To grasp whether a numerical method may suffer from instability, we perform a stability analysis.
### Linear stability theory
Given the ODE
$$\dot x(t)=f(t,x(t)), \quad x(t_0)=x_0,$$
classical stability theory for the analytical solutions tell us that we have to investigate the stability of solutions to
$$\dot X(t)=JX(t), \quad X(t_0)=0,$$
where $J=\partial_{x}f(t_{0},x(t_{0}))$ is the Jacobian at some steady-state $f(t_{0},x(t_0))=0$.
In this case, the linear stability theory tells us that the steady-state solution of the original equation is stable if all eigenvalues of the Jacobian have negative real part:
$$\text{Re}(\lambda)<0, \quad \forall \lambda \in \lambda(J).$$
"""
# ╔═╡ 05882b94-54ee-4dbb-876c-02a7ec5bbe49
md"""
### Test equation
A simplified version of the above "test" equation (with a non-trivial solution) is known as the **Dahlquist test equation**
$$\dot x(t)=\lambda x(t), \quad x(0)=1,$$
with parameter $\lambda \in \mathbb{C}$. It is the primary benchmark for numerical methods. From before, we know its analytical solution:
$$x(t)=\exp(\lambda t)$$
We also know explicit Euler **approximates** the solution!
"""
# ╔═╡ cc2977bc-145c-4ed9-a1fc-d157f7c761b4
md"""
#### Stability analysis for explicit Euler
Applied to the test equation, we recall that the explicit Euler scheme becomes a linear recurrence relation
$$x_{k+1}=x_{k}+h\lambda x_k=(1+h\lambda)x_k$$
If we want the numerical solution to remain stable, we must require that
$$|1+h\lambda| \leq 1$$
Hence, for a given problem, where $\lambda \in \mathbb{C}$ is fixed, this puts an explicit condition on step-sizes $h$ which guarantee stability. The corresponding **stability region** is shown below:
"""
# ╔═╡ 6dd7b689-9447-4804-be86-b4a38034f915
begin
function explicit_stability(z)
out = 1+z
end
_r = -2.5:0.01:1.5
_i = -1.75:0.01:1.75
_R = [explicit_stability(r+i*im) for r in _r, i in _i]
_R = abs.(_R)
heatmap(_r, _i, _R', c=:RdBu, xlabel="Re(hλ)", ylabel="Im(hλ)", title="Explicit Euler stability")
vline!([0.0], color=:black, lw=2, label="")
hline!([0.0], color=:black, lw=2, label="")
plot!(cos.(0:0.1:2pi).-1,sin.(0:0.1:2pi), color=:black, lw=2, label="")
end
# ╔═╡ dd2c6725-dfd4-4f5f-ad3b-46728fe36568
md"""
#### Stability analysis for implicit Euler
A similar analysis is also performed for the implicit Euler scheme
$$x_{k+1}=x_{k}+hf(t_{k},x_{k})$$
Here we see for the test equation that
$$x_{k+1}=x_{k}+h\lambda x_{k+1} =\frac{1}{1-h\lambda}x_k$$
Again, stability requires that
$$\left|\frac{1}{1-h\lambda}\right|\leq1$$
The corresponding stability region is shown below:
"""
# ╔═╡ 174c6695-89b3-4786-8289-e68be0d42e1f
begin
function implicit_stability(z)
out = 1/(1-z)
end
_ri = -1.5:0.01:2.5
_ii = -1.75:0.01:1.75
_Ri = [implicit_stability(r+i*im) for r in _ri, i in _ii]
_Ri = abs.(_Ri)
heatmap(_ri, _ii, _Ri', c=:RdBu, clim=(0,3.05), xlabel="Re(hλ)", ylabel="Im(hλ)", title="Implicit Euler stability")
vline!([0.0], color=:black, lw=2, label="")
hline!([0.0], color=:black, lw=2, label="")
plot!(cos.(0:0.1:2pi).+1,sin.(0:0.1:2pi), color=:black, lw=2, label="")
end
# ╔═╡ 7dd538c9-6fb0-4736-966a-0c43349a7638
md"""
**How would we then expect the implicit Euler scheme handle the above stiff equation?**
"""
# ╔═╡ a634c6c7-f387-4720-afc1-d22ce9f7ce83
md"""
#### General stability analysis
In general, if we can write our numerical method applied to the test equation as a recurrence relation
$$x_{k+1}=R(h\lambda)x_{k}$$
then the stability region is given by all $h\in \mathbb{R}$ and $\lambda \in \mathbb{C}$ satisfying
$$|R(h\lambda)|\leq 1$$
**Note the difference between the continuous linear stability condition and discrete linear stability condition.**
"""
# ╔═╡ c9ec776e-e445-443d-b8e0-ce1cd02cb5da
md"""
# Break
**5-15 minutes?**
"""
# ╔═╡ 073e5c9c-a3d7-41bb-95d0-4c3fb9c750e3
md"""
# Error estimation
We now know that it is crucial to choose the step-size correctly, in order to enjoy both accuracy and stability. However, for accuracy, the step-size was related to the local error of our numerical method, which is unknown.
**Let us estimate it!**
"""
# ╔═╡ 08c6c980-9997-47a5-b591-628c8746a6ff
md"""
## Step-doubling
We know already that if we half the step-size, then asymptotically we will quarter the local error. Therefore, we can compare the numerical solution obtained by a single step, to that obtained by taking two half steps.
We perform a rudimentary theoretical analysis for scalar equations.
**See Lecture04C slides for the analysis on the test equation.**
"""
# ╔═╡ ae73a126-6705-45ee-8637-665a84e9f1c3
md"""
### Single step
Given a method of order $p$, we know that, asymptotically, for one step from $t_{k}$ to $t_{k+1}$ we have a local truncation error of the order
$$\tau_{k+1} = x_{k+1}-x_k(t_{k+1})=Ch^{p+1}+O(h^{p+2})$$
### Double step
Using the same method, we first take a half step with local truncation error
$$\hat{\tau}_{k+\frac{1}{2}}=\hat{x}_{k+\frac{1}{2}}-x_k(t_{k+\frac{1}{2}})=C\left(\left(h/2\right)^{p+1}\right)+O(h^{p+2})$$
and a second half step, which will have a similar local truncation error
$$\hat\tau_{k+1}=\hat{x}_{k+1}-x_{k+\frac{1}{2}}(t_{k+\frac{1}{2}})=C\left(\left(h/2\right)^{p+1}\right)+O(h^{p+2})$$
Using Taylor expansions, it is possible to show that
$$\hat{x}_{k+1}-x_{k}(t_{k+1})=2C\left(\left(h/2\right)^{p+1}\right)+O(h^{p+2})$$
"""
# ╔═╡ 56809f6e-6caf-4f4a-8e0b-fbc75633a04d
md"""
### Error estimate
Consequently, we find that that the error estimate asymptotically
$$\begin{align*}
\hat\tau_{k+1}=\hat{x}_{k+1}-x_{k+1} &= 2C\left(\left(h/2\right)^{p+1}\right)-Ch^{p+1}+O(h^{p+2})\\
&= KCh^{p+1}+O(h^{p+2}), \quad K\geq1
\end{align*}$$
We now see that this estimate of the local truncation error asymptotically follows a $K$ multiple of the original local truncation error
$$\hat\tau_{k+1} =K\tau_{k+1} \geq \tau_{k+1},$$
and therefore, we can use it to overestimate the error!
"""
# ╔═╡ 5e720150-4cf5-40b1-91e9-b0aaaae5ab71
md"""
#### Richardson Extrapolation
In a method known as Richardson extrapolation, the constant $K$ can be used to describe a method with one order higher $(p+1)$. Note that it is straightforward to compute the constant $K$.
"""
# ╔═╡ ac75df14-444b-48b5-97e8-87b781be101b
md"""
# Adaptive step-size control
## Accepting steps
Given the estimate of our local truncation error $\hat{\tau}_{k+1}$, we are now able to judge, whether or not our current step was computed accurately enough.
Setting an absolute tolerance $\varepsilon_\text{abs}>0$, we check whether the absolute truncation error is small enough
$$\|\hat\tau_{k+1}\|\leq \varepsilon_\text{abs}$$
If we further want control over the relative error, we set a relative tolerance $\varepsilon_\text{rel}$ and check whether
$$\|\hat\tau_{k+1}\|\leq \|[\varepsilon_\text{abs},\varepsilon_\text{rel}\|x_{k+1}\|]^T\|$$
Here, the choice of "norm" $||\cdot||$ is free to choose.
Often, we will consider scaled error estimates and check
$$\|r_{k+1}\|\leq 1$$
and to be extra sure, we sometimes include a safety factor $\alpha < 1$ (often $\alpha=0.8,0.95$)
$$\|r_{k+1}\|\leq \alpha$$
"""
# ╔═╡ 56d515b4-17db-405b-a046-42477e606020
md"""
## Adjusting steps
Assuming that the current error estimate was found too large with the step-size $h_{k}$, we consult the asymptotic error
$$\|r_{k+1}\|=\hat{C}h_{k}^{p+1}\leq\alpha$$
Rearranging the inequality and taking the largest step yields
$$\hat h_{k}=\left(\frac{\alpha}{\hat{C}}\right)^{\frac{1}{p+1}}$$
Rearranging the left-hand side equality gives us an estimate for the constant
$$\hat{C}=\|r_{k+1}\|h_{k}^{-(p+1)},$$
which yields the final choice of our new step-size
$$\hat{h}_{k}=h_{k}\left(\frac{\alpha}{\|r_{k+1}\|}\right)^{\frac{1}{p+1}}$$
This is known as **asymptotic step-size control**!
**Remark**: In case the step was accepted, the asymptotic step-size controller also gives a method to adjust the step-size in order to asymptotically hit the local truncation error tolerance.
"""
# ╔═╡ 3d709ffe-d04d-41e4-9ddb-c543d74ad539
md"""
## Initial step-size
A heuristic is needed to choose the initial step-size.
**See Lecture04B slides on Learn!**
"""
# ╔═╡ 069d49de-b8f7-469f-9bc6-445ff3cc680d
md"""
# Numerical experiments
The above considerations have been implemented below.
Here we have a method to perform adaptive integration with an explicit Euler scheme, as well as the classical Runge-Kutta scheme.
Let us now test how our routines behave with respect to
- Accuracy
- Stability
- Efficiency
"""
# ╔═╡ 654c5fc7-dda5-4d55-a8fc-f6702ebc7c11
begin
function adaptive_integrator(f, tspan, x₀, p; h₀=1e-6, reltol=1e-3, abstol=1e-6, method=euler_step!)
# Error controller parameters
safety_factor = 0.8
min_factor = 0.1
max_factor = 10.0
order = if (method == euler_step!) 1.0 else 4.0 end
# Integration interval
t₀, tₛ = tspan
# Initial condition
t = t₀
t₊ = t₀ + h₀
h = h₀
x = deepcopy(x₀)
# Cache
x₊ = zero(x)
x₊₊ = zero(x)
x₊₊₊ = zero(x)
dx = zero(x)
e = zero(x)
# Counters
nfun = 0
naccept = 0
nreject = 0
# Output
ts = [t]
xs = [deepcopy(x)]
rs = [0.0]
# Main loop
while t < tₛ
if t₊ > tₛ
t₊ = tₛ
h = t₊ - t
end
# Compute full step
method(x₊, f, dx, x, p, t, h)
# Compute two half steps
method(x₊₊, f, dx, x, p, t, 0.5h)
method(x₊₊₊, f, dx, x₊₊, p, t + 0.5h, 0.5h)
if (method == euler_step!)
nfun += 3
else
nfun += 12
end
# Get error estimate
e .= x₊₊₊ .- x₊
e ./= abstol .+ reltol .* max.(abs.(x₊₊₊), abs.(x₊))
r = norm(e)
if r ≤ 1
# Accept the step
naccept += 1
t += h
x .= x₊₊₊
push!(ts, t)
push!(xs, deepcopy(x))
push!(rs, r)
else
nreject += 1
end
# Asymptotic step-size control
h *= max(min_factor, min(max_factor, (safety_factor / r)^(1/(order+1))))
end
return ts, hcat(xs...), rs, nfun, naccept, nreject
end
function euler_step!(x₊, f, dx, x, p, t, h)
# Explicit Euler scheme
f(dx, x, t, p)
x₊ .= x .+ h .* dx
return nothing
end
function rk4_step!(x₊, f, dx, x, p, t, h)
#Non-optimized classical Runge-Kutta scheme
f(dx, x, t, p)
k₁ = h .* dx
f(dx, x .+ 0.5 .* k₁, t + 0.5 .* h, p)
k₂ = h .* dx
f(dx, x .+ 0.5 .* k₂, t + 0.5 .* h, p)
k₃ = h .* dx
f(dx, x .+ k₃, t + h, p)
k₄ = h .* dx
x₊ .= x .+ (k₁ .+ 2 .* k₂ .+ 2 .* k₃ .+ k₄) ./ 6
return nothing
end
end
# ╔═╡ 3ec61edc-f080-4c60-8583-c6e467628d69
md"""
## Benchmark
Following the modeling slides presented in the previous lectures, we have implemented a dispersive plug-flow reactor to benchmark on.
The dispersive PFR is a good test case, since its parameters can induce stiffness.
**Consult the Courant-Friedrichs-Lewy stability condition and Von Neumann stability analysis**
"""
# ╔═╡ a1ef93a5-710e-4051-8190-0279c93bbb73
function f(dx, x, t, p)
# States and boundary conditions
dcA = dx
cA = x
cAᵢₙ = p[5]
# Mesh
n = size(cA, 1)
h = p[1]
# Parameters
v = p[2]
D = p[3]
k = p[4]
# Flux
N = zeros(n + 1)
# Convective flux (upwinding)
if v > 0
N[1] = v * cAᵢₙ
N[2:end] .= v .* cA
else
N[1:end-1] .= v .* cA
N[end] = v * cAᵢₙ
end
# Diffusive flux
N[2:end-1] .-= (D / h) .* (cA[2:end] .- cA[1:end-1])
# Reaction rate
dcA .= -2.0 .* k .* cA .* cA
# Mass balances
dcA .-= (N[2:end] .- N[1:end-1]) ./ h
return nothing
end
# ╔═╡ cb764f34-c959-4936-8902-7da7ebadf439
md"""
### Problem definition
"""
# ╔═╡ 0dacd922-fdf9-4f80-b9e7-f12a68720d79
begin
## Problem
# Parameters
v = 1.0
D = 2e-1
k = 0.5
# Mesh
n = 20
L = 1.0
h = L / n
zs = collect(range(0.0, L, length=n))
## Initialization
tₛ = 10.0
tspan = (0.0, tₛ)
c₀ = 0.1 .* ones(n)
cᵢₙ = 0.2
p = [h, v, D, k, cᵢₙ]
## Integrate
ts, xs, rs, nfun, naccept, nreject = adaptive_integrator(
f, tspan, c₀, p;
reltol=1e-3, abstol=1e-6,
#method=euler_step!,
method=rk4_step!,
)
nothing
end
# ╔═╡ d17aa551-9b9e-48a2-a699-24c2371fdb85
plot(ts, xs'[:, end], label="", ylabel="Concentration cA", xlabel="Time t", title="Outlet", lw=2)
# ╔═╡ cb6a3f3a-6b9c-4944-8ab0-870ee754ca35
begin
plot(zs, xs[:,1:10:end], label="", ylabel="Concentration cA", xlabel="Length z", title="Profiles", lw=2)
end
# ╔═╡ 58d369b4-c52b-4af9-be3a-955edd253bf6
surface(ts, zs, xs, title="Concentration surface", xflip = true, camera = (75,35))
# ╔═╡ 00e1d80f-893e-47dd-8592-faeb71cb4744
md"""
## Accuracy & stability
"""
# ╔═╡ 235031fa-9d28-4398-becc-559eb59c4bd5
begin
errorplot=plot(ts[2:end], rs[2:end], label="||r||", xlabel="Time t", ylabel="Error norm ||r||", lw=2, title="Error")
hline!([1.0], label="Accept step", lw=2)
hline!([0.8], label="Error goal", lw=2)
hplot=plot(ts[2:end], diff(ts), label="h", xlabel="Time t", ylabel="Step-size h", lw=2, title="Step-size")
plot(errorplot, hplot, layout=(2,1))
end
# ╔═╡ 03bcdf8a-6ef4-4056-a411-937e89c40789
begin
@info "Function evaluations: $(nfun)"
@info "Accepted steps: $(naccept)"
@info "Rejected steps: $(nreject)"
end
# ╔═╡ 5bac1c45-1b54-455a-9150-25e5d65c9008
md"""
**To test the accuracy and stability, try to modify:**
- The diffusion parameter `D` and reaction parameter `k`
- Which parameter effects the problem stiffness?
- The method `euler_step!` vs. `rk4_step!`
- Which integrator performs the best?
- At which tolerance?
- At which "level" of stiffness?
"""
# ╔═╡ 5b205537-307a-4f1e-9739-62b1e1929467
md"""
## Efficiency
Let us reality-check our initial numerical tests. We benchmark both methods based on their individual **work-precision diagram**.
"""
# ╔═╡ d84473d0-f94d-411e-950b-f73ebb5cce37
function work_precision(f, tspan, x₀, p)
# Sequence of equal reltol=abstol=tol in log-scape
tols = 10.0 .^ collect(range(-8, -2, length=10))
nfuns = zeros(length(tols), 2)
for method in [euler_step!, rk4_step!]
for (i, tol) in enumerate(tols)
_, _, _, nfun, _, _ = adaptive_integrator(
f, tspan, x₀, p;
reltol=tol, abstol=tol,
method=method,
)
nfuns[i, method == euler_step! ? 1 : 2] = nfun
end
end
return tols, nfuns
end
# ╔═╡ 1b2b8427-c417-4d72-998b-ecf6f3687a15
begin
#tols, nfuns = work_precision(f, tspan, c₀, p)
#scatter(tols, nfuns, xscale=:log10, yscale=:log10, xlabel="Tolerance εₐ=εᵣ=ε", #ylabel="Function evaluations", markersize=5, label=["Explicit Euler" "Classical #RK4"])
end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
[compat]
Plots = "~1.40.9"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.11.2"
manifest_format = "2.0"
project_hash = "49c59e298d2677d57878b8dda433262eeea19c77"
[[deps.AliasTables]]
deps = ["PtrArrays", "Random"]
git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff"
uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8"
version = "1.1.3"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.2"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
version = "1.11.0"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
version = "1.11.0"
[[deps.BitFlags]]
git-tree-sha1 = "0691e34b3bb8be9307330f88d1a3c3f25466c24d"
uuid = "d1d4a3ce-64b1-5f1a-9ba4-7e7e69966f35"
version = "0.1.9"
[[deps.Bzip2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "8873e196c2eb87962a2048b3b8e08946535864a1"
uuid = "6e34b625-4abd-537c-b88f-471c36dfa7a0"
version = "1.0.8+4"
[[deps.Cairo_jll]]
deps = ["Artifacts", "Bzip2_jll", "CompilerSupportLibraries_jll", "Fontconfig_jll", "FreeType2_jll", "Glib_jll", "JLLWrappers", "LZO_jll", "Libdl", "Pixman_jll", "Xorg_libXext_jll", "Xorg_libXrender_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "009060c9a6168704143100f36ab08f06c2af4642"
uuid = "83423d85-b0ee-5818-9007-b63ccbeb887a"
version = "1.18.2+1"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "962834c22b66e32aa10f7611c08c8ca4e20749a9"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.8"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"]
git-tree-sha1 = "26ec26c98ae1453c692efded2b17e15125a5bea1"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.28.0"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "c7acce7a7e1078a20a285211dd73cd3941a871d6"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.12.0"
weakdeps = ["StyledStrings"]
[deps.ColorTypes.extensions]
StyledStringsExt = "StyledStrings"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"]
git-tree-sha1 = "8b3b6f87ce8f65a2b4f857528fd8d70086cd72b1"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.11.0"
[deps.ColorVectorSpace.extensions]
SpecialFunctionsExt = "SpecialFunctions"
[deps.ColorVectorSpace.weakdeps]
SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "64e15186f0aa277e174aa81798f7eb8598e0157e"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.13.0"
[[deps.Compat]]
deps = ["TOML", "UUIDs"]
git-tree-sha1 = "8ae8d32e09f0dcf42a36b90d4e17f5dd2e4c4215"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.16.0"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.1.1+0"
[[deps.ConcurrentUtilities]]
deps = ["Serialization", "Sockets"]
git-tree-sha1 = "d9d26935a0bcffc87d2613ce14c527c99fc543fd"
uuid = "f0e56b4a-5159-44fe-b623-3e5288b988bb"
version = "2.5.0"
[[deps.Contour]]
git-tree-sha1 = "439e35b0b36e2e5881738abc8857bd92ad6ff9a8"
uuid = "d38c429a-6771-53c6-b99e-75d170b6e991"
version = "0.6.3"
[[deps.DataAPI]]
git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.16.0"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "1d0a14036acb104d9e89698bd408f63ab58cdc82"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.20"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
version = "1.11.0"
[[deps.Dbus_jll]]
deps = ["Artifacts", "Expat_jll", "JLLWrappers", "Libdl"]
git-tree-sha1 = "fc173b380865f70627d7dd1190dc2fce6cc105af"
uuid = "ee1fde0b-3d02-5ea6-8484-8dfef6360eab"
version = "1.14.10+0"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae"
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
version = "1.9.1"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.EpollShim_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "8a4be429317c42cfae6a7fc03c31bad1970c310d"
uuid = "2702e6a9-849d-5ed8-8c21-79e8b8f9ee43"
version = "0.0.20230411+1"
[[deps.ExceptionUnwrapping]]
deps = ["Test"]
git-tree-sha1 = "d36f682e590a83d63d1c7dbd287573764682d12a"
uuid = "460bff9d-24e4-43bc-9d9f-a8973cb893f4"
version = "0.1.11"
[[deps.Expat_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "e51db81749b0777b2147fbe7b783ee79045b8e99"
uuid = "2e619515-83b5-522b-bb60-26c02a35a201"
version = "2.6.4+3"
[[deps.FFMPEG]]
deps = ["FFMPEG_jll"]
git-tree-sha1 = "53ebe7511fa11d33bec688a9178fac4e49eeee00"
uuid = "c87230d0-a227-11e9-1b43-d7ebe4e7570a"
version = "0.4.2"
[[deps.FFMPEG_jll]]
deps = ["Artifacts", "Bzip2_jll", "FreeType2_jll", "FriBidi_jll", "JLLWrappers", "LAME_jll", "Libdl", "Ogg_jll", "OpenSSL_jll", "Opus_jll", "PCRE2_jll", "Zlib_jll", "libaom_jll", "libass_jll", "libfdk_aac_jll", "libvorbis_jll", "x264_jll", "x265_jll"]
git-tree-sha1 = "466d45dc38e15794ec7d5d63ec03d776a9aff36e"
uuid = "b22a6f82-2f65-5046-a5b2-351ab43fb4e5"
version = "4.4.4+1"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
version = "1.11.0"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "05882d6995ae5c12bb5f36dd2ed3f61c98cbb172"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.5"
[[deps.Fontconfig_jll]]
deps = ["Artifacts", "Bzip2_jll", "Expat_jll", "FreeType2_jll", "JLLWrappers", "Libdl", "Libuuid_jll", "Zlib_jll"]
git-tree-sha1 = "21fac3c77d7b5a9fc03b0ec503aa1a6392c34d2b"
uuid = "a3f928ae-7b40-5064-980b-68af3947d34b"
version = "2.15.0+0"
[[deps.Format]]
git-tree-sha1 = "9c68794ef81b08086aeb32eeaf33531668d5f5fc"
uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8"
version = "1.3.7"
[[deps.FreeType2_jll]]
deps = ["Artifacts", "Bzip2_jll", "JLLWrappers", "Libdl", "Zlib_jll"]
git-tree-sha1 = "786e968a8d2fb167f2e4880baba62e0e26bd8e4e"
uuid = "d7e528f0-a631-5988-bf34-fe36492bcfd7"
version = "2.13.3+1"
[[deps.FriBidi_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl"]
git-tree-sha1 = "846f7026a9decf3679419122b49f8a1fdb48d2d5"
uuid = "559328eb-81f9-559d-9380-de523a88c83c"
version = "1.0.16+0"
[[deps.GLFW_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Libglvnd_jll", "Xorg_libXcursor_jll", "Xorg_libXi_jll", "Xorg_libXinerama_jll", "Xorg_libXrandr_jll", "libdecor_jll", "xkbcommon_jll"]
git-tree-sha1 = "fcb0584ff34e25155876418979d4c8971243bb89"
uuid = "0656b61e-2033-5cc2-a64a-77c0f6c09b89"
version = "3.4.0+2"
[[deps.GR]]
deps = ["Artifacts", "Base64", "DelimitedFiles", "Downloads", "GR_jll", "HTTP", "JSON", "Libdl", "LinearAlgebra", "Preferences", "Printf", "Qt6Wayland_jll", "Random", "Serialization", "Sockets", "TOML", "Tar", "Test", "p7zip_jll"]
git-tree-sha1 = "9bf00ba4c45867c86251a7fd4cb646dcbeb41bf0"
uuid = "28b8d3ca-fb5f-59d9-8090-bfdbd6d07a71"
version = "0.73.12"
[[deps.GR_jll]]
deps = ["Artifacts", "Bzip2_jll", "Cairo_jll", "FFMPEG_jll", "Fontconfig_jll", "FreeType2_jll", "GLFW_jll", "JLLWrappers", "JpegTurbo_jll", "Libdl", "Libtiff_jll", "Pixman_jll", "Qt6Base_jll", "Zlib_jll", "libpng_jll"]
git-tree-sha1 = "36d5430819123553bf31dfdceb3653ca7d9e62d7"
uuid = "d2c73de3-f751-5644-a686-071e5b155ba9"
version = "0.73.12+0"
[[deps.Gettext_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Libiconv_jll", "Pkg", "XML2_jll"]
git-tree-sha1 = "9b02998aba7bf074d14de89f9d37ca24a1a0b046"
uuid = "78b55507-aeef-58d4-861c-77aaff3498b1"
version = "0.21.0+0"
[[deps.Glib_jll]]
deps = ["Artifacts", "Gettext_jll", "JLLWrappers", "Libdl", "Libffi_jll", "Libiconv_jll", "Libmount_jll", "PCRE2_jll", "Zlib_jll"]
git-tree-sha1 = "b0036b392358c80d2d2124746c2bf3d48d457938"
uuid = "7746bdde-850d-59dc-9ae8-88ece973131d"
version = "2.82.4+0"
[[deps.Graphite2_jll]]
deps = ["Artifacts", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "01979f9b37367603e2848ea225918a3b3861b606"
uuid = "3b182d85-2403-5c21-9c21-1e1f0cc25472"
version = "1.3.14+1"
[[deps.Grisu]]
git-tree-sha1 = "53bb909d1151e57e2484c3d1b53e19552b887fb2"
uuid = "42e2da0e-8278-4e71-bc24-59509adca0fe"
version = "1.0.2"
[[deps.HTTP]]
deps = ["Base64", "CodecZlib", "ConcurrentUtilities", "Dates", "ExceptionUnwrapping", "Logging", "LoggingExtras", "MbedTLS", "NetworkOptions", "OpenSSL", "PrecompileTools", "Random", "SimpleBufferStream", "Sockets", "URIs", "UUIDs"]
git-tree-sha1 = "c67b33b085f6e2faf8bf79a61962e7339a81129c"
uuid = "cd3eb016-35fb-5094-929b-558a96fad6f3"