-
Notifications
You must be signed in to change notification settings - Fork 0
/
shallow_water_model.py
765 lines (669 loc) · 23.1 KB
/
shallow_water_model.py
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
r"""Python implementation of a unidimensional Shallow Water model.
The model describes the time evolution of the water height \(h(x)\)
and the horizontal velocity \(v(x)\) in a fixed-length domain. The
model equations read:
\[
\frac{\partial h}{\partial t} + \frac{\partial(hu)}{\partial x} = 0,\\
\frac{\partial(hu)}{\partial t} + \frac{\partial(hu^2)}{\partial x} + gh\frac{\partial h}{\partial x} = 0.
\]
The boundary conditions are the following:
1. on the left, a constant inflow \(Q=hu\);
2. on the right, a homogeneous Neumann condition for \(h\) and \(u\),
where fluxes are consequently determined by the state of the system
along the boundary.
The equations are solved by the `shallow_water_forward` function using
numerical schemes detailed by, e.g., [Honnorat, 2007](https://tel.archives-ouvertes.fr/tel-00273318)
and originally implemented by [Vivien Mallet](mailto:[email protected]).
The `ShallowWaterModel` class defines a user-friendly object-oriented
interface to the `shallow_water_forward` function and can be used as follows.
model = ShallowWaterModel()
state = model.new_state_crenel()
for t in range(Nt):
model.forward(state)
"""
import numpy as np
from numba import njit
class ShallowWaterState:
r"""Container class for a Shallow Water model state.
A model state is a couple of numpy arrays `(h, u)` of size `Nx`
(the number of grid points) containing the values of \(h(x)\) and
\(u(x)\) in the domain. For simplicity, each model state also stores
a couple of numpy arrays `(fh, fu)` of size `Nx+1`. These arrays
are used as temporary storage during the model integration to
compute the flux values for \(h(x)\) and \(u(x)\).
Attributes
----------
h : numpy array of size Nx
The values of \(h(x)\).
u : numpy array of size Nx
The values of \(u(x)\).
fh : numpy array of size Nx+1
The flux values for \(h(x)\).
fu : numpy array of size Nx+1
The flux values for \(u(x)\).
"""
def __init__(self, Nx):
"""Init the model state."""
self.h = np.ones(Nx)
self.u = np.zeros(Nx)
self.fh = np.zeros(Nx+1)
self.fu = np.zeros(Nx+1)
class ShallowWaterEnsembleState:
r"""Container class for an ensemble of Shallow Water model states.
See the documentation for the `ShallowWaterState` class.
Attributes
----------
Ne : int
Ensemble size.
h : numpy array of shape (Ne, Nx)
The values of \(h(i, x)\).
u : numpy array of shape (Ne, Nx)
The values of \(u(i, x)\).
fh : numpy array of size Nx+1
The flux values for \(h(x)\).
fu : numpy array of size Nx+1
The flux values for \(u(x)\).
"""
def __init__(self, Ne, Nx):
"""Init the ensemble of model states."""
self.Ne = Ne
self.h = np.ones((Ne, Nx))
self.u = np.zeros((Ne, Nx))
self.fh = np.zeros(Nx+1)
self.fu = np.zeros(Nx+1)
class ShallowWaterModel:
"""Implementation of the Shallow Water model.
Attributes
----------
Nx : integer, optional
The number of grid points.
dx : real, optional
The size of the grid cell.
dt : real, optional
The integration step.
Q : real, optional
The constant inflow on the left.
g : real, optional
The acceleration due to gravity.
"""
def __init__(self, Nx=100, dx=1, dt=0.03, Q=0.1, g=9.81):
"""Init the model."""
self.Nx = Nx
self.dx = dx
self.dt = dt
self.Q = Q
self.g = g
def new_state_crenel(self, h_anom=1.05):
r"""Create a new model state.
The water height \(h(x)\) is a crenel: \(h(x)=1\) everywhere but
in the center of the domain, where \(h(x)=h_a\).
The horizontal velocity \(u(x)\) is null.
Arguments
---------
h_anom : real, optional
The water height at the center \(h_a\).
Returns
-------
state : ShallowWaterState
The new model state.
"""
ic = (self.Nx-1) // 2
i_min = max(ic-5, 0)
i_max = min(ic+5, self.Nx-1)
state = ShallowWaterState(self.Nx)
state.h[i_min:i_max+1] = h_anom
return state
def new_ensemble_crenel(self,
Ne,
mean_h_anom=0,
std_h_anom=0.02,
seed=None,
debias=True):
"""Create an ensemble of model states.
Each ensemble member is built as in the `ShallowWaterModel.new_state_crenel`
method but with a random value for `h_anom`, drawn from the
normal distribution with mean `mean_h_anom` and standard deviation
`std_h_anom`.
Arguments
---------
Ne : int
Ensemble size
mean_h_anom : real, optional
The average water anomaly in the ensemble.
std_h_anom : real, optional
The standard deviation of water anomaly in the ensemble.
seed : int, optional
The random seed.
debias : boolean, optional
If True, the sample mean of `h_anom` is corrected to be
exactly `mean_h_anom`.
Returns
-------
ensemble : ShallowWaterEnsembleState
The new ensemble of model states.
"""
rng = np.random.default_rng(seed=seed)
ic = (self.Nx-1) // 2
i_min = max(ic-5, 0)
i_max = min(ic+5, self.Nx-1)
h_anom = rng.standard_normal(size=Ne)
if debias:
h_anom -= h_anom.mean()
h_anom = mean_h_anom + std_h_anom * h_anom
ensemble = ShallowWaterEnsembleState(Ne, self.Nx)
for i in range(Ne):
ensemble.h[i, i_min:i_max+1] = h_anom[i]
return ensemble
def forward(self, state):
"""Perform one integration step.
Uses the `shallow_water_forward` function to integrate the model
state.
Arguments
---------
state : ShallowWaterState
The model state to integrate.
"""
shallow_water_forward(self.Nx,
self.dx,
self.dt,
self.Q,
self.g,
state.h,
state.u,
state.fh,
state.fu)
def forward_ensemble(self, ensemble):
"""Perform one integration step.
Uses the `shallow_water_forward` function to integrate the model
states.
Arguments
---------
ensemble : ShallowWaterEnembleState
The ensemble of model states to integrate.
"""
for i in range(ensemble.Ne):
shallow_water_forward(self.Nx,
self.dx,
self.dt,
self.Q,
self.g,
ensemble.h[i],
ensemble.u[i],
ensemble.fh,
ensemble.fu)
@njit(cache=True)
def shallow_water_forward(Nx, dx, dt, Q, g, h, u, fh, fu):
r"""Perform one integration of the Shallow Water model.
The integration is performed in-place and relies on
`numba` for efficiency.
Arguments
---------
Nx : integer
The number of grid points.
dx : real
The size of the grid cell.
dt : real
The integration step.
Q : real
The constant inflow on the left.
g : real
The acceleration due to gravity.
h : numpy array of size Nx
The values of \(h(x)\).
u : numpy array of size Nx
The values of \(u(x)\).
fh : numpy array of size Nx+1
Temporary storage of the flux values for \(h(x)\).
fu : numpy array of size Nx+1
Temporary storage of the flux values for \(u(x)\).
"""
# left boundary: constant inflow
fh[0], fu[0] = _compute_flux_hll(g, h[0], h[0], Q/h[0], u[0])
# fluxes inside the domain
for i in range(Nx-1):
fh[i+1], fu[i+1] = _compute_flux_hll(g, h[i], h[i+1], u[i], u[i+1])
# right boundary: free
fh[Nx], fu[Nx] = _compute_flux_hll(g, h[Nx-1], h[Nx-1], u[Nx-1], u[Nx-1])
# update h and u
for i in range(Nx):
h[i] += dt * (fh[i]-fh[i+1]) / dx
u[i] += dt * (fu[i]-fu[i+1]) / dx
@njit(cache=True)
def _compute_flux_hll(g, hl, hr, ul, ur):
"""Auxiliary function for the model integration."""
# phase speed of the wave
cl = np.sqrt(g*hl)
cr = np.sqrt(g*hr)
clr = cl + cr
# height at the interface
ulr = ul - ur
h_tmp = 0.5 * (hl+hr) * (1+0.5*ulr/clr)
if h_tmp <= min(hl, hr):
tmp = 0.5*clr + 0.25*ulr
h_interface = tmp**2/g
elif h_tmp >= max(hl, hr):
gl = np.sqrt(0.5*g*(h_tmp+hl)/(h_tmp*hl))
gr = np.sqrt(0.5*g*(h_tmp+hr)/(h_tmp*hr))
h_interface = (hl*gl+hr*gr+ulr) / (gl+gr)
else:
h_interface = h_tmp
# wave velocity
pl = np.sqrt(0.5*h_interface*(h_interface+hl)) / hl if h_interface > hl else 1
sl = ul - cl*pl
if sl >= 0:
return _compute_flux(g, hl, ul)
pr = np.sqrt(0.5*h_interface*(h_interface+hr)) / hr if h_interface > hr else 1
sr = ur + cr*pr
if sr <= 0:
return _compute_flux(g, hr, ur)
# flux
fhl, ful = _compute_flux(g, hl, ul)
fhr, fur = _compute_flux(g, hr, ur)
fh = (sr*fhl-sl*fhr+sr*sl*(hr-hl))/(sr-sl)
fu = (sr*ful-sl*fur-sr*sl*ulr)/(sr-sl)
return (fh, fu)
@njit(cache=True)
def _compute_flux(g, h, u):
"""Auxiliary function for the model integration."""
fh = h*u
fu = h*u**2 + 0.5*g*h**2
return (fh, fu)
def make_fancy_animation_h(trajs_h,
title,
palette=None,
Nx=100,
x_min=0,
x_max=100,
y_min=0.99,
y_max=1.08,
Nt=500,
freq=10,
interval=75):
r"""Make an animation of water height.
Arguments
---------
trajs_h : list
The list of trajectories to plot. Each element is
a tuple (label, data) where label is a string,
the label to print, and data is the numpy array
containing the trajectory \(h(t)\) to plot.
title : string
The title of the animation.
palette : list, optional
The color palette. Defaults to seaborn's deep palette.
Nx : int, optional
The number of grid points.
x_min : float, optional
The lower limit for the x-axis.
x_max : float, optional
The upper limit for the x-axis.
y_min : float, optional
The lower limit for the y-axis.
y_max : float, optional
The upper limit for the y-axis.
Nt : int, optional
The number of time steps to animate.
freq : int, optional
The time frequency for animation frames.
interval : int, optional
The time delay between frames in milliseconds.
Returns
-------
anim : matplotlib.animation.FuncAnimation
The fancy animation.
"""
from matplotlib import pyplot as plt
from matplotlib import animation
import seaborn as sns
if palette is None:
palette = sns.color_palette('deep')
fig = plt.figure(figsize=(12, 6))
ax = plt.gca()
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xlabel('Domain')
ax.set_ylabel('Water height')
ax.set_title(title)
lines = []
for (i, (lbl, traj)) in enumerate(trajs_h):
line, = ax.plot([], [], c=palette[i], label=lbl)
lines.append(line)
plt.legend()
x = np.arange(Nx+1)
def animate(t):
for (i, (lbl, traj)) in enumerate(trajs_h):
lines[i].set_data(x, traj[t])
return tuple(lines)
frames = range(0, Nt+1, freq)
anim = animation.FuncAnimation(fig, animate, frames=frames,
interval=interval, blit=True)
plt.close(fig)
return anim
def make_fancy_animation_u(trajs_u,
title,
palette=None,
Nx=100,
x_min=0,
x_max=100,
y_min=-0.2,
y_max=0.2,
Nt=500,
freq=10,
interval=75):
r"""Make an animation of horizontal velocity.
Arguments
---------
trajs_u : list
The list of trajectories to plot. Each element is
a tuple (label, data) where label is a string,
the label to print, and data is the numpy array
containing the trajectory \(u(t)\) to plot.
title : string
The title of the animation.
palette : list, optional
The color palette. Defaults to seaborn's deep palette.
Nx : int, optional
The number of grid points.
x_min : float, optional
The lower limit for the x-axis.
x_max : float, optional
The upper limit for the x-axis.
y_min : float, optional
The lower limit for the y-axis.
y_max : float, optional
The upper limit for the y-axis.
Nt : int, optional
The number of time steps to animate.
freq : int, optional
The time frequency for animation frames.
interval : int, optional
The time delay between frames in milliseconds.
Returns
-------
anim : matplotlib.animation.FuncAnimation
The fancy animation.
"""
from matplotlib import pyplot as plt
from matplotlib import animation
import seaborn as sns
if palette is None:
palette = sns.color_palette('deep')
fig = plt.figure(figsize=(12, 6))
ax = plt.gca()
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xlabel('Domain')
ax.set_ylabel('Horizontal velocity')
ax.set_title(title)
lines = []
for (i, (lbl, traj)) in enumerate(trajs_u):
line, = ax.plot([], [], c=palette[i], label=lbl)
lines.append(line)
plt.legend()
x = np.arange(Nx+1)
def animate(t):
for (i, (lbl, traj)) in enumerate(trajs_u):
lines[i].set_data(x, traj[t])
return tuple(lines)
frames = range(0, Nt+1, freq)
anim = animation.FuncAnimation(fig, animate, frames=frames,
interval=interval, blit=True)
plt.close(fig)
return anim
def plot_time_series_h(trajs,
title,
palette=None,
y_min=0.99,
y_max=1.08,
dt=0.03,
Nt=500):
"""Make a time series plot for water height.
Arguments
---------
trajs : list
The list of trajectories to plot. Each element is
a tuple (label, data) where label is a string,
the label to print, and data is the numpy array
containing the trajectory \(h(t)\) to plot.
title : string
The title of the animation.
palette : list, optional
The color palette. Defaults to seaborn's deep palette.
y_min : float, optional
The lower limit for the y-axis.
y_max : float, optional
The upper limit for the y-axis.
dt : float, optional
The integration time step.
Nt : int, optional
The number of time steps to animate.
"""
from matplotlib import pyplot as plt
import seaborn as sns
time = dt * np.arange(Nt+1)
if palette is None:
palette = sns.color_palette('deep')
fig = plt.figure(figsize=(12, 6))
ax = plt.gca()
ax.set_xlim(time[0], time[-1])
ax.set_ylim(y_min, y_max)
ax.set_xlabel('Time')
ax.set_ylabel('Water height')
ax.set_title(title)
for (i, (lbl, traj)) in enumerate(trajs):
ax.plot(time, traj, c=palette[i], label=lbl)
plt.legend()
def plot_time_series_mae(trajs,
title,
palette=None,
y_min=0,
y_max=0.01,
dt=0.03,
Nt=500):
"""Make a time series plot for MAE.
Arguments
---------
trajs : list
The list of trajectories to plot. Each element is
a tuple (label, data) where label is a string,
the label to print, and data is the numpy array
containing the trajectory \(h(t)\) to plot.
title : string
The title of the animation.
palette : list, optional
The color palette. Defaults to seaborn's deep palette.
y_min : float, optional
The lower limit for the y-axis.
y_max : float, optional
The upper limit for the y-axis.
dt : float, optional
The integration time step.
Nt : int, optional
The number of time steps to animate.
"""
from matplotlib import pyplot as plt
import seaborn as sns
time = dt * np.arange(Nt+1)
if palette is None:
palette = sns.color_palette('deep')
fig = plt.figure(figsize=(12, 6))
ax = plt.gca()
ax.set_xlim(time[0], time[-1])
ax.set_ylim(y_min, y_max)
ax.set_xlabel('Time')
ax.set_ylabel('MAE')
ax.set_title(title)
for (i, (lbl, traj)) in enumerate(trajs):
ax.plot(time, traj, c=palette[i], label=lbl)
plt.legend()
def plot_time_series_rmse(trajs,
title,
palette=None,
y_min=0,
y_max=0.02,
dt=0.03,
Nt=500):
"""Make a time series plot for RMSE.
Arguments
---------
trajs : list
The list of trajectories to plot. Each element is
a tuple (label, data) where label is a string,
the label to print, and data is the numpy array
containing the trajectory \(h(t)\) to plot.
title : string
The title of the animation.
palette : list, optional
The color palette. Defaults to seaborn's deep palette.
y_min : float, optional
The lower limit for the y-axis.
y_max : float, optional
The upper limit for the y-axis.
dt : float, optional
The integration time step.
Nt : int, optional
The number of time steps to animate.
"""
from matplotlib import pyplot as plt
import seaborn as sns
time = dt * np.arange(Nt+1)
if palette is None:
palette = sns.color_palette('deep')
fig = plt.figure(figsize=(12, 6))
ax = plt.gca()
ax.set_xlim(time[0], time[-1])
ax.set_ylim(y_min, y_max)
ax.set_xlabel('Time')
ax.set_ylabel('RMSE')
ax.set_title(title)
for (i, (lbl, traj)) in enumerate(trajs):
ax.plot(time, traj, c=palette[i], label=lbl)
plt.legend()
def make_fancy_animation_h_ensemble(trajs_h,
trajs_E,
title,
palette=None,
Nx=100,
x_min=0,
x_max=100,
y_min=0.99,
y_max=1.08,
Nt=500,
freq=10,
interval=75):
r"""Make an animation of water height.
Arguments
---------
trajs_h : list
The list of trajectories to plot. Each element is
a tuple (label, data) where label is a string,
the label to print, and data is the numpy array
containing the trajectory \(h(t)\) to plot.
trajs_E : list
The list of ensemble members to plot.
title : string
The title of the animation.
palette : list, optional
The color palette. Defaults to seaborn's deep palette.
Nx : int, optional
The number of grid points.
x_min : float, optional
The lower limit for the x-axis.
x_max : float, optional
The upper limit for the x-axis.
y_min : float, optional
The lower limit for the y-axis.
y_max : float, optional
The upper limit for the y-axis.
Nt : int, optional
The number of time steps to animate.
freq : int, optional
The time frequency for animation frames.
interval : int, optional
The time delay between frames in milliseconds.
Returns
-------
anim : matplotlib.animation.FuncAnimation
The fancy animation.
"""
from matplotlib import pyplot as plt
from matplotlib import animation
import seaborn as sns
if palette is None:
palette = sns.color_palette('deep')
fig = plt.figure(figsize=(12, 6))
ax = plt.gca()
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
ax.set_xlabel('Domain')
ax.set_ylabel('Water height')
ax.set_title(title)
lines = []
lines_E = []
for traj in trajs_E:
line, = ax.plot([], [], c=palette[len(trajs_h)], lw=0.25)
lines_E.append(line)
for (i, (lbl, traj)) in enumerate(trajs_h):
line, = ax.plot([], [], c=palette[i], label=lbl)
lines.append(line)
plt.legend()
x = np.arange(Nx+1)
def animate(t):
for (line, traj) in zip(lines_E, trajs_E):
line.set_data(x, traj[t])
for (i, (lbl, traj)) in enumerate(trajs_h):
lines[i].set_data(x, traj[t])
return tuple(lines_E+lines)
frames = range(0, Nt+1, freq)
anim = animation.FuncAnimation(fig, animate, frames=frames,
interval=interval, blit=True)
plt.close(fig)
return anim
def make_fancy_animation_B(traj_B,
title,
cmap=None,
vmax=5e-5,
Nt=500,
freq=10,
interval=75):
"""Make an animation of B matrix.
Arguments
---------
trajs_B : numpy array
The trajectories of B to plot.
title : string
The title of the animation.
cmap : string, optional
The color map. Defaults to custom RdBu cmap.
v_max : float, optional
The upper limit for the z-axis.
Nt : int, optional
The number of time steps to animate.
freq : int, optional
The time frequency for animation frames.
interval : int, optional
The time delay between frames in milliseconds.
Returns
-------
anim : matplotlib.animation.FuncAnimation
The fancy animation.
"""
from matplotlib import pyplot as plt
from matplotlib import animation
import seaborn as sns
if cmap is None:
cmap = sns.diverging_palette(240, 10, as_cmap=True)
fig = plt.figure(figsize=(12, 6))
ax = plt.gca()
ax.grid(False)
ax.set_title(title)
im = ax.imshow(traj_B[0], vmin=-vmax, vmax=vmax, cmap=cmap)
plt.colorbar(im)
def animate(t):
im.set_array(traj_B[t])
return (im,)
frames = range(0, Nt+1, freq)
anim = animation.FuncAnimation(fig, animate, frames=frames,
interval=interval, blit=True)
plt.close(fig)
return anim