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

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

devel/unstructured : added kernel for curl curl ; used by Baroclinic_3D_ullrich

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