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

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

devel/unstructured : more fixes to mixed precision

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