gravity_waves_load.py 14.6 KB
Newer Older
blaise's avatar
blaise committed
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
from extrude import *
from dgpy import *
from math import *
import time, os, sys
import gmshPartition
from scipy import interpolate
import scipy
try :
    import cPickle as pickle
except:
    import pickle
from partitionThenExtrude import *
#### Physical constants ###

minOrder=3
maxOrder=3
minConv=3
maxConv=3
convType = 'space' #Can be either 'time' or 'space'
meshSplitForTimeConv = 4
Rd=287.05
Cp=1005.0
Cv=Cp-Rd
gamma=Cp/Cv
p0=1.0e5
g=9.80665
#TEST CASE
T0=250
N=sqrt(g*g/(Cp*T0))
theta0=T0
U=20.0
dT=1.0e-4
H=10000
delta=g/(Rd*T0)

hmult=80
loadRef=True

d=5000*hmult
xc=-50000*hmult
dimension=2

###########################
#### Begin and end time ###
Ti=0
Tf=30*60*hmult*1.01
###########################


def hydrostaticState(z) :
  THs = T0 
  pHs = p0 * exp(-delta*z) 
  thetaHs = THs*(p0/pHs)**(Rd/Cp)
  rho0 = p0 * delta / g
  rhoHs = rho0 * exp(-delta*z)
  return rhoHs,thetaHs
def initialCondition(FCT,  XYZ) :
    for i in range (0,XYZ.size1()) :
        x=XYZ(i,0)
        z=XYZ(i,1)
        rhoHs,thetaHs = hydrostaticState(z)

        Tb= dT * exp(-((x-xc)**2)/(d*d))*sin(pi*z/H)        
        rho0 = p0 / (T0*Rd)
        rhob = rho0 * (-Tb/T0)
        rhoPert = rhoHs + exp(-0.5*delta*z)*rhob

        Tpert = T0 + exp(0.5*delta*z)*Tb
        pPert = p0 * exp(-delta*z) #Only background state
        thetaPert = Tpert*(p0/pPert)**(Rd/Cp)
        FCT.set(i,0,rhoPert-rhoHs)
        FCT.set(i,1,U*rhoPert)
        FCT.set(i,2,0)
        FCT.set(i,3,rhoPert*thetaPert-rhoHs*thetaHs)
def getError(FCT, ref, numerical) :
  for i in range(FCT.size1()):
    for j in range(FCT.size2()):
      FCT.set(i,j,(ref(i,j)-numerical(i,j))**2)
def getErrorNonSquare(FCT, ref, numerical) :
  for i in range(FCT.size1()):
    for j in range(FCT.size2()):
      FCT.set(i,j,(ref(i,j)-numerical(i,j)))

def getSquare(FCT, fields) :
  for i in range(FCT.size1()):
    for j in range(FCT.size2()):
        FCT.set(i,j,fields(i,j)**2)

timeIters = [DG_ERK_EULER,DG_ERK_22,DG_ERK_33,DG_ERK_44,DG_ERK_44] 

for order in range(minOrder,maxOrder+1):
  if (Msg.GetCommRank()==0 and os.path.isdir('convergence') == False):
    os.makedirs('convergence')
  Msg.Barrier()
  convOutFile = open('convergence/convData_p'+str(order),'w')
  convOutFile.close()
  
  for iConv in range (minConv,maxConv+1) :
    if (Msg.GetCommRank()==0):
      print("Convergence i = %i"%iConv)
      lineModel = GModel()
      lineModel.load("line.geo")
      lineModel.mesh(1)
      
      if (convType == 'space'):
        nbSplit = iConv
      else:
        if (convType == 'time'):
          nbSplit = meshSplitForTimeConv-1
        else:
          Msg.Error('convType should either be ""space"" or ""time""')
      
      for jConv in range (1,nbSplit+1):
        lineModel.refineMesh(1)
      lineModel.save("line.msh")
      partitionThenExtrude(Msg.GetCommSize(),nbSplit,hmult)
      
    Msg.Barrier()
    expDir = 'convergence/output_p'+str(order)+convType+str(iConv)
    model = GModel()
    name='line'
    if Msg.GetCommSize()>1:
      partStr='_part_%i' % Msg.GetCommSize()
    else:
      partStr=''
    model.load(name + partStr + '_2d_XY_periodic.msh')
  
    groups = dgGroupCollection(model, dimension, order)
    groups.splitGroupsByPhysicalTag();
    groupsH = dgGroupCollection.newByTag(model, dimension-1, order, ["bottom_domain"])
    extrusion = dgExtrusion(groups, groupsH, ["bottom_domain"], False)
    groups.splitFaceGroupsByOrientation(extrusion) 
  
  
    claw = dgEulerAtmLaw(dimension)
    solution = dgDofContainer(groups, claw.getNbFields())
    XYZ = groups.getFunctionCoordinates()
  
    initF=functionPython(4, initialCondition, [XYZ])
    solution.L2Projection(initF)
  
                
    def rhoHydrostatic(FCT,  XYZ) :
        for i in range (0,XYZ.size1()) :
            z=XYZ(i,1)
            rhoHs,thetaHs = hydrostaticState(z)
            FCT.set(i,0,rhoHs)
    
    def rhoThetaHydrostatic(FCT,  XYZ) :
        for i in range (0,XYZ.size1()) :
            z=XYZ(i,1)
            rhoHs,thetaHs = hydrostaticState(z)
            FCT.set(i,0,rhoHs*thetaHs)
            
    def getVelocity(FCT, sol, XYZ) :
        for i in range (0,sol.size1()) :
            z=XYZ(i,1)
            rhoHs,thetaHs = hydrostaticState(z)
            rho=rhoHs+sol(i,0)
            FCT.set(i,0,sol(i,1)/rho)
            FCT.set(i,1,sol(i,2)/rho)
            FCT.set(i,2,0)
    
    def getRhop(FCT, sol) :
        for i in range (0,sol.size1()) :
            FCT.set(i,0,sol(i,0))
    
    def getpp(FCT, sol, XYZ) :
        for i in range (0,sol.size1()) :
            z=XYZ(i,1)
            rhoHs,thetaHs = hydrostaticState(z)
            rho=rhoHs+sol(i,0)
            rhoTheta = rhoHs*thetaHs+sol(i,3)
            pHs=p0*(rhoHs*thetaHs*Rd/p0)**gamma
            p=p0*(rhoTheta*Rd/p0)**gamma
            FCT.set(i,0,p-pHs)
    
    def getpHs(FCT, sol, XYZ) :
        for i in range (0,sol.size1()) :
            z=XYZ(i,1)
            rhoHs,thetaHs = hydrostaticState(z)
            pHs=p0*(rhoHs*thetaHs*Rd/p0)**gamma
            FCT.set(i,0,pHs)
    
    def getp(FCT, sol, XYZ) :
        for i in range (0,sol.size1()) :
            z=XYZ(i,1)
            rhoHs,thetaHs = hydrostaticState(z)
            rhoTheta = rhoHs*thetaHs+sol(i,3)
            p=p0*(rhoTheta*Rd/p0)**gamma
            FCT.set(i,0,p)
    
    def getThetap(FCT, sol, XYZ) :
        for i in range (0,sol.size1()) :
            z=XYZ(i,1)
            rhoHs,thetaHs = hydrostaticState(z)
            rho=rhoHs+sol(i,0)
            FCT.set(i,0,(sol(i,3)+(rhoHs*thetaHs))/rho-thetaHs)
    
    uv=functionPython(3, getVelocity, [solution.getFunction(), XYZ])
    rhop=functionPython(1, getRhop, [solution.getFunction()])
    pHs=functionPython(1, getpHs, [solution.getFunction(), XYZ])
    p=functionPython(1, getp, [solution.getFunction(), XYZ])
    pp=functionPython(1, getpp, [solution.getFunction(), XYZ])
    thetap=functionPython(1, getThetap, [solution.getFunction(), XYZ])
    
    
    rhoHs = dgDofContainer(groups, 1)
    rhoHs.interpolate(functionPython(1, rhoHydrostatic, [XYZ]))
    rhoThetaHs = dgDofContainer(groups, 1)
    rhoThetaHs.interpolate(functionPython(1, rhoThetaHydrostatic, [XYZ]))

    if loadRef:
        refModel = GModel()
        refModel.load("refMesh.msh")
        refGroups = dgGroupCollection(refModel, dimension, order)
        refSol =dgDofContainer(refGroups,claw.getNbFields())    
        refXYZ = refGroups.getFunctionCoordinates()
        solInRefMesh = dgDofContainer(refGroups,claw.getNbFields())
        projToRef = dgMesh2MeshProjection(solution,solInRefMesh);
        thetapRef=functionPython(1, getThetap, [refSol.getFunction(), refXYZ])
        rhoHsRef = dgDofContainer(refGroups, 1)
        rhoHsRef.interpolate(functionPython(1, rhoHydrostatic, [refXYZ]))
        rhoThetaHsRef = dgDofContainer(refGroups, 1)
        rhoThetaHsRef.interpolate(functionPython(1, rhoThetaHydrostatic, [refXYZ]))
        error = functionPython(4, getError, [refSol.getFunction(), solInRefMesh.getFunction()])
        solRefSq=functionPython(4, getSquare, [refSol.getFunction()])
        integratorError = dgFunctionIntegrator(refGroups, error)
        intErr = fullMatrixDouble(4,1)
        integratorRefSq = dgFunctionIntegrator(refGroups, solRefSq)
        intRefSq = fullMatrixDouble(4,1)   

    
    claw.setHydrostaticState(rhoHs,rhoThetaHs)
    claw.setPhysicalConstants(gamma,Rd,p0,g)

    trms = claw.getActiveTerms();
    trms.setAdvV(True);
    trms.setAdvT(True);
    trms.setPGrad(True);
    trms.setVDiv(True);
    trms.setCor(True);
    trms.setGrav(True);
    trms.setDiff(False);
    trms.setLax(True);
    
    
    c = sqrt(gamma * p0 / 1)
    #nuStab = dgJumpDiffusion(groups, 3, 2 * order + 1, c, 200)
    #nu = nuStab.diffusivity()
    #nuStab.apply(solution)
    #claw.setNuFactor(nu)
    
    boundaryWall = claw.newBoundaryWall()
    claw.addBoundaryCondition('bottom_domain', boundaryWall)
    claw.addBoundaryCondition('top_domain', boundaryWall)
    
    #We need to use a dof container to restrict the initial condition
    # (=boundary condition) to the discretization space
    #initDof = dgDofContainer(groups, 4)
    #initDof.interpolate(initF)
    #outsideBoundary = claw.newOutsideValueBoundary("",initDof.getFunction())
    #claw.addBoundaryCondition('left', outsideBoundary)
    #claw.addBoundaryCondition('right', outsideBoundary)
    
    #zero=claw.new0FluxBoundary()
    #claw.addBoundaryCondition('bottom', zero)
    #claw.addBoundaryCondition('top', zero)
    #claw.addBoundaryCondition('left', zero)
    #claw.addBoundaryCondition('right', zero)
    
    if (convType == 'space'):
      timeIter = dgERK(claw, None, timeIters[min(order,len(timeIters))])
    else:
      filterMode = FILTER_LINEARVERTICAL
      claw.setFilterMode(filterMode)
      if (filterMode == FILTER_LINEARVERTICAL):
        petscIm = dgLinearSystemExtrusion(claw, groups, extrusion)
        petscIm.setParameter("petscOptions",  "-ksp_type preonly -pc_type lu")
      else:
        petscIm = linearSystemPETScBlockDouble()
        if (Msg.GetCommSize() > 1):
          petscIm.setParameter("petscOptions",  "-ksp_type preonly -pc_type lu -pc_factor_mat_solver_package mumps")
        else:
          petscIm.setParameter("petscOptions",  "-ksp_type preonly -pc_type lu")
      dofIm = dgDofManager.newDGBlock(groups, claw.getNbFields(), petscIm)
#      timeIter = dgERK(claw, None, timeIters[min(order,len(timeIters))])
      timeIter = dgIMEXRK(claw, dofIm, 2)     #timeorder
    #claw.setFilterMode(FILTER_LINEAR);
    ##petscIm = dgLinearSystemExtrusion(claw, groups, extrusion)
    #
    #petscIm = linearSystemPETScBlockDouble()
    ##petscIm.setParameter("petscOptions",  "-ksp_type preonly -pc_type lu -pc_factor_mat_solver_package mumps")
    ##petscIm.setParameter("petscOptions",  "-ksp_atol 0 -ksp_rtol 1e-20")
    #dofIm = dgDofManager.newDGBlock(groups, claw.getNbFields(), petscIm)
    ##timeIter = dgIMEXDIMSIM(claw, dofIm, 2)     #timeorder
    ##timeIter = dgIMEXTSRK(claw, dofIm, 4)     #timeorder
    #timeIter = dgIMEXRK(claw, dofIm, 2)     #timeorder
    ##timeIter = dgDIRK(claw, dofIm, 2)     #timeorder
    #timeIter.getNewton().setAtol(1.e-5) #ATol
    #timeIter.getNewton().setRtol(1.e-8) #Rtol
    #timeIter.getNewton().setVerb(3)     #Verbosity
    
    if (convType == 'space'):
      dt=claw.getMinOfTimeSteps(solution, extrusion)*1.5
    else:
      dt=claw.getMinOfTimeSteps(solution, extrusion)*2
    #Constant time step to avoid temporal convergence effects
#    dt=claw.getMinOfTimeSteps(solution, extrusion)/(2**(maxConv-iConv))

  #  dt=0.01
    #dt=100
    #Modify the time step such that if corresponds to the ref solution exports
    #In minutes
    interv=10.0
    interv=interv*60.0*hmult
    nbStepInInterv = floor(interv/dt)
    print (interv, nbStepInInterv)
    dt=interv/nbStepInInterv

    if (convType == 'time'):
      dt = dt/2**iConv
    
    
    nbSteps = int(ceil(Tf/dt))

    if (Msg.GetCommRank()==0):
        print("Time step:",dt)
    
    #Export data
    def getExp(FCT, sol, thetap, rhoHs, rhoThetaHs) :
        for i in range (0,FCT.size1()) :
            FCT.set(i,0,sol(i,0))
            FCT.set(i,1,sol(i,1))
            FCT.set(i,2,sol(i,2))
            FCT.set(i,3,sol(i,3))
            FCT.set(i,4,thetap(i,0))
            FCT.set(i,5,rhoHs(i,0))
            FCT.set(i,6,rhoThetaHs(i,0))
    Exp=functionPython(7, getExp, [solution.getFunction(), thetap, rhoHs.getFunction(), rhoThetaHs.getFunction()])
    nCompExp=[1,2,1,1,1,1]
    namesExp=["rhop","rhouv","rhothetap","thetap","rhoHs","rhoThetaHs"]

    if loadRef:
        ExpRef=functionPython(7, getExp, [refSol.getFunction(), thetapRef, rhoHsRef.getFunction(), rhoThetaHsRef.getFunction()])
        errorNS = functionPython(4, getErrorNonSquare, [refSol.getFunction(), solInRefMesh.getFunction()])
#        errorExpNS = functionPython(7, getErrorNonSquare, [Exp, ExpRef])
    sBV = 2.0/3*(order+1.0)
    muBV = 4.88281250000000e-05
    filterBV = dgFilterBoydVandeven(groups, "", sBV, muBV,True,True)
    
    
    t=Ti
    # starter for IMEX TSRK
    #t=timeIter.starter(solution,dt,t,3)
    # starter for IMEX DIMSIM
    #timeIter.starter(solution,dt,dt,t,3)

    n_export=0
    timeStart=time.clock();
    for i in range(0,nbSteps-1):
        t=dt*i #More accurate, but dt cannot be changed
        if (t%interv/interv < 1e-11 or (interv-t%interv)/interv < 1e-11):
            solution.exportFunctionVtk(Exp,expDir+'/export', t, i,"solution",nCompExp,namesExp)
            if loadRef:
366
                refSol.importIdx("refSol"+str(t)+"/refSol"+str(t)+".idx")
blaise's avatar
blaise committed
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
                Msg.Barrier()
                projToRef.projectFromTo(solution,solInRefMesh)
                integratorError.compute(intErr)
                integratorRefSq.compute(intRefSq)
                if (Msg.GetCommRank()==0):
                    print("Rel Error on rhop: "+str(intErr(0,0)/intRefSq(0,0)))
                    print("Rel Error on rhou: "+str(intErr(1,0)/intRefSq(1,0)))
                    if (i!=0):
                        print("Rel error on rhow: "+str(intErr(2,0)/intRefSq(2,0)))
                    print("Rel Error on rhothetap: "+str(intErr(3,0)/intRefSq(3,0)))
                    convOutFile = open('convergence/convData_p'+str(order),'a')
                    if (i!=0):
                        convOutFile.write("%i %e %e %e %e %e\n" % (iConv, t, intErr(0,0)/intRefSq(0,0),intErr(1,0)/intRefSq(1,0),intErr(2,0)/intRefSq(2,0),intErr(3,0)/intRefSq(3,0)))
                    convOutFile.close()
                refSol.exportFunctionVtk(ExpRef,expDir+'/ref', t, i,"solution",nCompExp,namesExp)
                refSol.exportFunctionVtk(errorNS,expDir+'/error', t, i,"solution",[1,1,1,1],["rhop","rhou","rhov","rhothetap"])
#                refSol.exportFunctionVtk(errorExpNS,expDir+'/errorExp', t, i,"solution",nCompExp,namesExp)
                refSol.exportFunctionVtk(solInRefMesh.getFunction(),expDir+'/solInRef', t, i,"solution",[1,1,1,1],["rhop","rhou","rhov","rhothetap"])
                refSol.exportFunctionVtk(refSol.getFunction(),expDir+'/refSol', t, i,"solution",[1,1,1,1],["rhop","rhou","rhov","rhothetap"])
                solution.exportFunctionVtk(solution.getFunction(),expDir+'/solution', t, i,"solution",[1,1,1,1],["rhop","rhou","rhov","rhothetap"])
            if (Msg.GetCommRank()==0):
                print('\nWritten! %s %i at time %e and step %i over %i' %(expDir+'/export',n_export,t,i,nbSteps))
                print('Time elapsed: '+str(time.clock()-timeStart))
            n_export=n_export+1
        norm = timeIter.iterate (solution, dt, t)
    #    nuStab.apply(solution);
        filterBV.apply(solution)
        if (Msg.GetCommRank()==0 and i%500==0):
            print('\nTime %e and step %i over %i' %(t,i,nbSteps))
            sys.stdout.flush()
    print ('')
    print ('Time elapsed: '+str(time.clock()-timeStart))
Msg.Exit(0)