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

Last change on this file since 784 was 784, checked in by jisesh, 6 years ago

devel/unstructured : laplacian operator

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