source: codes/icosagcm/devel/Python/src/unstructured.pyx @ 642

Last change on this file since 642 was 642, checked in by dubos, 7 years ago

devel/unstructured : bubble test case with Fortran time stepping

File size: 14.3 KB
Line 
1import time
2import math
3import numpy as np
4import dynamico.wrap as wrap
5from ctypes import c_void_p, c_int, c_double, c_bool
6
7from libc.time cimport time as ctime, time_t
8cimport numpy as np
9
10#------------- direct Cython interface to DYNAMICO routines -------------#
11
12cdef enum: max_nb_stage=5
13cdef extern :
14    cdef double tauj[max_nb_stage]
15    cdef double cslj[max_nb_stage][max_nb_stage]
16    cdef double cflj[max_nb_stage][max_nb_stage]
17    cdef int nb_stage[1]
18
19cdef extern from "functions.h":
20     cdef void dynamico_ARK_step(int nstep,
21                                 double *mass_col, double *rhodz, double *theta_rhodz, 
22                                 double *u, double *geopot, double *w,
23                                 double *theta, double *ps, double *pk, double *hflux, double *qv,
24                                 double *dmass_col, double *drhodz, double *dtheta_rhodz,
25                                 double *du_fast, double *du_slow,
26                                 double *dPhi_fast, double *dPhi_slow, 
27                                 double *dW_fast, double *dW_slow)
28     cdef void dynamico_init_params()
29     cpdef void dynamico_setup_xios()
30     cpdef void dynamico_xios_set_timestep(double)
31     cpdef void dynamico_xios_update_calendar(int)
32
33#------------- import and wrap DYNAMICO routines -------------#
34
35ker=wrap.Struct() # store imported fun X as funs.X
36
37check_args = False # use True instead of False for debugging, probably with some overhead
38
39try:   
40    kernels = wrap.SharedLib(vars(ker), 'libicosa.so', check_args=check_args) 
41    setvar, setvars, getvar, getvars = kernels.setvar, kernels.setvars, kernels.getvar, kernels.getvars
42except OSError:
43    print """
44Unable to load shared library 'libkernels.so' !
45    """
46    raise
47
48# providing a full prototype enables type-checking when calling
49# if a number n is present in the prototype, the previous type is repeated n times
50kernels.import_funs([
51                     ['dynamico_setup_xios',None],
52                     ['dynamico_xios_set_timestep',c_double],
53                     ['dynamico_xios_update_calendar',c_int],
54                     ['dynamico_init_mesh',c_void_p,13],
55                     ['dynamico_init_metric', c_void_p,6],
56                     ['dynamico_init_hybrid', c_void_p,3],
57                     ['dynamico_caldyn_unstructured', c_double, c_void_p,20],
58                     ['dynamico_partition_graph', c_int,2, c_void_p,3, c_int, c_void_p],
59                     ])
60
61# set/get global variables
62eta_mass,eta_lag=(1,2)
63thermo_theta,thermo_entropy,thermo_moist,thermo_boussinesq=(1,2,3,4)
64
65kernels.addvars(
66    c_bool,'hydrostatic','debug_hevi_solver',
67    c_int,'llm','nqdyn','primal_num','max_primal_deg',
68    'dual_num','max_dual_deg','edge_num','max_trisk_deg',
69    'caldyn_thermo','caldyn_eta','nb_threads',
70    c_double,'elapsed','g', 'ptop', 'cpp', 'cppv',
71    'Rd', 'Rv', 'preff', 'Treff', 'pbot', 'rho_bot', 'Phi_bot')
72
73elapsed=0.
74
75#------------------------ Extension type performing a full ARK time step ----------------------
76
77ctypedef double *dbl_ptr
78cdef dbl_ptr ptr1(double[:] data) : return &data[0]
79cdef dbl_ptr ptr2(double[:,:] data) : return &data[0,0]
80cdef dbl_ptr ptr3(double[:,:,:] data) : return &data[0,0,0]
81cdef dbl_ptr ptr4(double[:,:,:,:] data) : return &data[0,0,0,0]
82cdef dbl_ptr ptr(data):
83    n=data.ndim
84    if n==1 : return ptr1(data)
85    if n==2 : return ptr2(data)
86    if n==3 : return ptr3(data)
87    if n==4 : return ptr4(data)
88    if n>4: raise IndexError
89       
90cdef alloc(dbl_ptr *p, allocator, n=1):
91    data=allocator(n)
92    p[0]=ptr(data)
93    return data
94
95cdef check_ptr(name, dbl_ptr p, np.ndarray data):
96    if p != ptr(data) : print name, 'p <> ptr(data) !!'
97       
98cdef class Caldyn_step:
99    # number of time steps to do at each invocation of advance()
100    cdef int nstep
101    # pointer to allocated arrays
102    cdef dbl_ptr p_mass, p_theta_rhodz, p_u, p_geopot, p_W                   # prognostic
103    cdef dbl_ptr p_mass_col, p_dmass_col, p_ps, p_theta, p_pk, p_hflux, p_qv # diagnostic
104    cdef dbl_ptr p_drhodz, p_dtheta_rhodz, p_du_fast, p_du_slow                # tendencies
105    cdef dbl_ptr p_dPhi_fast, p_dPhi_slow, p_dW_fast, p_dW_slow                # tendencies
106    # allocated arrays, must remain referenced or segfault
107    cdef readonly np.ndarray mass, theta_rhodz, u, geopot, W
108    cdef readonly np.ndarray mass_col, dmass_col, ps, theta, pk, hflux, qv
109    cdef readonly np.ndarray drhodz, dtheta_rhodz, du_fast, du_slow
110    cdef readonly np.ndarray dPhi_fast, dPhi_slow, dW_fast, dW_slow
111
112    def __init__(self,mesh,time_scheme, nstep):
113        self.nstep=nstep
114        #        self.mesh=mesh
115        fps, ftheta, fmass = mesh.field_ps, mesh.field_theta, mesh.field_mass
116        fw, fu, fz = mesh.field_w, mesh.field_u, mesh.field_z
117        # collect coefficients of time scheme
118        cdef double[:]   tauj_ = time_scheme.tauj
119        cdef double[:,:] cslj_ = time_scheme.csjl
120        cdef double[:,:] cflj_ = time_scheme.cfjl
121        ns = time_scheme.nstage
122        nb_stage[0]=ns
123
124        cdef int i,j
125        for i in range(ns):
126            tauj[i]=tauj_[i]
127            for j in range(ns):
128                cslj[i][j]=cslj_[i,j]
129                cflj[i][j]=cflj_[i,j]
130        # allocate arrays, store pointers to avoid overhead when calling dynamico
131        #    prognostic/diagnostic
132        self.ps                       = alloc(&self.p_ps, fps) 
133        self.mass_col, self.dmass_col = alloc(&self.p_mass_col, fps), alloc(&self.p_dmass_col, fps,ns), 
134        self.mass, self.theta_rhodz   = alloc(&self.p_mass, fmass), alloc(&self.p_theta_rhodz, fmass),
135        self.theta, self.pk           = alloc(&self.p_theta, fmass), alloc(&self.p_pk, fmass), 
136        self.geopot, self.W           = alloc(&self.p_geopot, fw), alloc(&self.p_W, fw),
137        self.hflux, self.u            = alloc(&self.p_hflux, fu), alloc(&self.p_u, fu) 
138        self.qv                       = alloc(&self.p_qv,fz)
139        #    tendencies
140        self.drhodz, self.dtheta_rhodz  = alloc(&self.p_drhodz,fmass,ns), alloc(&self.p_dtheta_rhodz,fmass,ns) 
141        self.du_fast, self.du_slow      = alloc(&self.p_du_fast,fu,ns), alloc(&self.p_du_slow,fu,ns)
142        self.dPhi_fast, self.dPhi_slow  = alloc(&self.p_dPhi_fast,fw,ns), alloc(&self.p_dPhi_slow,fw,ns)
143        self.dW_fast, self.dW_slow      = alloc(&self.p_dW_fast,fw,ns), alloc(&self.p_dW_slow,fw,ns)
144    def next(self):
145        #        global elapsed
146        # time1=time.time()
147        dynamico_ARK_step(self.nstep,
148                          self.p_mass_col, self.p_mass, self.p_theta_rhodz,
149                          self.p_u, self.p_geopot, self.p_W,
150                          self.p_theta, self.p_ps, self.p_pk, self.p_hflux, self.p_qv,
151                          self.p_dmass_col, self.p_drhodz, self.p_dtheta_rhodz,
152                          self.p_du_fast, self.p_du_slow,
153                          self.p_dPhi_fast, self.p_dPhi_slow,
154                          self.p_dW_fast, self.p_dW_slow)
155        #time2=time.time()
156        #if time2>time1: elapsed=elapsed+time2-time1
157
158def caldyn_step_TRSW(mesh,time_scheme,nstep):
159    setvars(('hydrostatic','caldyn_thermo','caldyn_eta'),
160            (True,thermo_boussinesq,eta_lag))
161    dynamico_init_params()
162    return Caldyn_step(mesh,time_scheme, nstep)
163def caldyn_step_HPE(mesh,time_scheme,nstep, caldyn_thermo,caldyn_eta, thermo,BC,g):
164    setvars(('hydrostatic','caldyn_thermo','caldyn_eta',
165             'g','ptop','Rd','cpp','preff','Treff'),
166             (True,caldyn_thermo,caldyn_eta,
167              g,BC.ptop,thermo.Rd,thermo.Cpd,thermo.p0,thermo.T0))
168    dynamico_init_params()
169    return Caldyn_step(mesh,time_scheme, nstep)
170def caldyn_step_NH(mesh,time_scheme,nstep, caldyn_thermo, caldyn_eta, thermo,BC,g):
171    setvars(('hydrostatic','caldyn_thermo','caldyn_eta',
172             'g','ptop','Rd','cpp','preff','Treff','pbot','rho_bot'),
173             (False,caldyn_thermo,caldyn_eta,
174              g,BC.ptop,thermo.Rd,thermo.Cpd,thermo.p0,thermo.T0,
175              BC.pbot.max(), BC.rho_bot.max()))
176    dynamico_init_params()
177    return Caldyn_step(mesh,time_scheme, nstep)
178   
179#----------------------------- Base class for dynamics ------------------------
180
181class Caldyn:
182    def __init__(self,mesh):
183        self.mesh=mesh
184        fps, ftheta, fmass = mesh.field_ps, mesh.field_theta, mesh.field_mass
185        fw, fu, fz = mesh.field_w, mesh.field_u, mesh.field_z
186        self.ps, self.ms, self.dms       = fps(), fps(), fps()
187        self.s, self.hs, self.dhs        = ftheta(), ftheta(), ftheta()
188        self.pk, self.berni, self.geopot, self.hflux = fmass(),fmass(),fw(),fu()
189        self.qu, self.qv                 = fu(),fz()
190        self.fmass, self.ftheta, self.fu, self.fw = fmass, ftheta, fu, fw
191    def bwd_fast_slow(self, flow, tau):
192        global elapsed
193        time1=time.time()
194        flow,fast,slow = self._bwd_fast_slow_(flow,tau)
195        time2=time.time()
196        elapsed=elapsed+time2-time1
197        return flow,fast,slow
198
199# when calling caldyn_unstructured, arrays for tendencies must be re-created each time
200# to avoid overwriting in the same memory space when time scheme is multi-stage
201
202#-------------------------- Shallow-water dynamics ---------------------
203
204class Caldyn_RSW(Caldyn):
205    def __init__(self,mesh):
206        Caldyn.__init__(self,mesh)
207        setvars(('hydrostatic','caldyn_thermo','caldyn_eta'),
208                (True,thermo_boussinesq,eta_lag))
209        self.dhs = self.fmass()
210        dynamico_init_params()
211    def _bwd_fast_slow_(self, flow, tau):
212        h,u = flow
213        # h*s = h => uniform buoyancy s=1 => shallow-water
214        dh, du_slow, du_fast, hs, buf = self.fmass(), self.fu(), self.fu(), h.copy(), self.geopot
215        ker.dynamico_caldyn_unstructured(tau, self.ms, h, hs, u, self.geopot, buf,
216                  self.s, self.ps, self.pk, self.hflux, self.qv,
217                  self.dms, dh, self.dhs, du_fast, du_slow,
218                  buf, buf, buf, buf)
219        return (h,u), (0.,du_fast), (dh,du_slow)
220
221#----------------------------------- HPE ------------------------------------
222
223class Caldyn_HPE(Caldyn):
224    def __init__(self,caldyn_thermo,caldyn_eta, mesh,thermo,BC,g):
225        Caldyn.__init__(self,mesh)
226        setvars(('hydrostatic','caldyn_thermo','caldyn_eta',
227                 'g','ptop','Rd','cpp','preff','Treff'),
228                (True,caldyn_thermo,caldyn_eta,
229                 g,BC.ptop,thermo.Rd,thermo.Cpd,thermo.p0,thermo.T0))
230        dynamico_init_params()
231    def _bwd_fast_slow_(self, flow, tau):
232        dm, dS, du_slow, du_fast, buf = self.fmass(), self.ftheta(), self.fu(), self.fu(), self.geopot
233        m,S,u = flow
234        ker.dynamico_caldyn_unstructured(tau, self.ms, m, S, u, self.geopot, buf,
235                  self.s, self.ps, self.pk, self.hflux, self.qv,
236                  self.dms, dm, dS, du_fast, du_slow,
237                  buf, buf, buf, buf)
238        return (m,S,u), (0.,0.,du_fast), (dm,dS,du_slow)
239
240#----------------------------------- NH ------------------------------------
241
242class Caldyn_NH(Caldyn):
243    def __init__(self,caldyn_thermo,caldyn_eta, mesh,thermo,BC,g):
244        Caldyn.__init__(self,mesh)
245        setvars(('hydrostatic','caldyn_thermo','caldyn_eta',
246                 'g','ptop','Rd','cpp','preff','Treff',
247                 'pbot','rho_bot'),
248                (False,caldyn_thermo,caldyn_eta,
249                 g,BC.ptop,thermo.Rd,thermo.Cpd,thermo.p0,thermo.T0,
250                 BC.pbot.max(), BC.rho_bot.max()))
251        dynamico_init_params()
252    def bwd_fast_slow(self, flow, tau):
253        ftheta, fmass, fu, fw = self.ftheta, self.fmass, self.fu, self.fw
254        dm, dS, du_slow, du_fast = fmass(), ftheta(), fu(), fu()
255        dPhi_slow, dPhi_fast, dW_slow, dW_fast = fw(), fw(), fw(), fw()
256        m,S,u,Phi,W = flow
257        ker.dynamico_caldyn_unstructured(tau, self.ms, m, S, u, Phi, W,
258                  self.s, self.ps, self.pk, self.hflux, self.qv,
259                  self.dms, dm, dS, du_fast, du_slow,
260                  dPhi_fast, dPhi_slow, dW_fast, dW_slow)
261        return ((m,S,u,Phi,W), (0.,0.,du_fast,dPhi_fast,dW_fast), 
262                (dm,dS,du_slow,dPhi_slow,dW_slow))
263
264#------------------------ Copy mesh info to Fortran side -------------------
265
266def init_mesh(llm, nqdyn, edge_num, primal_num, dual_num,
267              max_trisk_deg, max_primal_deg, max_dual_deg,
268              primal_nb, primal_edge, primal_ne,
269              dual_nb,dual_edge,dual_ne,dual_vertex, 
270              left,right,down,up,trisk_deg,trisk,
271              Ai, Av, fv, le_de, Riv2, wee):
272    setvars( ('llm','nqdyn','edge_num','primal_num','dual_num',
273              'max_trisk_deg','max_primal_deg','max_dual_deg'),
274             (llm, nqdyn, edge_num, primal_num, dual_num, 
275              max_trisk_deg, max_primal_deg, max_dual_deg) )       
276    print('init_mesh ...')
277    ker.dynamico_init_mesh(primal_nb,primal_edge,primal_ne,
278              dual_nb,dual_edge,dual_ne,dual_vertex,
279              left,right,down,up,trisk_deg,trisk)
280    print ('...done')
281    print('init_metric ...')
282    ker.dynamico_init_metric(Ai,Av,fv,le_de,Riv2,wee)
283    print ('...done')
284
285#------------------------ Mesh partitioning ------------------------
286
287# Helper functions and interface to ParMETIS
288# list_stencil converts an adjacency graph from array format index[num_cells, MAX_EDGES] to compressed format
289# loc_stencil returns the start/end indices (vtxdist) expected by ParMETIS
290# i.e. index[start:end] with start=vtxdist[cell], end=vtxdist[cell+1] lists the edges of cell 'cell'
291
292def list_stencil(degree, stencil, cond=lambda x:True):
293    for i in range(degree.size):
294        for j in range(degree[i]):
295            s=stencil[i,j]
296            if cond(s): yield stencil[i,j]
297               
298def loc_stencil(degree, stencil):
299    loc=0
300    for i in range(degree.size):
301        yield loc
302        loc=loc+degree[i]
303    yield loc
304
305def partition_mesh(degree, stencil, nparts): 
306    # arguments : PArray1D and PArray2D describing mesh, number of desired partitions
307    dim_cell, degree, stencil = degree.dim, degree.data, stencil.data
308    comm, vtxdist, idx_start, idx_end = dim_cell.comm, dim_cell.vtxdist, dim_cell.start, dim_cell.end
309    mpi_rank, mpi_size = comm.Get_rank(), comm.Get_size()
310    adjncy_loc, xadj_loc = list_stencil(degree, stencil), loc_stencil(degree, stencil)
311    adjncy_loc, xadj_loc = [np.asarray(list(x), dtype=np.int32) for x in (adjncy_loc, xadj_loc)]
312    owner = np.zeros(idx_end-idx_start, dtype=np.int32);
313    ker.dynamico_partition_graph(mpi_rank, mpi_size, vtxdist, xadj_loc, adjncy_loc, nparts, owner)
314    return owner
Note: See TracBrowser for help on using the repository browser.