-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathbarotropicqgql_betaforced.jl
305 lines (233 loc) · 9.47 KB
/
barotropicqgql_betaforced.jl
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
# # Quasi-Linear forced-dissipative barotropic QG beta-plane turbulence
#
#md # This example can be viewed as a Jupyter notebook via [](@__NBVIEWER_ROOT_URL__/generated/barotropicqgql_betaforced.ipynb).
#
# A simulation of forced-dissipative barotropic quasi-geostrophic turbulence on
# a beta plane under the *quasi-linear approximation*. The dynamics include
# linear drag and stochastic excitation.
#
# ## Install dependencies
#
# First let's make sure we have all required packages installed.
# ```julia
# using Pkg
# pkg"add GeophysicalFlows, Random, Statistics, Printf, Plots"
# ```
# ## Let's begin
# Let's load `GeophysicalFlows.jl` and some other needed packages.
using GeophysicalFlows, Random, Printf, Plots
using FourierFlows: parsevalsum
using Statistics: mean
# ## Choosing a device: CPU or GPU
dev = CPU() # Device (CPU/GPU)
nothing # hide
# ## Numerical parameters and time-stepping parameters
n = 128 # 2D resolution = n^2
stepper = "FilteredRK4" # timestepper
dt = 0.05 # timestep
nsteps = 8000 # total number of time-steps
nsubs = 10 # number of time-steps for intermediate logging/plotting (nsteps must be multiple of nsubs)
nothing # hide
# ## Physical parameters
L = 2π # domain size
β = 10.0 # planetary PV gradient
μ = 0.01 # bottom drag
nothing # hide
# ## Forcing
# We force the vorticity equation with stochastic excitation that is delta-correlated in time
# and while spatially homogeneously and isotropically correlated. The forcing has a spectrum
# with power in a ring in wavenumber space of radius ``k_f`` (`forcing_wavenumber`) and width
# ``δ_f`` (`forcing_bandwidth`), and it injects energy per unit area and per unit time
# equal to ``\varepsilon``. That is, the forcing covariance spectrum is proportional to
# ``\exp{[-(|\bm{k}| - k_f)^2 / (2 δ_f^2)]}``.
forcing_wavenumber = 14.0 * 2π/L # the forcing wavenumber, `k_f`, for a spectrum that is a ring in wavenumber space
forcing_bandwidth = 1.5 * 2π/L # the width of the forcing spectrum, `δ_f`
ε = 0.001 # energy input rate by the forcing
grid = TwoDGrid(dev, n, L)
K = @. sqrt(grid.Krsq) # a 2D array with the total wavenumber
forcing_spectrum = @. exp(-(K - forcing_wavenumber)^2 / (2 * forcing_bandwidth^2))
@CUDA.allowscalar forcing_spectrum[grid.Krsq .== 0] .= 0 # ensure forcing has zero domain-average
ε0 = parsevalsum(forcing_spectrum .* grid.invKrsq / 2, grid) / (grid.Lx * grid.Ly)
@. forcing_spectrum *= ε/ε0 # normalize forcing to inject energy at rate ε
nothing # hide
# We reset of the random number generator for reproducibility
if dev==CPU(); Random.seed!(1234); else; CUDA.seed!(1234); end
nothing # hide
# Next we construct function `calcF!` that computes a forcing realization every timestep.
# First we make sure that if `dev=GPU()`, then `CUDA.rand()` function is called for random
# numbers uniformly distributed between 0 and 1.
random_uniform = dev==CPU() ? rand : CUDA.rand
function calcF!(Fh, sol, t, clock, vars, params, grid)
Fh .= sqrt.(forcing_spectrum) .* exp.(2π * im * random_uniform(eltype(grid), size(sol))) ./ sqrt(clock.dt)
return nothing
end
nothing # hide
# ## Problem setup
# We initialize a `Problem` by providing a set of keyword arguments. Not providing
# a viscosity coefficient ν leads to the module's default value: ν=0. In this
# example numerical instability due to accumulation of enstrophy in high wavenumbers
# is taken care with the `FilteredTimestepper` we picked.
prob = BarotropicQGQL.Problem(dev; nx=n, Lx=L, β=β, μ=μ, dt=dt, stepper=stepper,
calcF=calcF!, stochastic=true)
nothing # hide
# and define some shortcuts.
sol, clock, vars, params, grid = prob.sol, prob.clock, prob.vars, prob.params, prob.grid
x, y = grid.x, grid.y
nothing # hide
# First let's see how a forcing realization looks like. Note that when plotting, we decorate
# the variable to be plotted with `Array()` to make sure it is brought back on the CPU when
# `vars` live on the GPU.
calcF!(vars.Fh, sol, 0.0, clock, vars, params, grid)
heatmap(x, y, Array(irfft(vars.Fh, grid.nx)'),
aspectratio = 1,
c = :balance,
clim = (-8, 8),
xlims = (-grid.Lx/2, grid.Lx/2),
ylims = (-grid.Ly/2, grid.Ly/2),
xticks = -3:3,
yticks = -3:3,
xlabel = "x",
ylabel = "y",
title = "a forcing realization",
framestyle = :box)
# ## Setting initial conditions
# Our initial condition is simply fluid at rest.
BarotropicQGQL.set_zeta!(prob, ArrayType(dev)(zeros(grid.nx, grid.ny)))
nothing # hide
# ## Diagnostics
# Create Diagnostics -- `energy` and `enstrophy` are functions imported at the top.
E = Diagnostic(BarotropicQGQL.energy, prob; nsteps=nsteps)
Z = Diagnostic(BarotropicQGQL.enstrophy, prob; nsteps=nsteps)
nothing # hide
# We can also define our custom diagnostics via functions.
function zetaMean(prob)
sol = prob.sol
sol[1, :]
end
zMean = Diagnostic(zetaMean, prob; nsteps=nsteps, freq=10) # the zonal-mean vorticity
nothing # hide
# We combile all diags in a list.
diags = [E, Z, zMean] # A list of Diagnostics types passed to "stepforward!" will be updated every timestep.
nothing # hide
# ## Output
# We choose folder for outputing `.jld2` files and snapshots (`.png` files).
filepath = "."
plotpath = "./plots_forcedbetaQLturb"
plotname = "snapshots"
filename = joinpath(filepath, "forcedbetaQLturb.jld2")
nothing # hide
# Do some basic file management,
if isfile(filename); rm(filename); end
if !isdir(plotpath); mkdir(plotpath); end
nothing # hide
# and then create Output.
get_sol(prob) = sol # extracts the Fourier-transformed solution
get_u(prob) = irfft(im * g.l .* g.invKrsq .* sol, g.nx)
out = Output(prob, filename, (:sol, get_sol), (:u, get_u))
# ## Visualizing the simulation
# We define a function that plots the vorticity and streamfunction fields, the
# corresponding zonal-mean vorticity and zonal-mean zonal velocity and timeseries
# of energy and enstrophy.
function plot_output(prob)
ζ̄, ζ′= prob.vars.Zeta, prob.vars.zeta
ζ = @. ζ̄ + ζ′
ψ̄, ψ′= prob.vars.Psi, prob.vars.psi
ψ = @. ψ̄ + ψ′
ζ̄ₘ = mean(ζ̄, dims=1)'
ūₘ = mean(prob.vars.U, dims=1)'
pζ = heatmap(x, y, Array(ζ'),
aspectratio = 1,
legend = false,
c = :balance,
clim = (-8, 8),
xlims = (-grid.Lx/2, grid.Lx/2),
ylims = (-grid.Ly/2, grid.Ly/2),
xticks = -3:3,
yticks = -3:3,
xlabel = "x",
ylabel = "y",
title = "vorticity ζ=∂v/∂x-∂u/∂y",
framestyle = :box)
pψ = contourf(x, y, Array(ψ'),
levels = -0.32:0.04:0.32,
aspectratio = 1,
linewidth = 1,
legend = false,
clim = (-0.22, 0.22),
c = :viridis,
xlims = (-grid.Lx/2, grid.Lx/2),
ylims = (-grid.Ly/2, grid.Ly/2),
xticks = -3:3,
yticks = -3:3,
xlabel = "x",
ylabel = "y",
title = "streamfunction ψ",
framestyle = :box)
pζm = plot(Array(ζ̄ₘ), y,
legend = false,
linewidth = 2,
alpha = 0.7,
yticks = -3:3,
xlims = (-3, 3),
xlabel = "zonal mean ζ",
ylabel = "y")
plot!(pζm, 0*y, y, linestyle=:dash, linecolor=:black)
pum = plot(Array(ūₘ), y,
legend = false,
linewidth = 2,
alpha = 0.7,
yticks = -3:3,
xlims = (-0.5, 0.5),
xlabel = "zonal mean u",
ylabel = "y")
plot!(pum, 0*y, y, linestyle=:dash, linecolor=:black)
pE = plot(1,
label = "energy",
linewidth = 2,
alpha = 0.7,
xlims = (-0.1, 4.1),
ylims = (0, 0.05),
xlabel = "μt")
pZ = plot(1,
label = "enstrophy",
linecolor = :red,
legend = :bottomright,
linewidth = 2,
alpha = 0.7,
xlims = (-0.1, 4.1),
ylims = (0, 5),
xlabel = "μt")
l = @layout Plots.grid(2, 3)
p = plot(pζ, pζm, pE, pψ, pum, pZ, layout=l, size = (1000, 600))
return p
end
nothing # hide
# ## Time-stepping the `Problem` forward
# We time-step the `Problem` forward in time.
p = plot_output(prob)
startwalltime = time()
anim = @animate for j = 0:round(Int, nsteps / nsubs)
if j % (1000 / nsubs) == 0
cfl = clock.dt * maximum([maximum(vars.u .+ vars.U) / grid.dx, maximum(vars.v) / grid.dy])
log = @sprintf("step: %04d, t: %d, cfl: %.2f, E: %.4f, Q: %.4f, walltime: %.2f min",
clock.step, clock.t, cfl, E.data[E.i], Z.data[Z.i],
(time()-startwalltime)/60)
println(log)
end
p[1][1][:z] = Array(@. vars.zeta + vars.Zeta)
p[1][:title] = "vorticity, μt=" * @sprintf("%.2f", μ * clock.t)
p[4][1][:z] = Array(@. vars.psi + vars.Psi)
p[2][1][:x] = Array(mean(vars.Zeta, dims=1)')
p[5][1][:x] = Array(mean(vars.U, dims=1)')
push!(p[3][1], μ * E.t[E.i], E.data[E.i])
push!(p[6][1], μ * Z.t[Z.i], Z.data[Z.i])
stepforward!(prob, diags, nsubs)
BarotropicQGQL.updatevars!(prob)
end
mp4(anim, "barotropicqgql_betaforced.mp4", fps=18)
# ## Save
# Finally, we can save, e.g., the last snapshot via
# ```julia
# savename = @sprintf("%s_%09d.png", joinpath(plotpath, plotname), clock.step)
# savefig(savename)
# ```