Example #1
0
def create_mv2_gridder_xyzt(nx=8,
                            ny=7,
                            nz=6,
                            nt=5,
                            xmin=-6.,
                            xmax=-3,
                            ymin=46,
                            ymax=48,
                            zmin=-200,
                            zmax=0,
                            tmin='2016',
                            tmax='2016-02',
                            tunits='days since 2016-01-01',
                            rotate=0):
    """Create a MV2 array on a grid

    Return
    ------
    MV2.array
    """

    # Axes
    shape = ()
    axes = []
    if nt != 0:
        time = create_time(lindates(tmin, tmax, nt), tunits)
        axes.append(time)
        shape += nt,
    if nz != 0:
        dep = create_dep(N.linspace(zmin, zmax, nz))
        axes.append(dep)
        shape += nz,
    if ny != 0:
        lat = create_lat(N.linspace(ymin, ymax, ny))
        axes.append(lat)
        shape += ny,
    if nx != 0:
        lon = create_lon(N.linspace(xmin, xmax, nx))
        axes.append(lon)
        shape += nx,

    # Array
    data = MV2.array(N.arange(N.multiply.reduce(shape)).reshape(shape),
                     copy=False,
                     axes=axes,
                     id='temp',
                     dtype='d')

    # Rotate grid
    if rotate:
        grid = data.getGrid()
        if grid is not None:
            grid = rotate_grid(grid, rotate)
            set_grid(data, grid)

    return data
Example #2
0
"""Test function :func:`~vacumm.misc.grid.resol`"""

from vcmq import create_lon, create_lat, create_grid, rotate_grid, assert_allclose
from vacumm.misc.grid.misc import resol2 as resol

lon1d = create_lon((0, 10., 1.))
lat1d = create_lat((43, 50, 1.))
rgrid = create_grid(lon1d, lat1d)
cgrid = rotate_grid(rgrid, 45)
lon2d = cgrid.getLongitude()
lat2d = cgrid.getLatitude()

assert_allclose(resol(lon1d, cache=False), 1.)
assert_allclose(resol(lon1d, meters=True, cache=False), 78626.2617245)

assert_allclose(resol(lon1d, lat=0, cache=False), 1.0)
assert_allclose(resol(lon1d, lat=0, meters=True, cache=False), 111195.031364)

assert_allclose(resol(rgrid, cache=False), (1.0, 1.0))
assert_allclose(resol(rgrid, meters=True, cache=False), (77242.051980165023, 111195.03136431401))

assert_allclose(resol((lon1d, lat1d), cache=False), (1.0, 1.0))
assert_allclose(resol((lon1d, lat1d), meters=True, cache=False), (77242.051980165023, 111195.03136431401))

assert_allclose(resol(cgrid, cache=False), (1.0, 1.0))
assert_allclose(resol(cgrid, meters=True, cache=False), (94804.663264739473, 94804.663264739473))


N.random.seed(0)
x = N.random.random(10)
y = N.random.random(10)
    P.scatter(xx.ravel(), yy.ravel(), c=(0, 1, 0))
    P.grid('on')
    P.axis('image')
    P.tight_layout()
    i = len(figfiles)
    savefig = figfile%i
    if os.path.exists(savefig): os.remove(savefig)
    P.savefig(savefig)
    figfiles.append(savefig)
    if show: P.show()
    else: P.close()
    
result = []
    
# 1D axis
lon1d = create_lon((0, 10))
result.append(('AssertEqual', (coord2slice(lon1d, lon=(2.5, 4., 'cc')), slice(3, 5, 1))))
result.append(('AssertEqual', (coord2slice(lon1d, lon=(2.5, 4., 'ccb')), slice(2, 5, 1))))
result.append(('AssertEqual', (coord2slice(lon1d, lon=slice(3, 6)), slice(3, 6, None))))
result.append(('AssertEqual', (coord2slice(lon1d, lat=(6, 8)), slice(0, 10, 1))))
result.append(('AssertEqual', (coord2slice(lon1d, lon=(60, 70)), None)))

# Rect grid
grid = create_grid((0, 10.), (20, 30.))
result.append(('AssertEqual', (coord2slice(grid, lon=(0., 3.5), lat=slice(3, 5)), 
    (slice(0, 4, 1), slice(3, 5, None), None))))
result.append(('AssertEqual', (coord2slice(grid, lat=(21,21, 'ccb')),
    (slice(0, 10, 1), slice(1, 2, 1), None))))

# 2D axis
lon2d = N.empty((10, 10.))
Example #4
0
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""Axes et grilles avec VACUMM"""

from vcmq import N, MV2, create_lon, create_lat, create_grid, isgrid, isrect, islon, set_grid,  get_grid, get_axis, varsel, resol, curv2rect, get_xy, meshgrid, meshcells, create_dep, isregular, P, rotate_grid, shiftgrid, extendgrid, create_axes2d, isdepthup, coord2slice, monotonic, xshift, depth2dz, get_closest

# Créer

# - axes
lon = create_lon((2., 11, 2.))  # -> SPECIFIEZ LE LONG_NAME
lat = create_lat(N.arange(43, 50.))
dep = create_dep((0., 10))
# -> AFFICHEZ LES INFOS
xx, yy = N.meshgrid(N.arange(5.), N.arange(4.))
lon2d, lat2d = create_axes2d(xx, yy)
ii = lon2d.getAxis(1)

# - grille
grid = create_grid(lon, lat)    # -> ESSAYEZ AVEC LON EXPLICITE
gridc = create_grid(lon2d, lat2d)


# Verifier
print islon(lon)
print isgrid(grid)              # -> TEST PARAM CURV=...
print isrect(gridc)             # -> CREEZ GRILLE NON RECT ET RETESTER
print isdepthup(dep)            # -> TESTEZ EN CHANGEANT ATTRIBUT POSITIVE ET VALEURS
print isregular(lon)            


# Affecter
"""Test :func:`~vacumm.misc.plot.section2` in quiver mode"""

# Imports
from vcmq import create_lon, N, MV2, create_dep, os, code_file_name, section2
from vacumm.misc.phys.units import deg2m

# Init data with z 1D
nz = 11
nx = 11
x = create_lon(N.arange(nx))
xm = deg2m(x[:],lat=45.) # meters
dx = xm[:].ptp()
z = create_dep((-nz+1, 1.), units='m', long_name='Depth')
dz = z[:].ptp()
scale = dz/dx
u = MV2.ones((nz,nx)) # 1 m/s
w = u*scale           # 1 m/s * scale
for var in u,w:
    var.setAxis(0, z)
    var.setAxis(1, x)
    var.units = 'm/s'

# Plot
figfile = code_file_name(ext='png')
if os.path.exists(figfile): os.remove(figfile)
s = section2((u,w), quiver_norm=1, fill=False, show=False,
    savefig=figfile, close=False, axes_aspect=1)

# Result
result = dict(files=figfile)
Example #6
0
"""Test CDAT conservative regridding"""
from vcmq import N, meshbounds, bounds1d, cdms2, MV2, rc, P, add_grid, rcdefaults, \
    create_lon, create_lat, savefigs, code_file_name

# Input grid
x0, y0, nx, ny, dx, dy = 0., 0., 20, 15, 5., 5.
x = x0 + N.arange(0, nx * dx, dx)
y = y0 + N.arange(0, ny * dy, dy)
xxbi, yybi = meshbounds(x, y)
xb = bounds1d(x)
yb = bounds1d(y)
lon = create_lon(x)
lat = create_lat(y)
lon.setBounds(xb)
lat.setBounds(yb)
gridi = cdms2.createRectGrid(lat, lon)

# Input data
vari = MV2.ones(gridi.shape) * 50
vari[5:10, 7:13] = -10
#vari[:, -1] = MV2.masked # <<< THIS MAKES IT WORK!

vari.setAxisList([gridi.getLatitude(), gridi.getLongitude()])
vari.setGrid(gridi)

# Output grid
grido, xxbo, yybo = gridi, xxbi, yybi

# Regrid
diag = {'dstAreaFractions': None}
varo = vari.regrid(grido,
Example #7
0
mob = MV2.array([0, 1, 1, 0], id='mobility', fill_value=-1)
paxis = lons.getAxis(0)
paxis.id = 'station'
axes = [daxis, paxis]
f = cdms2.open(ncfile, 'w')
for var in lons, lats, mob, temp_error, sal_error:
    var.setAxis(-1, paxis)
    if var.ndim == 2:
        var.setAxis(0, daxis)
    f.write(var)
f.close()
print os.path.abspath(ncfile)

# HF radars
ncfile = '../data/obs.hfradars.nc'
lon = create_lon((-5.8, -4.7, .1))
lat = create_lat((47.8, 48.3, .1))
nx = len(lon)
ny = len(lat)
u_error = MV2.ones((ny, nx), id='u_error', axes=[lat, lon])
u_error[:] *= .2
u_error[:] += N.resize(N.linspace(0, .1, nx), (ny, nx))
u_error[:2, :2] = u_error[-2:, :2] = N.ma.masked
v_error = u_error.clone()
v_error.id = 'v_error'
mob = MV2.zeros((ny, nx), id='mobility', axes=[lat, lon], dtype='i')
f = cdms2.open(ncfile, 'w')
for var in mob, u_error, v_error:
    f.write(var)
f.depth = 'surf'
f.close()
Example #8
0
"""Test :func:`~vacumm.misc.plot.curve2` with a longitude axis"""

# Imports
from vcmq import MV2, code_file_name, os, code_file_name, curve2, create_lon

# Init
var = MV2.arange(5.)
var.units = r'$m s^{-1}$'
var.long_name = 'Speed'
var.setAxis(0, create_lon(var.getAxis(0)))

# Plot
figfile = code_file_name(ext='png')
if os.path.exists(figfile): os.remove(figfile)
curve2(var, savefig=figfile, show=False, close=True)

Example #9
0
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""Axes et grilles avec VACUMM"""

from vcmq import N, MV2, create_lon, create_lat, create_grid, isgrid, isrect, islon, set_grid, get_grid, get_axis, varsel, resol, curv2rect, get_xy, meshgrid, meshcells, create_dep, isregular, P, rotate_grid, shiftgrid, extendgrid, create_axes2d, isdepthup, coord2slice, monotonic, xshift, depth2dz, get_closest

# Créer

# - axes
lon = create_lon((2., 11, 2.))  # -> SPECIFIEZ LE LONG_NAME
lat = create_lat(N.arange(43, 50.))
dep = create_dep((0., 10))
# -> AFFICHEZ LES INFOS
xx, yy = N.meshgrid(N.arange(5.), N.arange(4.))
lon2d, lat2d = create_axes2d(xx, yy)
ii = lon2d.getAxis(1)

# - grille
grid = create_grid(lon, lat)  # -> ESSAYEZ AVEC LON EXPLICITE
gridc = create_grid(lon2d, lat2d)

# Verifier
print islon(lon)
print isgrid(grid)  # -> TEST PARAM CURV=...
print isrect(gridc)  # -> CREEZ GRILLE NON RECT ET RETESTER
print isdepthup(dep)  # -> TESTEZ EN CHANGEANT ATTRIBUT POSITIVE ET VALEURS
print isregular(lon)

# Affecter
var = MV2.ones(grid.shape)
set_grid(var, grid)
Example #10
0
"""Test function :func:`~vacumm.misc.grid.resol`"""

from vcmq import create_lon, create_lat, create_grid, rotate_grid, assert_allclose
from vacumm.misc.grid.misc import resol

lon1d = create_lon((0, 10., 1.))
lat1d = create_lat((43, 50, 1.))
rgrid = create_grid(lon1d, lat1d)
cgrid = rotate_grid(rgrid, 45)
lon2d = cgrid.getLongitude()
lat2d = cgrid.getLatitude()

assert_allclose(resol(lon1d, cache=False), 1.)
assert_allclose(resol(lon1d, meters=True, cache=False), 78626.2617245)

assert_allclose(resol(lon1d, lat=0, cache=False), 1.0)
assert_allclose(resol(lon1d, lat=0, meters=True, cache=False), 111195.031364)

assert_allclose(resol(rgrid, cache=False), (1.0, 1.0))
assert_allclose(resol(rgrid, meters=True, cache=False), (77242.051980165023, 111195.03136431401))

assert_allclose(resol((lon1d, lat1d), cache=False), (1.0, 1.0))
assert_allclose(resol((lon1d, lat1d), meters=True, cache=False), (77242.051980165023, 111195.03136431401))

assert_allclose(resol(cgrid, cache=False), (1.0, 1.0))
assert_allclose(resol(cgrid, meters=True, cache=False), (94804.663264739473, 94804.663264739473))


N.random.seed(0)
x = N.random.random(10)
y = N.random.random(10)
Example #11
0
dep1 = 0
time0 = "2008-08-15 07:00"
time1 = "2008-08-15 16:00"
ne = 4
nez = 2



# Imports
from vcmq import (N, MV2, code_file_name, os, P, create_lon, create_lat, create_dep,
                  create_time, lindates, create_axis, reltime, grid2xy,
                  comptime, set_grid, rotate_grid, add_grid)

# Rectangular xyzt with 1d z data and coords
# - data
lon = create_lon(N.linspace(lon0, lon1, nx))
lat = create_lat(N.linspace(lat0, lat1, ny))
dep = create_dep(N.linspace(dep0, dep1, nz))
time = create_time(lindates(time0, time1, nt))
extra = create_axis(N.arange(ne), id='member')
data = N.resize(lat[:], (ne, nt, nz, nx, ny)) # function of y
data = N.moveaxis(data, -1, -2)
#data = N.arange(nx*ny*nz*nt*ne, dtype='d').reshape(ne, nt, nz, ny, nx)
vi = MV2.array(data,
                 axes=[extra, time, dep, lat, lon], copy=False,
                 fill_value=1e20)
N.random.seed(0)
xo = N.random.uniform(lon0, lon1, np)
yo = N.random.uniform(lat0, lat1, np)
zo = N.random.uniform(dep0, dep1, np)
to = comptime(N.random.uniform(reltime(time0, time.units).value,
Example #12
0
"""Test :func:`~vacumm.misc.plot.section2` in quiver mode"""

# Imports
from vcmq import create_lon, N, MV2, create_dep, os, code_file_name, section2
from vacumm.misc.phys.units import deg2m

# Init data with z 1D
nz = 11
nx = 11
x = create_lon(N.arange(nx))
xm = deg2m(x[:], lat=45.)  # meters
dx = xm[:].ptp()
z = create_dep((-nz + 1, 1.), units='m', long_name='Depth')
dz = z[:].ptp()
scale = dz / dx
u = MV2.ones((nz, nx))  # 1 m/s
w = u * scale  # 1 m/s * scale
for var in u, w:
    var.setAxis(0, z)
    var.setAxis(1, x)
    var.units = 'm/s'

# Plot
figfile = code_file_name(ext='png')
if os.path.exists(figfile): os.remove(figfile)
s = section2((u, w),
             quiver_norm=1,
             fill=False,
             show=False,
             savefig=figfile,
             close=True,
"""Test CDAT conservative regridding"""
from vcmq import N, meshbounds, bounds1d, cdms2, MV2, rc, P, add_grid, rcdefaults, \
    create_lon, create_lat, savefigs, code_file_name
    
# Input grid
x0, y0, nx, ny, dx, dy = 0., 0., 20, 15, 5., 5.
x = x0+N.arange(0, nx*dx, dx)
y = y0+N.arange(0, ny*dy, dy)
xxbi, yybi = meshbounds(x, y)
xb = bounds1d(x)
yb = bounds1d(y)
lon = create_lon(x)
lat = create_lat(y)
lon.setBounds(xb)
lat.setBounds(yb)
gridi = cdms2.createRectGrid(lat, lon)

# Input data
vari = MV2.ones(gridi.shape)*50
vari[5:10, 7:13] = -10
#vari[:, -1] = MV2.masked # <<< THIS MAKES IT WORK!

vari.setAxisList([gridi.getLatitude(), gridi.getLongitude()])
vari.setGrid(gridi)

# Output grid
grido, xxbo, yybo = gridi, xxbi, yybi

# Regrid
diag = {'dstAreaFractions':None}
varo = vari.regrid(grido, tool='esmf', method='conservative', 
Example #14
0
def slice_gridded_var(var, member=None, time=None, depth=None, lat=None, lon=None):
    """Make slices of a variable and squeeze out singletons to reduce it

    The "member" axis is considered here as a generic name for the first
    axis of unkown type.

    .. warning:: All axes must be 1D
    """

    # Check order
    var = var(squeeze=1)
    order = var.getOrder()

    # Unkown axis
    if '-' in order and member is not None:
        i = order.find('-')
        id = var.getAxisIds()[i]
        if isinstance(member, slice):
            kw = {id:member}
            var = var(**kw)
        else:
            axo = create_axis(member)
            cp_atts(var.getAxis(i), axo)
            var = regrid1d(var, axo, iaxi=i)(squeeze=N.isscalar(member))

    # Time interpolation
    if 't' in order and time is not None:
        axi = var.getTime()
        if isinstance(time, slice):
            var = var(time=time)
        else:
            axo = create_time(time, axi.units)
            var = regrid1d(var, axo)(squeeze=N.isscalar(time))

    # Depth interpolation
    if 'z' in order and depth is not None:
        if depth=='bottom':
            var = slice_bottom(var)
        else:
            if depth=='surf':
                depth = slice(-1, None)
            if isinstance(depth, slice):
                var = var(level=depth, squeeze=1) # z squeeze only?
            elif (N.isscalar(depth) and var.getLevel()[:].ndim==1 and
                  depth in var.getLevel()):
                var = var(level=depth)
            else:
                axo = create_dep(depth)
                if axo[:].max()>10:
                    sonat_warn('Interpolation depth is positive. Taking this opposite')
                    axo[:] *=-1
                var = regrid1d(var, axo)(squeeze=N.isscalar(depth))

    # Point
    if (order.endswith('yx') and lon is not None and lat is not None and
            not isinstance(lat, slice) and not isinstance(lon, slice)):

        var = grid2xy(var, lon, lat)(squeeze=N.isscalar(lon))

    else:

        # Latitude interpolation
        if 'y' in order and lat:
            if isinstance(lat, slice):
                var = var(lat=lat)
            else:
                axo = create_lat(lat)
                var = regrid1d(var, axo)(squeeze=N.isscalar(lat))

        # Longitude interpolation
        if 'x' in order and lon:
            if isinstance(lon, slice):
                var = var(lon=lon)
            else:
                axo = create_lon(lon)
                var = regrid1d(var, axo)(squeeze=N.isscalar(lon))

    return var
Example #15
0
"""Test :func:`~vacumm.misc.plot.curve2` with a longitude axis"""

# Imports
from vcmq import MV2, code_file_name, os, curve2, create_lon

# Init
var = MV2.arange(5.)
var.units = r'$m s^{-1}$'
var.long_name = 'Speed'
var.setAxis(0, create_lon(var.getAxis(0)))

# Plot
figfile = code_file_name(ext='png')
if os.path.exists(figfile): os.remove(figfile)
curve2(var, savefig=figfile, show=False, close=True)