slimPre.py 15.1 KB
Newer Older
Philippe Delandmeter's avatar
Philippe Delandmeter committed
1
2
3
4
5
import dgpy
import slim_private
import numpy as np
import datetime
import calendar
Philippe Delandmeter's avatar
Philippe Delandmeter committed
6
7
import dgftp

Philippe Delandmeter's avatar
Philippe Delandmeter committed
8
9
10
11
12
13
14

class Mesh :
    def __init__(self, mesh_file_name, mesh_proj=None) :
        self._groups = dgpy.dgGroupCollection(mesh_file_name)
        self._mesh_proj = mesh_proj


Philippe Delandmeter's avatar
Philippe Delandmeter committed
15
class Region :
Philippe Delandmeter's avatar
Philippe Delandmeter committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    def __init__(self, mesh, physical_tags='') :
        self._mesh = mesh
        self._physical_tags = physical_tags
        self._nodes = []
        self._groups = []
        self._node_map = {}
        self._node_ids = []
        num_ = 0
        self._type = "interface"
        for iGroup in range(mesh._groups.getNbElementGroups()) :
            group = mesh._groups.getElementGroup(iGroup)
            if not None and  (not (slim_private._is_string(physical_tags) and group.getPhysicalTag() == physical_tags) and not group.getPhysicalTag() in physical_tags) :
                continue
            self._type = "volume"
            self._groups.append(group)
            nbNodes = group.getNbNodes()
            ig = len(self._groups) - 1
            for iElement in range(group.getNbElements()) :
                element = group.getElement(iElement)
                for iNode in range(nbNodes) :
                    nodeId = mesh._groups.mesh().gmshVertexId(element.vertex(iNode))
                    if not nodeId in self._node_map :
                        self._nodes.append((ig, nbNodes*iElement+iNode))
                        num_ += 1
                        self._node_map[nodeId] = num_
                        self._node_ids.append(nodeId)
        if self._type == "volume" :
Philippe Delandmeter's avatar
Philippe Delandmeter committed
43
            self.coordinates = self._evaluateFunctor(dgpy.function.getCoordinates(), 3)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
            return

        for iFaceGroup in range(mesh._groups.getNbFaceGroups()) :
            faceGroup = mesh._groups.getFaceGroup(iFaceGroup)
            if not (slim_private._is_string(physical_tags) and faceGroup.physicalTag() == physical_tags) and not faceGroup.physicalTag() in physical_tags :
                continue
            self._groups.append(faceGroup)
            nbNodes = faceGroup.getNbNodes()
            ig = len(self._groups) - 1
            for iFace in range(faceGroup.size()) :
                group = faceGroup.elementGroup(0)
                iElement = faceGroup.elementId(iFace, 0)
                element = group.getElement(iElement)
                cl = faceGroup.closure(iFace, 0)
                for iNode in range(nbNodes) :
                    nodeId = mesh._groups.mesh().gmshVertexId(element.vertex(cl[iNode]))
                    if not nodeId in self._node_map :
                        self._nodes.append((ig, nbNodes*iFace+iNode))
                        num_ += 1
                        self._node_map[nodeId] = num_
                        self._node_ids.append(nodeId)
        self.coordinates = self._evaluateFunctor(dgpy.function.getCoordinates(), 3)

    def _evaluateFunctor(self, f, size) :
        fc = dgpy.functorCache(dgpy.functorCache.NODE_GROUP_MODE, self._mesh._groups)
        val = np.empty((len(self._nodes), size))
        valg = []
        for g in self._groups :
            if self._type == "volume":
                fc.setGroup(g)
            else:
                fc.setInterfaceGroup(g)
            valg.append(np.copy(fc.get(f)))
        for i,(iG, iN) in enumerate(self._nodes) :
            val[i,:] = valg[iG][iN]
        return val


class Coordinate_system :
Philippe Delandmeter's avatar
Philippe Delandmeter committed
83
84
    def __init__(self, region, data_proj) :
        self._region = region
Philippe Delandmeter's avatar
Philippe Delandmeter committed
85

Philippe Delandmeter's avatar
Philippe Delandmeter committed
86
        mesh_proj = region._mesh._mesh_proj
Philippe Delandmeter's avatar
Philippe Delandmeter committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        if mesh_proj is not None :
            print('Projection used:')
            print('  mesh proj:', mesh_proj)
            print('  data proj:', data_proj)
            _mesh_proj = dgpy.pj_init_plus(mesh_proj)
            _data_proj = dgpy.pj_init_plus(data_proj)
        elif mesh_proj is None :
            print('Projection used:')
            print('  mesh proj: no projection. Coordinates are 3D')
            print('  data proj:', data_proj)
            mesh_proj2 = "+proj=latlong +ellps=WGS84"
            _mesh_proj = dgpy.pj_init_plus(mesh_proj2)
            _data_proj = dgpy.pj_init_plus(data_proj)

Philippe Delandmeter's avatar
Philippe Delandmeter committed
101
        xyz = region.coordinates
Philippe Delandmeter's avatar
Philippe Delandmeter committed
102
        if mesh_proj :
Philippe Delandmeter's avatar
Philippe Delandmeter committed
103
            self.coordinates = dgpy.pjTransform(_mesh_proj, _data_proj, xyz)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
104
105
106
107
108
109
110
111
112
113
114
115
            epsVect = np.zeros(xyz.shape) 
            epsVect[:,0] = np.hypot(xyz[1,0]-xyz[0,0],xyz[1,1]-xyz[0,1]) / 1000.
            xyz0 = dgpy.pjTransform(_mesh_proj, _data_proj, xyz-epsVect)
            xyz1 = dgpy.pjTransform(_mesh_proj, _data_proj, xyz+epsVect)
            if dgpy.pj_is_latlong(_data_proj) :
                xyz1[:,0] = np.where( xyz1[:,0]<xyz0[:,0], xyz1[:,0]+2*np.pi, xyz1[:,0])
            self._angle = np.arctan2(xyz1[:,1]-xyz0[:,1], xyz1[:,0]-xyz0[:,0])
        else :
            lonlat = np.zeros(xyz.shape)
            lonlat[:,0] = np.arctan2(xyz[:,1], xyz[:,0])
            lonlat[:,1] = np.arcsin(xyz[:,2] / np.sqrt(xyz[:,0]*xyz[:,0]+xyz[:,1]*xyz[:,1]+xyz[:,2]*xyz[:,2]) )
            lonlat[:,2] = np.sqrt(xyz[:,0]*xyz[:,0]+xyz[:,1]*xyz[:,1]+xyz[:,2]*xyz[:,2]) 
Philippe Delandmeter's avatar
Philippe Delandmeter committed
116
            self.coordinates = dgpy.pjTransform(_mesh_proj, _data_proj, lonlat)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
            epsVect = np.zeros(xyz.shape) 
            epsVect[:,0] = 0.01
            xyz0 = dgpy.pjTransform(_mesh_proj, _data_proj, xyz-epsVect)
            xyz1 = dgpy.pjTransform(_mesh_proj, _data_proj, xyz+epsVect)
            self._angle = np.atan2(xyz1[:,1]-xyz0[:,1], xyz1[:,0]-xyz0[:,0])

        if _mesh_proj:
            dgpy.pj_free(_mesh_proj)
        if _data_proj:
            dgpy.pj_free(_data_proj)

    def rotate(self, u, v):
        u2 =  u * np.cos(self._angle) + v * np.sin(self._angle)
        v2 = -u * np.sin(self._angle) + v * np.cos(self._angle)
        return (u2, v2)


class Time :
    def __init__(self, time_vector, initial_time='1970-01-01 00:00:00', periodic=False) :
        self._time = np.array(time_vector)
        self._periodic = periodic

        fmt = '%Y-%m-%d %H:%M:%S'
        date_ref  = datetime.datetime.strptime('1970-01-01 00:00:00', fmt)
        date_user = datetime.datetime.strptime(initial_time, fmt)
        date_shift = (date_user-date_ref)
        time_shift = date_shift.days * 86400 + date_shift.seconds
        self._time += time_shift

    def __init__(self, initial_time, final_time, time_step, periodic=False) :
        self._periodic = periodic
        fmt = '%Y-%m-%d %H:%M:%S'
        date  = datetime.datetime.strptime(initial_time, fmt)
        initial_time = calendar.timegm([date.year, date.month, date.day, date.hour, date.minute, date.second])
        date  = datetime.datetime.strptime(final_time, fmt)
        final_time = calendar.timegm([date.year, date.month, date.day, date.hour, date.minute, date.second])
        self._time = np.arange(initial_time, final_time+time_step*0.9999, time_step)


Philippe Delandmeter's avatar
Philippe Delandmeter committed
156
def write_file(file_name, region=None, time=None, data=[]):
Philippe Delandmeter's avatar
Philippe Delandmeter committed
157
158
159
    
    oF = dgpy.slimNetCDFWrap(file_name)

Philippe Delandmeter's avatar
Philippe Delandmeter committed
160
161
    if region is not None :
        nbNodes = len(region._node_ids)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
162
163
        nodeDim = oF.create_dimension('node', nbNodes)
        nodeVar = oF.create_variable_int('node', [nodeDim])
Philippe Delandmeter's avatar
Philippe Delandmeter committed
164
        oF.set_variable_int(nodeVar, region._node_ids)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
165
166
167
168
169
170
    if time is not None :
        nTimes = np.shape(time._time)[0]
        timeArray = np.array([time._time])
        if not time._periodic:
            timeUnits = 'seconds since 1970-01-01 00:00:00'
        else:
171
            timeUnits = 'seconds since the beginning of the period'
Philippe Delandmeter's avatar
Philippe Delandmeter committed
172
173
174
175
176
    else :
        nTimes = 1
        timeUnits = 'there is no timeVariable. This is only virtual'
        timeArray = np.array([[0.]]) 
    timeDim = oF.create_dimension('time', nTimes)
177
    timeVar = oF.create_variable('time', [timeDim], timeUnits, time._periodic)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
178
179
180
181
182
    oF.set_variable(timeVar, timeArray)

    nFields = len(data)
    valVar = [0]*nFields
    for iField in range(nFields) :
Philippe Delandmeter's avatar
Philippe Delandmeter committed
183
        if region is not None :
Philippe Delandmeter's avatar
Philippe Delandmeter committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
            valVar[iField] = oF.create_variable(data[iField][0], [timeDim, nodeDim], None)
        else :
            valVar[iField] = oF.create_variable(data[iField][0], [timeDim], None)
    oF.enddef()
    for iField in range(nFields) :
        if not isinstance(data[iField][1], np.ndarray) :
            try :
                values = np.array([float(data[iField][1])])
            except :
                values = np.array(data[iField][1])
        else :
            values = data[iField][1]
        if len(values.shape) == 1:
            values = values[None,:]

        oF.set_variable(valVar[iField], values)


def netcdf_to_msh(mesh_file_name, nc_file_name, variable_name, export_file_name):
    """
    export a field in the netcdf format to msh format. Available only if the field is defined on all the mesh nodes

    keyword arguments:
    mesh_file_name   -- path to the mesh file (.msh format)
    nc_file_name     -- path to the netcdf file (.nc format)
    variable_name    -- name of the variable in the netcdf file
    export_file_name -- path to the field name (.msh format)
    """

    groups = dgpy.dgGroupCollection(mesh_file_name)
    f = dgpy.slimInputRead(nc_file_name, variable_name)
    groups.exportFunctionMsh(f, export_file_name)

Philippe Delandmeter's avatar
Philippe Delandmeter committed
217
def tpxo_tide(region, time, data_file_name=None): 
Philippe Delandmeter's avatar
Philippe Delandmeter committed
218
219
220
221
222
223
224
225
226
227
228
229
    """ generate TPXO nc files
    This function will download the files tpxo and generate the data at the requested timesteps
    
    keyword arguments:
    mesh_file_name  -- path to the mesh file (.msh format)
    data_file_name  -- name of the mesh file to generate
    initial_time    -- first time of export
    end_time        -- last time of export
    time_step       -- time_step used to export the data
    physical_tags   -- vector containing the physical tags where the data will be stored (default: [])
    """

Philippe Delandmeter's avatar
Philippe Delandmeter committed
230
    lonlat = Coordinate_system(region, data_proj='+proj=latlong +ellps=WGS84')
Philippe Delandmeter's avatar
Philippe Delandmeter committed
231
232
233
234
235
236
237
238
239

    h_file_name = 'h_tpxo7.2.nc'
    u_file_name = 'u_tpxo7.2.nc'
    dgftp.get( ("/slim_data/tides/%s" % h_file_name) )
    dgftp.get( ("/slim_data/tides/%s" % u_file_name) )
    tide_ssh = dgpy.slimFunctionTpxo(h_file_name,'ha','hp','lon_z','lat_z')
    tide_u = dgpy.slimFunctionTpxo(u_file_name,'Ua','up','lon_u','lat_u')
    tide_v = dgpy.slimFunctionTpxo(u_file_name,'Va','vp','lon_v','lat_v')

Philippe Delandmeter's avatar
Philippe Delandmeter committed
240
    lonlat_coordinates = lonlat.coordinates * 180 / np.pi
Philippe Delandmeter's avatar
Philippe Delandmeter committed
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    n = np.size(time._time)
    m = len(lonlat_coordinates)

    h = np.empty((n,m))
    u = np.empty((n,m))
    v = np.empty((n,m))
    for i in range(n):
        h[i,:] = tide_ssh.getAtPoints(lonlat_coordinates, time._time[i])[:,0]
        u[i,:] = tide_u.getAtPoints(lonlat_coordinates, time._time[i])[:,0]
        v[i,:] = tide_v.getAtPoints(lonlat_coordinates, time._time[i])[:,0]

    (u, v) = lonlat.rotate(u,v)

    if data_file_name is not None:
Philippe Delandmeter's avatar
Philippe Delandmeter committed
255
        write_file(data_file_name, region=region, time=time, data=[('h', h), ('u', u), ('v', v)])
Philippe Delandmeter's avatar
Philippe Delandmeter committed
256
257
258
259


    return (h, u, v)

Philippe Delandmeter's avatar
Philippe Delandmeter committed
260
def residual_flow(region, flow, bathymetry, data_file_name=None): 
Philippe Delandmeter's avatar
Philippe Delandmeter committed
261

Philippe Delandmeter's avatar
Philippe Delandmeter committed
262
    groups = region._mesh._groups
Philippe Delandmeter's avatar
Philippe Delandmeter committed
263
264
265
    integNormals = dgpy.dgFunctionIntegratorInterface(groups, dgpy.function.getNormals())
    nx = 0
    ny = 0
Philippe Delandmeter's avatar
Philippe Delandmeter committed
266
    for tag in region._physical_tags:
Philippe Delandmeter's avatar
Philippe Delandmeter committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
        normals = integNormals.computeVector(tag)
        nx += normals[0]
        ny += normals[1]
    norm = np.sqrt(nx*nx+ny*ny)
    nx = nx/norm
    ny = ny/norm
    norm = np.sqrt(nx*nx+ny*ny)

    bathFunc = slim_private._load_function(bathymetry, groups)
    def orientedSurfNumpy(cmap, val, h, n) : 
        val[:] = h[:] * (n[:,0]*nx + n[:,1]*ny)
    f = dgpy.functionNumpy(1, orientedSurfNumpy, [bathFunc, dgpy.function.getNormals()])

    integInterface = dgpy.dgFunctionIntegratorInterface(groups, f)
    section = 0
Philippe Delandmeter's avatar
Philippe Delandmeter committed
282
    for tag in region._physical_tags:
Philippe Delandmeter's avatar
Philippe Delandmeter committed
283
284
285
286
287
288
        section += integInterface.compute(tag)

    def transportNumpy(cmap, val, h) : # eta is neglected here
        val[:,0] = -h[:] * flow / section * nx
        val[:,1] = -h[:] * flow / section * ny
    f = dgpy.functionNumpy(2, transportNumpy, [bathFunc])
Philippe Delandmeter's avatar
Philippe Delandmeter committed
289
    vals = region._evaluateFunctor(f, 2)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
290
291
292
293
294
295
296
297
298
299
300
301
302
    return vals

def smooth_bathymetry(mesh, bathymetry, output_file_name, coefficient=0.5):
    """ 
    Smoothes the bathymetry locally in order to locally reduce the noise in the momentum
    
    keyword arguments:
    mesh_file_name -- path to the mesh file (.msh format)
    bathymetry     -- tuple containing the raw bathymetry data file (.nc format) and the name of the variable bathymetry inside
    coefficient    -- coefficient for the smoothing algorithm (default: 0.5) 
    """
    groups = mesh._groups
    dof = dgpy.dgDofContainer(groups, 1)
Valentin Vallaeys's avatar
Valentin Vallaeys committed
303
    slim_private._load(dof, bathymetry)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
304
    #prepro = Data_writer(mesh)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
305
    region = Region(mesh)
Philippe Delandmeter's avatar
Philippe Delandmeter committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
    #load data
    m = groups.cgMesh()
    n = m.nVertices()
    data = np.ndarray((n),"d")
    for ig in range(groups.getNbElementGroups()) :
        g = groups.getElementGroup(ig)
        gdata = dof.getGroupProxy(ig)
        for ie in range(g.getNbElements()):
            vs = m.vertices(ig, ie)
            for i, v in enumerate(vs) :
                data[v] = gdata(i,ie)
    #smoothing
    count = 0
    factor = coefficient
    while True:
        count = count+1
        emax = 0
        for ig in range(groups.getNbElementGroups()):
            g = groups.getElementGroup(ig)
            for ie in range(g.getNbElements()):
                vs = m.vertices(ig, ie)
                vs = np.array(vs)
                bathe = data[vs]
                dmax = bathe.max() * factor
                for i in range(len(vs)):
                    for j in range(i+1, len(vs)):
                        d = abs(bathe[i] - bathe[j])
                        if (d > dmax):
                            mean = (bathe[i] + bathe[j])/2
                            if (d - dmax > emax):
                                emax = d - dmax
                            if (bathe[i] > bathe[j]):
                                 bathe[i] = mean+dmax/2
                                 bathe[j] = mean-dmax/2
                            else:
                                 bathe[i] = mean-dmax/2
                                 bathe[j] = mean+dmax/2
                data[vs,] = bathe
        #print(count,emax)
        if emax < .2 :
            break
Philippe Delandmeter's avatar
Philippe Delandmeter committed
347
348
349
    for i in range(1,len(region._node_map)):
        if region._node_map[i] > n:
            n = region._node_map[i]
Philippe Delandmeter's avatar
Philippe Delandmeter committed
350
351
352
353
354
355
356
357
358
    n+=1
    data_ordered = np.ndarray((n),"d")
    for ig in range(groups.getNbElementGroups()) :
        g = groups.getElementGroup(ig)
        for ie in range(g.getNbElements()):
            vs = m.vertices(ig, ie)
            el = g.getElement(ie)
            for i, v in enumerate(vs) :
                vId = groups.mesh().gmshVertexId(el.vertex(i))
359
                data_ordered[region._node_map[vId]] = data[v]
Philippe Delandmeter's avatar
Philippe Delandmeter committed
360
361
362
    if bathymetry[0][-3:] == ".nc":
        data_name = bathymetry[1]
    else:
Philippe Delandmeter's avatar
Philippe Delandmeter committed
363
364
        data_name = 'bath'
    write_file(output_file_name, region=region, time=None, data=[(data_name, data_ordered)])
Philippe Delandmeter's avatar
Philippe Delandmeter committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379

def get_data_from_netcdf(nc_file_name, variable_name):
    """
    Returns the array containing the values of the variable in the nectdf file (SLIM format)

    keyword arguments:
    nc_file_name  -- path to the netcdf file (.nc format)
    variable_name -- name of the variable in the netcdf file
    """
    #TODO use a wrapper instead of netCDF4
    from netCDF4 import Dataset
    f = Dataset(nc_file_name,"r")
    val = f.variables[variable_name][:]
    return val

Philippe Delandmeter's avatar
Philippe Delandmeter committed
380
381
382
383
def set_global_data_directory(path):
    dgftp.global_data = path
def get_file(file):
    dgftp.get( ("/slim_data/bohai/%s" % file) , global_path=True)