generated from underworld-community/template-project
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathEx_ConvectionSLCN_Cartesian_benchmark.py
754 lines (561 loc) · 24.2 KB
/
Ex_ConvectionSLCN_Cartesian_benchmark.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
# %% [markdown]
# # Constant viscosity convection, Cartesian domain (benchmark)
#
#
#
# This example solves 2D dimensionless isoviscous thermal convection with a Rayleigh number, for comparison with the [Blankenbach et al. (1989) benchmark](https://academic.oup.com/gji/article/98/1/23/622167).
#
# We set up a v, p, T system in which we will solve for a steady-state T field in response to thermal boundary conditions and then use the steady-state T field to compute a stokes flow in response.
#
# %%
import petsc4py
from petsc4py import PETSc
import underworld3 as uw
from underworld3.systems import Stokes
from underworld3 import function
import os
import numpy as np
import sympy
from copy import deepcopy
# %% [markdown]
# ### Set parameters to use
# %%
Ra = 1e4 #### Rayleigh number
k = 1.0 #### diffusivity
boxLength = 1.0
boxHeight = 1.0
tempMin = 0.
tempMax = 1.
viscosity = 1
res= 16 ### x and y res of box
nsteps = 5 ### maximum number of time steps to run the first model
epsilon_lr = 1e-8 ### criteria for early stopping; relative change of the Vrms in between iterations
##########
# parameters needed for saving checkpoints
# can set outdir to None if you don't want to save anything
outDir = "./output/convection_16/"
save_every = 10
#
infile = None # set infile to a value if there's a checkpoint from a previous run that you want to start from
# example infile settings:
# infile = outfile # will read outfile, but this file will be overwritten at the end of this run
# infile = outdir + "/convection_16" # file is that of 16 x 16 mesh
prev_res = None # if infile is not None, then this should be set to the previous model resolution
os.makedirs(outDir, exist_ok = True)
# %% [markdown]
# ### Create mesh and variables
# %%
meshbox = uw.meshing.UnstructuredSimplexBox(
minCoords=(0.0, 0.0),
maxCoords=(boxLength, boxHeight),
cellSize=1.0 /res,
qdegree = 3
)
# meshbox = uw.meshing.StructuredQuadBox(minCoords=(0.0, 0.0), maxCoords=(boxLength, boxHeight), elementRes=(res,res), qdegree = 3)
# %%
# visualise the mesh if in a notebook / serial
if uw.mpi.size == 1:
import numpy as np
import pyvista as pv
import vtk
pv.global_theme.background = "white"
pv.global_theme.window_size = [750, 750]
pv.global_theme.antialiasing = True
pv.global_theme.jupyter_backend = "panel"
pv.global_theme.smooth_shading = True
pv.global_theme.camera["viewup"] = [0.0, 1.0, 0.0]
pv.global_theme.camera["position"] = [0.0, 0.0, -5.0]
pv.global_theme.show_edges = True
pv.global_theme.axes.show = True
meshbox.vtk(outDir+"Convection_mesh.vtk")
pvmesh = pv.read(outDir+"Convection_mesh.vtk")
pl = pv.Plotter()
# pl.add_mesh(pvmesh,'Black', 'wireframe', opacity=0.5)
pl.add_mesh(pvmesh, edge_color="Black", show_edges=True)
pl.show(cpos="xy")
# %%
v_soln = uw.discretisation.MeshVariable("U", meshbox, meshbox.dim, degree=2) # degree = 2
p_soln = uw.discretisation.MeshVariable("P", meshbox, 1, degree=1) # degree = 1
t_soln = uw.discretisation.MeshVariable("T", meshbox, 1, degree=3) # degree = 3
t_0 = uw.discretisation.MeshVariable("T0", meshbox, 1, degree=3) # degree = 3
# additional variable for the gradient
dTdZ = uw.discretisation.MeshVariable(r"\partial T/ \partial \Z", # FIXME: Z should not be a function of x, y, z
meshbox,
1,
degree = 3) # degree = 3
# variable containing stress in the z direction
sigma_zz = uw.discretisation.MeshVariable(r"\sigma_{zz}",
meshbox,
1, degree=2) # degree = 3
x, z = meshbox.X
# projection object to calculate the gradient along Z
dTdZ_calc = uw.systems.Projection(meshbox, dTdZ)
dTdZ_calc.uw_function = t_soln.sym.diff(z)[0]
dTdZ_calc.smoothing = 1.0e-3
dTdZ_calc.petsc_options.delValue("ksp_monitor")
# %% [markdown]
# ### System set-up
# Create solvers and set boundary conditions
# %%
# Create Stokes object
stokes = Stokes(
meshbox,
velocityField=v_soln,
pressureField=p_soln,
solver_name="stokes",
)
# try these
#stokes.petsc_options['pc_type'] = 'lu' # lu if linear
# stokes.petsc_options["snes_max_it"] = 1000
#stokes.tolerance = 1.0e-3
# stokes.petsc_options["snes_atol"] = 1e-6
# stokes.petsc_options["snes_rtol"] = 1e-6
#stokes.petsc_options["ksp_rtol"] = 1e-5 # reduce tolerance to increase speed
# Set solve options here (or remove default values
# stokes.petsc_options.getAll()
#stokes.petsc_options["snes_rtol"] = 1.0e-6
# stokes.petsc_options["fieldsplit_pressure_ksp_monitor"] = None
# stokes.petsc_options["fieldsplit_velocity_ksp_monitor"] = None
# stokes.petsc_options["fieldsplit_pressure_ksp_rtol"] = 1.0e-6
# stokes.petsc_options["fieldsplit_velocity_ksp_rtol"] = 1.0e-2
# stokes.petsc_options.delValue("pc_use_amat")
stokes.constitutive_model = uw.constitutive_models.ViscousFlowModel
stokes.constitutive_model.Parameters.viscosity=viscosity
stokes.saddle_preconditioner = 1.0 / viscosity
sol_vel = sympy.Matrix([0., 0.])
# Free-slip boundary conditions
stokes.add_dirichlet_bc(sol_vel, "Left", [0])
stokes.add_dirichlet_bc(sol_vel, "Right", [0])
stokes.add_dirichlet_bc(sol_vel, "Top", [1])
stokes.add_dirichlet_bc(sol_vel, "Bottom", [1])
#### buoyancy_force = rho0 * (1 + (beta * deltaP) - (alpha * deltaT)) * gravity
# buoyancy_force = (1 * (1. - (1 * (t_soln.sym[0] - tempMin)))) * -1
buoyancy_force = Ra * t_soln.sym[0]
stokes.bodyforce = sympy.Matrix([0, buoyancy_force])
# %%
# Create adv_diff object
adv_diff = uw.systems.AdvDiffusionSLCN(
meshbox,
u_Field=t_soln,
V_fn=v_soln,
solver_name="adv_diff",
)
adv_diff.constitutive_model = uw.constitutive_models.DiffusionModel
adv_diff.constitutive_model.Parameters.diffusivity = k
adv_diff.theta = 0.5
# Dirichlet boundary conditions for temperature
adv_diff.add_dirichlet_bc(1.0, "Bottom")
adv_diff.add_dirichlet_bc(0.0, "Top")
adv_diff.petsc_options["pc_gamg_agg_nsmooths"] = 5
# %% [markdown]
# ### Set initial temperature field
#
# The initial temperature field is set to a sinusoidal perturbation.
# %%
import math, sympy
if infile is None:
pertStrength = 0.1
deltaTemp = tempMax - tempMin
with meshbox.access(t_soln, t_0):
t_soln.data[:] = 0.
t_0.data[:] = 0.
with meshbox.access(t_soln):
for index, coord in enumerate(t_soln.coords):
# print(index, coord)
pertCoeff = math.cos( math.pi * coord[0]/boxLength ) * math.sin( math.pi * coord[1]/boxLength )
t_soln.data[index] = tempMin + deltaTemp*(boxHeight - coord[1]) + pertStrength * pertCoeff
t_soln.data[index] = max(tempMin, min(tempMax, t_soln.data[index]))
with meshbox.access(t_soln, t_0):
t_0.data[:,0] = t_soln.data[:,0]
else:
meshbox_prev = uw.meshing.UnstructuredSimplexBox(
minCoords=(0.0, 0.0),
maxCoords=(boxLength, boxHeight),
cellSize=1.0/prev_res,
qdegree = 3,
regular = False
)
# T should have high degree for it to converge
v_soln_prev = uw.discretisation.MeshVariable("U", meshbox_prev, meshbox_prev.dim, degree=2) # degree = 2
p_soln_prev = uw.discretisation.MeshVariable("P", meshbox_prev, 1, degree=1) # degree = 1
t_soln_prev = uw.discretisation.MeshVariable("T", meshbox_prev, 1, degree=3) # degree = 3
v_soln_prev.load_from_h5_plex_vector(infile + '.U.0.h5')
p_soln_prev.load_from_h5_plex_vector(infile + '.P.0.h5')
t_soln_prev.load_from_h5_plex_vector(infile + '.T.0.h5')
with meshbox.access(v_soln, t_soln, p_soln):
t_soln.data[:, 0] = uw.function.evaluate(t_soln_prev.sym[0], t_soln.coords)
p_soln.data[:, 0] = uw.function.evaluate(p_soln_prev.sym[0], p_soln.coords)
#for velocity, encounters errors when trying to interpolate in the non-zero boundaries of the mesh variables
v_coords = deepcopy(v_soln.coords)
v_soln.data[:] = uw.function.evaluate(v_soln_prev.fn, v_coords)
del meshbox_prev
del v_soln_prev
del p_soln_prev
del t_soln_prev
# %% [markdown]
# ### Some plotting and analysis tools
# %%
# check the mesh if in a notebook / serial
# allows you to visualise the mesh and the mesh variable
'''FIXME: change this so it's better'''
def plotFig(meshbox, s_field, v_field, s_field_name, save_fname = None, with_arrows = False, cmap = "coolwarm"):
"""
s_field - scalar field - corresponds to colors
v_field - vector field - usually the velocity - 2 components
"""
if uw.mpi.size == 1:
import numpy as np
import pyvista as pv
import vtk
pv.global_theme.background = "white"
pv.global_theme.window_size = [500, 500]
pv.global_theme.anti_aliasing = None #"ssaa", "msaa", "fxaa", or None
#pv.global_theme.jupyter_backend = "panel"
pv.global_theme.smooth_shading = True
pvmesh = pv.read(outDir+"Convection_mesh.vtk")
velocity = np.zeros((meshbox.data.shape[0], 3))
velocity[:, 0] = uw.function.evaluate(v_field.sym[0], meshbox.data)
velocity[:, 1] = uw.function.evaluate(v_field.sym[1], meshbox.data)
#pvmesh.point_data["V"] = velocity / 10
points = np.zeros((s_field.coords.shape[0], 3))
points[:, 0] = s_field.coords[:, 0]
points[:, 1] = s_field.coords[:, 1]
point_cloud = pv.PolyData(points)
with meshbox.access():
point_cloud.point_data[s_field_name] = uw.function.evaluate(s_field.fn, points[:, 0:2])
skip = 2
num_row = len(meshbox._centroids[::skip, 0])
cpoints = np.zeros((num_row, 3))
cpoints[:, 0] = meshbox._centroids[::skip, 0]
cpoints[:, 1] = meshbox._centroids[::skip, 1]
cpoint_cloud = pv.PolyData(cpoints)
# pvstream = pvmesh.streamlines_from_source(
# cpoint_cloud,
# vectors="V",
# integrator_type=2,
# integration_direction="forward",
# compute_vorticity=False,
# max_steps=1000,
# surface_streamlines=True,
# )
pl = pv.Plotter()
with meshbox.access():
skip = 2
num_row = len(v_field.coords[::skip, 0:2])
arrow_loc = np.zeros((num_row, 3))
arrow_loc[:, 0:2] = v_field.coords[::skip, 0:2]
arrow_length = np.zeros((num_row, 3))
arrow_length[:, 0] = v_field.data[::skip, 0]
arrow_length[:, 1] = v_field.data[::skip, 1]
pl = pv.Plotter()
#pl.add_mesh(pvmesh,'Gray', 'wireframe')
pl.add_mesh(
pvmesh, cmap=cmap, edge_color="Black",
show_edges=True, use_transparency=False, opacity=0.1,
)
if with_arrows:
pl.add_arrows(arrow_loc, arrow_length, mag=0.04, opacity=0.8)
else:
pl.add_points(point_cloud, cmap=cmap, point_size=18, opacity=0.8)
# pl.add_mesh(pvstream, opacity=0.5)
# pl.add_arrows(arrow_loc2, arrow_length2, mag=1.0e-1)
# pl.add_points(pdata)
pl.show(cpos="xy", jupyter_backend = "panel")
if save_fname is not None:
#pl.save_graphic(save_fname, dpi = 300)
pl.image_scale = 3
pl.screenshot(save_fname)
pvmesh.clear_data()
pvmesh.clear_point_data()
plotFig(meshbox, t_soln, v_soln, "T", save_fname = None, with_arrows = False, cmap = "coolwarm")
# %%
def plot_T_mesh(filename):
if uw.mpi.size == 1:
import numpy as np
import pyvista as pv
import vtk
pv.global_theme.background = "white"
pv.global_theme.window_size = [750, 750]
pv.global_theme.antialiasing = True
pv.global_theme.jupyter_backend = "pythreejs"
pv.global_theme.smooth_shading = True
pv.global_theme.camera["viewup"] = [0.0, 1.0, 0.0]
pv.global_theme.camera["position"] = [0.0, 0.0, 5.0]
pvmesh = pv.read(outDir+"Convection_mesh.vtk")
velocity = np.zeros((meshbox.data.shape[0], 3))
velocity[:, 0] = uw.function.evaluate(v_soln.sym[0], meshbox.data)
velocity[:, 1] = uw.function.evaluate(v_soln.sym[1], meshbox.data)
pvmesh.point_data["V"] = velocity / 333
pvmesh.point_data["T"] = uw.function.evaluate(t_soln.fn, meshbox.data)
# point sources at cell centres
cpoints = np.zeros((meshbox._centroids.shape[0] // 4, 3))
cpoints[:, 0] = meshbox._centroids[::4, 0]
cpoints[:, 1] = meshbox._centroids[::4, 1]
cpoint_cloud = pv.PolyData(cpoints)
pvstream = pvmesh.streamlines_from_source(
cpoint_cloud,
vectors="V",
integrator_type=45,
integration_direction="forward",
compute_vorticity=False,
max_steps=25,
surface_streamlines=True,
)
points = np.zeros((t_soln.coords.shape[0], 3))
points[:, 0] = t_soln.coords[:, 0]
points[:, 1] = t_soln.coords[:, 1]
point_cloud = pv.PolyData(points)
with meshbox.access():
point_cloud.point_data["T"] = t_soln.data.copy()
pl = pv.Plotter()
pl.add_mesh(
pvmesh,
cmap="coolwarm",
edge_color="Gray",
show_edges=True,
scalars="T",
use_transparency=False,
opacity=0.5,
)
pl.add_points(point_cloud, cmap="coolwarm", render_points_as_spheres=False, point_size=10, opacity=0.5)
pl.add_mesh(pvstream, opacity=0.4)
pl.remove_scalar_bar("T")
pl.remove_scalar_bar("V")
pl.screenshot(filename="{}.png".format(filename), window_size=(1280, 1280), return_img=False)
# pl.show()
pl.close()
pvmesh.clear_data()
pvmesh.clear_point_data()
pv.close_all()
# %% [markdown]
# #### RMS velocity
# The root mean squared velocity, $v_{rms}$, is defined as:
#
#
# \begin{aligned}
# v_{rms} = \sqrt{ \frac{ \int_V (\mathbf{v}.\mathbf{v}) dV } {\int_V dV} }
# \end{aligned}
#
# where $\bf{v}$ denotes the velocity field and $V$ is the volume of the box.
# %%
# underworld3 function for calculating the rms velocity
def v_rms(mesh = meshbox, v_solution = v_soln):
# v_soln must be a variable of mesh
v_rms = math.sqrt(uw.maths.Integral(mesh, v_solution.fn.dot(v_solution.fn)).evaluate())
return v_rms
#print(f'initial v_rms = {v_rms()}')
# %% [markdown]
# #### Surface integrals
# Since there is no uw3 function yet to calculate the surface integral, we define one. \
# The surface integral of a function, $f_i(\mathbf{x})$, is approximated as:
#
# \begin{aligned}
# F_i = \int_V f_i(\mathbf{x}) S(\mathbf{x}) dV
# \end{aligned}
#
# With $S(\mathbf{x})$ defined as an un-normalized Gaussian function with the maximum at $z = a$ - the surface we want to evaluate the integral in (e.g. z = 1 for surface integral at the top surface):
#
# \begin{aligned}
# S(\mathbf{x}) = exp \left( \frac{-(z-a)^2}{2\sigma ^2} \right)
# \end{aligned}
#
# In addition, the full-width at half maximum is set to 1/res so the standard deviation, $\sigma$ is calculated as:
#
# \begin{aligned}
# \sigma = \frac{1}{2}\frac{1}{\sqrt{ 2 log 2}}\frac{1}{res}
# \end{aligned}
#
# %%
# function for calculating the surface integral
def surface_integral(mesh, uw_function, mask_fn):
calculator = uw.maths.Integral(mesh, uw_function * mask_fn)
value = calculator.evaluate()
calculator.fn = mask_fn
norm = calculator.evaluate()
integral = value / norm
return integral
''' set-up surface expressions for calculating Nu number '''
# the full width at half maximum is set to 1/res
sdev = 0.5*(1/math.sqrt(2*math.log(2)))*(1/res)
up_surface_defn_fn = sympy.exp(-((z - 1)**2)/(2*sdev**2)) # at z = 1
lw_surface_defn_fn = sympy.exp(-(z**2)/(2*sdev**2)) # at z = 0
# %% [markdown]
# ### Main simulation loop
# %%
t_step = 0
time = 0.
timeVal = np.zeros(nsteps)*np.nan # time values
vrmsVal = np.zeros(nsteps)*np.nan # v_rms values
NuVal = np.zeros(nsteps)*np.nan # Nusselt number values
# %%
#### Convection model / update in time
# NOTE: There is a strange interaction here between the solvers if the zero_guess is set to False
while t_step < nsteps:
vrmsVal[t_step] = v_rms()
timeVal[t_step] = time
stokes.solve(zero_init_guess=True) # originally True
delta_t = 0.5 * stokes.estimate_dt() # originally 0.5
adv_diff.solve(timestep=delta_t, zero_init_guess=False) # originally False
# calculate Nusselt number
dTdZ_calc.solve()
up_int = surface_integral(meshbox, dTdZ.sym[0], up_surface_defn_fn)
lw_int = surface_integral(meshbox, t_soln.sym[0], lw_surface_defn_fn)
Nu = -up_int/lw_int
NuVal[t_step] = -up_int/lw_int
# stats then loop
tstats = t_soln.stats()
if uw.mpi.rank == 0:
print("Timestep {}, dt {}".format(t_step, delta_t))
print(f't_rms = {t_soln.stats()[6]}, v_rms = {vrmsVal[t_step]}, Nu = {NuVal[t_step]}')
''' save mesh variables together with mesh '''
if t_step % save_every == 0:
print("Saving checkpoint for time step: ", t_step)
meshbox.petsc_save_checkpoint(outputPath=outDir, meshVars=[v_soln, p_soln, t_soln, dTdZ, sigma_zz], index=0)
# early stopping criterion
if t_step > 1 and abs((NuVal[t_step] - NuVal[t_step - 1])/NuVal[t_step]) < epsilon_lr:
break
t_step += 1
time += delta_t
# save final mesh variables in the run
meshbox.petsc_save_checkpoint(outputPath=outDir, meshVars=[v_soln, p_soln, t_soln, dTdZ, sigma_zz], index=0)
# %%
if uw.mpi.rank == 0:
import matplotlib.pyplot as plt
# plot how Nu is evolving through time
fig,ax = plt.subplots(dpi = 100)
#ax.hlines(42.865, 0, 2000, linestyle = "--", linewidth = 0.5, color = "gray", label = r"Benchmark $v_{rms}$")
ax.plot(np.arange((~np.isnan(vrmsVal)).sum()),
NuVal[~np.isnan(vrmsVal)],
color = "k",
label = str(res) + " x " + str(res))
ax.legend()
ax.set_xlabel("Time step")
ax.set_ylabel(r"$v_{rms}$", color = "k")
#ax.set_xlim([0, 2000])
#ax.set_ylim([0, 100])
# %%
# Calculate benchmark values
if uw.mpi.rank == 0:
print("RMS velocity at the final time step is {}.".format(v_rms()))
# %% [markdown]
# ### Post-run analysis
#
# **Benchmark values**
# The loop above outputs $v_{rms}$ as a general statistic for the system. For further comparison, the benchmark values for the RMS velocity, $v_{rms}$, Nusselt number, $Nu$, and non-dimensional gradients at the cell corners, $q_1$ and $q_2$, are shown below for different Rayleigh numbers. All benchmark values shown below were determined in Blankenbach *et al.* 1989 by extroplation of numerical results.
#
# | $Ra$ | $v_{rms}$ | $Nu$ | $q_1$ | $q_2$ |
# | ------------- |:-------------:|:-----:|:-----:|:-----:|
# | 10$^4$ | 42.865 | 4.884 | 8.059 | 0.589 |
# | 10$^5$ | 193.215 | 10.535 | 19.079 | 0.723 |
# | 10$^6$ | 833.990 | 21.972 | 45.964 | 0.877 |
# %%
# set-up variables to use in calculating the benchmark values
sigma_zz_fn = stokes.stress[1, 1]
dTdZ_calc.solve() # recalculate gradient of T along Z
# %% [markdown]
# ### Calculate the $Nu$ value
# The Nusselt number is defined as:
#
# \begin{aligned}
# Nu = -h\frac{ \int_{0}^{l} \partial_{z}T(x, z = h) dx} {\int_{0}^{l} T(x, z = 0) dx}
# \end{aligned}
# %%
up_int = surface_integral(meshbox, dTdZ.sym[0], up_surface_defn_fn)
lw_int = surface_integral(meshbox, t_soln.sym[0], lw_surface_defn_fn)
Nu = -up_int/lw_int
if uw.mpi.rank == 0:
print("Calculated value of Nu: {}".format(Nu))
# %% [markdown]
# ### Calculate the non-dimensional gradients at the cell corners, $q_i$
# The non-dimensional temperature gradient at the cell corner, $q_i$, is defined as:
# \begin{aligned}
# q = \frac{-h}{\Delta T} \left( \frac{\partial T}{\partial z} \right)
# \end{aligned}
#
# Note that these values depend on the non-dimensional temperature gradient in the vertical direction, $\frac{\partial T}{\partial z}$.
# These gradients are evaluated at the following points:
#
# $q_1$ at $x=0$, $z=h$; $q_2$ at $x=l$, $z=h$;
#
# $q_3$ at $x=l$, $z=0$; $q_4$ at $x=0$, $z=0$.
# %%
# calculate q values which depend on the temperature gradient fields
q1 = -(boxHeight/(tempMax - tempMin))*uw.function.evaluate(dTdZ.sym[0], np.array([[0., 0.999999*boxHeight]]))[0]
q2 = -(boxHeight/(tempMax - tempMin))*uw.function.evaluate(dTdZ.sym[0], np.array([[0.999999*boxLength, 0.999999*boxHeight]]))[0]
q3 = -(boxHeight/(tempMax - tempMin))*uw.function.evaluate(dTdZ.sym[0], np.array([[0.999999*boxLength, 0.]]))[0]
q4 = -(boxHeight/(tempMax - tempMin))*uw.function.evaluate(dTdZ.sym[0], np.array([[0., 0.]]))[0]
if uw.mpi.rank == 0:
print('Rayleigh number = {0:.1e}'.format(Ra))
print('q1 = {0:.3f}; q2 = {1:.3f}'.format(q1, q2))
print('q3 = {0:.3f}; q4 = {1:.3f}'.format(q3, q4))
# %% [markdown]
# ### Calculate the stress for comparison with benchmark value
#
# The stress field for whole box in dimensionless units (King 2009) is:
# \begin{equation}
# \tau_{ij} = \eta \frac{1}{2} \left[ \frac{\partial v_j}{\partial x_i} + \frac{\partial v_i}{\partial x_j}\right].
# \end{equation}
# For vertical normal stress it becomes:
# \begin{equation}
# \tau_{zz} = \eta \frac{1}{2} \left[ \frac{\partial v_z}{\partial z} + \frac{\partial v_z}{\partial z}\right] = \eta \frac{\partial v_z}{\partial z}.
# \end{equation}
# This is calculated below.
# %%
# projection for the stress in the zz direction
x, y = meshbox.X
stress_calc = uw.systems.Projection(meshbox, sigma_zz)
stress_calc.uw_function = sigma_zz_fn
stress_calc.smoothing = 1.0e-3
stress_calc.petsc_options.delValue("ksp_monitor")
stress_calc.solve()
# %% [markdown]
# The vertical normal stress is dimensionalised as:
#
# $$
# \sigma_{t} = \frac{\eta_0 \kappa}{\rho g h^2}\tau _{zz} \left( x, z=h\right)
# $$
#
# where all constants are defined below.
#
# Finally, we calculate the topography defined using $h = \sigma_{top} / (\rho g)$. The topography of the top boundary calculated in the left and right corners as given in Table 9 of Blankenbach et al 1989 are:
#
# | $Ra$ | $\xi_1$ | $\xi_2$ | $x$ ($\xi = 0$) |
# | ------------- |:-----------:|:--------:|:--------------:|
# | 10$^4$ | 2254.02 | -2903.23 | 0.539372 |
# | 10$^5$ | 1460.99 | -2004.20 | 0.529330 |
# | 10$^6$ | 931.96 | -1283.80 | 0.506490 |
# %%
# subtract the average value for the benchmark since the mean is set to zero
mean_sigma_zz_top = -surface_integral(meshbox,
sigma_zz.sym[0],
up_surface_defn_fn)/boxLength
# %%
# Set parameters in SI units
grav = 10 # m.s^-2
height = 1.e6 # m
rho = 4.0e3 # g.m^-3
kappa = 1.0e-6 # m^2.s^-1
eta0=1.e23
def calculate_topography(coord): # only coord has local scope
sigma_zz_top = -uw.function.evaluate(sigma_zz.sym[0], coord) - mean_sigma_zz_top
# dimensionalise
dim_sigma_zz_top = ((eta0 * kappa) / (height**2)) * sigma_zz_top
topography = dim_sigma_zz_top / (rho * grav)
return topography
# %%
# topography at the top corners
e1 = calculate_topography(np.array([[0, 0.999999*boxHeight]]))
e2 = calculate_topography(np.array([[0.999999*boxLength, 0.999999*boxHeight]]))
# calculate the x-coordinate with zero stress
with meshbox.access():
cond = meshbox.data[:, 1] == meshbox.data[:, 1].max()
up_surface_coords = meshbox.data[cond]
up_surface_coords[:, 1] = 0.999999*up_surface_coords[:, 1]
abs_topo = abs(calculate_topography(up_surface_coords))
min_abs_topo_coord = up_surface_coords[np.where(abs_topo == abs_topo.min())[0]].flatten()
if uw.mpi.rank == 0:
print("Topography [x=0], [x=max] = {0:.2f}, {1:.2f}".format(e1[0], e2[0]))
print("x where topo = 0 is at {0:.6f}".format(min_abs_topo_coord[0]))
# %%
# %%
# %%