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

Last change on this file since 681 was 681, checked in by dubos, 6 years ago

devel/unstructured : local mesh setup + halo exchange

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