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

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

devel/Python : fix numpy messing up OpenMP

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