-
Notifications
You must be signed in to change notification settings - Fork 0
/
convection.py
194 lines (149 loc) · 6.51 KB
/
convection.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
"""
Script to test WNL analysis
Usage:
convection.py [options]
Options:
--Lmax=<Lmax> Lmax resolution for simulation [default: 43]
--Nmax=<Nmax> Nmax resolution for simulation [default: 48]
--Ekman=<Ekman> Ekman number [default: 1e-3]
--Prandtl=<Prandtl> Prandtl number [default: 1]
--beta=<beta> Radius ratio [default: 0.35]
--internal Whether to use internal heating or not
--eps=<eps> How far away from criticaility [default: 0.1]
"""
import numpy as np
import dedalus.public as d3
import os
import h5py
import pandas as pd
from dedalus.extras.flow_tools import GlobalArrayReducer
from mpi4py import MPI
import logging
from docopt import docopt
restart_file=False
comm = MPI.COMM_WORLD
rank = comm.rank
ncpu = comm.size
logger = logging.getLogger(__name__)
log2 = np.log2(ncpu)
args = docopt(__doc__)
# Try to create balanced mesh
# Choose mesh whose factors are most similar in size
factors = [[ncpu//i,i] for i in range(1,int(np.sqrt(ncpu))+1) if np.mod(ncpu,i)==0]
score = np.array([f[1]/f[0] for f in factors])
mesh = factors[np.argmax(score)]
Lmax = int(args['--Lmax'])
Nmax = int(args['--Nmax'])
Ekman = float(args['--Ekman'])
Prandtl = float(args['--Prandtl'])
beta = float(args['--beta'])
internal = args['--internal']
eps = float(args['--eps'])
file_dir = 'data/Ekman_{0:g}_Prandtl_{1:g}_beta_{2:g}_internal_{3:s}'.format(Ekman, Prandtl, beta, str(internal))
data = np.load('{0:s}/results.npz'.format(file_dir))
idx = np.argmin(data['Ra'])
mc = data['ms'][idx]
Rayleigh = data['Ra'][idx]*(1+eps**2)
stop_time = 100000
r_outer = 1/(1-beta)
r_inner = r_outer - 1
radii = (r_inner, r_outer)
c = d3.SphericalCoordinates('phi', 'theta', 'r')
d = d3.Distributor((c,), mesh=mesh, dtype=np.float64)
b = d3.ShellBasis(c, (2*(Lmax+1),Lmax+1,Nmax+1), radii=radii, dealias=(3/2,3/2,3/2),dtype=np.float64)
s2_basis = b.S2_basis()
bk1 = b.clone_with(k=1)
phi, theta, r = d.local_grids(b)
u = d.VectorField(c,name='u', bases=b)
p = d.Field(name='p', bases=bk1)
φ = d.Field(name='φ', bases=bk1)
T = d.Field(name='T', bases=b)
tau_u1 = d.VectorField(c,name='tau_u1', bases=s2_basis)
tau_u2 = d.VectorField(c,name='tau_u2', bases=s2_basis)
tau_p = d.Field(name='tau_p')
tau_phi = d.Field(name='tau_phi')
tau_T1 = d.Field(name='tau_T1', bases=s2_basis)
tau_T2 = d.Field(name='tau_T2', bases=s2_basis)
ez = d.VectorField(c,name='ez', bases=b)
ez['g'][1] = -np.sin(theta)
ez['g'][2] = np.cos(theta)
ro_vec = d.VectorField(c,name='r_vec', bases=b.radial_basis)
ro_vec['g'][2] = r/r_outer
## initial condition (Load from file) ##
d_complex = d3.Distributor((c,), mesh=mesh, dtype=np.complex128)
b_complex = d3.ShellBasis(c, (2*(Lmax+1), Lmax+1, Nmax+1), radii=radii, dealias=(3/2,3/2,3/2), dtype=np.complex128)
uA = d_complex.VectorField(c,name='um', bases=b_complex.meridional_basis)
TA = d_complex.Field(name='Tm', bases=b_complex.meridional_basis)
with h5py.File('{0:s}/eigenvector/eigenvector_s1.h5'.format(file_dir), mode='r') as file:
uA.load_from_hdf5(file, -1)
TA.load_from_hdf5(file, -1)
uA.change_scales(1)
TA.change_scales(1)
u['g'] = (uA['g']*np.exp(1j*mc*phi)).real
T['g'] = (TA['g']*np.exp(1j*mc*phi)).real
df = pd.read_csv('{0:s}/wnl_coefficients.csv'.format(file_dir), index_col=0)
chi = np.complex128(df['chi'])[0]
gamma = np.complex128(df['gamma_AA'])[0] + np.complex128(df['gamma_AAbar'])[0]
predicted_amplitude = 4*eps**2*chi.real/gamma.real
logger.info('Predicted amplitude = {0:g}'.format(predicted_amplitude))
reducer = GlobalArrayReducer(MPI.COMM_WORLD)
norm = reducer.global_max((0.5*d3.integ(u@u)).evaluate()['g'])
u['g'] /= np.sqrt(norm/(0.1*predicted_amplitude))
T['g'] /= np.sqrt(norm/(0.1*predicted_amplitude))
# Conducting state
if internal:
logger.info("Using internal heating")
T['g'] += -(1-beta)/(1+beta)*r**2 + (1-beta)/(1+beta)*r_outer**2
else:
logger.info("Using differential heating")
T['g'] += r_inner*r_outer/r - r_inner
norm = reducer.global_max((0.5*d3.integ(u@u)).evaluate()['g'])
logger.info('norm = %g' % norm.real )
########################################
rvec = d.VectorField(c, name='r_er', bases=b.radial_basis)
rvec['g'][2] = r
lift = lambda A, n: d3.Lift(A, bk1, n)
grad_u = d3.grad(u) + rvec*lift(tau_u1,-1) # First-order reduction
grad_T = d3.grad(T) + rvec*lift(tau_T1,-1) # First-order reduction
# Hydro only
problem = d3.IVP([p, u, T, tau_u1, tau_u2, tau_T1, tau_T2, tau_p], namespace=locals())
problem.add_equation("trace(grad_u) + tau_p = 0")
problem.add_equation("dt(u) - Ekman*div(grad_u) + grad(p) + lift(tau_u2,-1) = cross(u, curl(u) + 2*ez) + Rayleigh*Ekman*ro_vec*T")
problem.add_equation("dt(T) - Ekman/Prandtl*div(grad_T) + lift(tau_T2,-1) = - dot(u,grad(T))")
problem.add_equation("integ(p)=0")
problem.add_equation("u(r=r_inner) = 0")
problem.add_equation("T(r=r_inner) = 1")
problem.add_equation("u(r=r_outer) = 0")
problem.add_equation("T(r=r_outer) = 0")
# Solver
solver = problem.build_solver(d3.SBDF4)
logger.info("Problem built")
solver.stop_sim_time = stop_time
flow = d3.GlobalFlowProperty(solver, cadence=100)
flow.add_property(d3.dot(u,u)/2., name='KE')
max_dt = 0.1
CFL = d3.CFL(solver, initial_dt=max_dt, cadence=10, safety=0.8, threshold=0.1,
max_change=1.5, min_change=0.5, max_dt=max_dt)
CFL.add_velocity(u)
file_name='verification_eps_{0:.2f}'.format(eps)
if MPI.COMM_WORLD.rank == 0:
if not os.path.exists(os.path.join(file_dir, file_name)):
os.mkdir(os.path.join(file_dir, file_name))
timeseries = solver.evaluator.add_file_handler(os.path.join(file_dir, file_name,'timeseries'), sim_dt=2e-7)
timeseries.add_task(d3.integ(d3.dot(u,u))/2, name='KE')
good_solution = True
# Main loop
try:
logger.info('Starting main loop')
while solver.proceed and good_solution:
timestep = CFL.compute_timestep()
solver.step(timestep)
if (solver.iteration-1) % 100 == 0:
KE = flow.volume_integral('KE')
good_solution = np.isfinite(KE)
logger.info('Iteration=%i, Time=%e, dt=%e, KE=%g' %(solver.iteration, solver.sim_time, timestep, KE))
except:
logger.error('Exception raised, triggering end of main loop.')
raise
finally:
solver.log_stats()