Пример #1
0
def interp2d(obj, newaxes, dims=None, order=1):
    """ bilinear interpolation: wrapper around mpl_toolkits.basemap.interp

    input:
        obj : DimArray
        newaxes: list of Axis object, or list of 1d arrays
        dims, optional: list of str (axis names), required if newaxes is a list of arrays

    output:
        interpolated data (n-d)
    """

    # make sure input axes have the valid format
    newaxes = Axes._init(newaxes, dims)  # valid format
    newaxes.sort(obj.dims)  # re-order according to object's dimensions
    x, y = newaxes  # 2-d interpolation

    # make new grid 2-D
    x1, x1 = np.meshgrid(x.values, y.values, indexing='ij')

    def interp2d(obj, order=1):
        """ 2-D interpolation function appled recursively on the object
        """
        x0, y0 = obj.axes[x.name].values, obj.axes[y.name].values
        res = interp(obj.values, x0, y0, x1, y1, order=order)
        return obj._constructor(res, newaxes, **obj._metadata)

    result = apply_recursive(obj, (x.name, y.name), interp2d)
    return result.transpose(obj.dims)  # transpose back to original dimensions
Пример #2
0
def interp2d(obj, newaxes, dims=None, order=1):
    """ bilinear interpolation: wrapper around mpl_toolkits.basemap.interp

    input:
        obj : DimArray
        newaxes: list of Axis object, or list of 1d arrays
        dims, optional: list of str (axis names), required if newaxes is a list of arrays

    output:
        interpolated data (n-d)
    """

    # make sure input axes have the valid format
    newaxes = Axes._init(newaxes, dims) # valid format
    newaxes.sort(obj.dims) # re-order according to object's dimensions
    x, y = newaxes  # 2-d interpolation

    # make new grid 2-D
    x1, x1 = np.meshgrid(x.values, y.values, indexing='ij')

    def interp2d(obj, order=1):
        """ 2-D interpolation function appled recursively on the object
        """
        x0, y0 = obj.axes[x.name].values, obj.axes[y.name].values
        res = interp(obj.values, x0, y0, x1, y1, order=order)
        return obj._constructor(res, newaxes, **obj._metadata)

    result = apply_recursive(obj, (x.name, y.name), interp2d)
    return result.transpose(obj.dims) # transpose back to original dimensions
Пример #3
0
def read_dimensions(f, name=None, ix=slice(None), verbose=False):
    """ return an Axes object

    name, optional: variable name

    return: Axes object
    """
    f, close = check_file(f, mode='r', verbose=verbose)

    # dimensions associated to the variable to load
    if name is None:
        dims = f.dimensions.keys()
    else:
        try:
            dims = f.variables[name].dimensions
        except KeyError:
            print "Available variable names:", f.variables.keys()
            raise

    dims = [str(d) for d in dims]  # conversion to string

    # load axes
    axes = Axes()
    for k in dims:

        try:
            values = f.variables[k][ix]
        except KeyError:
            msg = "'{}' dimension not found, define integer range".format(k)
            warnings.warn(msg)
            values = np.arange(len(f.dimensions[k]))

        # replace unicode by str as a temporary bug fix (any string seems otherwise to be treated as unicode in netCDF4)
        if values.size > 0 and type(values[0]) is unicode:
            for i, val in enumerate(values):
                if type(val) is unicode:
                    values[i] = str(val)

        axes.append(Axis(values, k))

    if close: f.close()

    return axes
Пример #4
0
def read_dimensions(f, name=None, ix=slice(None), verbose=False):
    """ return an Axes object

    name, optional: variable name

    return: Axes object
    """
    f, close = check_file(f, mode='r', verbose=verbose)

    # dimensions associated to the variable to load
    if name is None:
        dims = f.dimensions.keys()
    else:
        try:
            dims = f.variables[name].dimensions
        except KeyError:
            print "Available variable names:",f.variables.keys()
            raise

    dims = [str(d) for d in dims] # conversion to string

    # load axes
    axes = Axes()
    for k in dims:

        try:
            values = f.variables[k][ix]
        except KeyError:
            msg = "'{}' dimension not found, define integer range".format(k)
            warnings.warn(msg)
            values = np.arange(len(f.dimensions[k]))

        # replace unicode by str as a temporary bug fix (any string seems otherwise to be treated as unicode in netCDF4)
        if values.size > 0 and type(values[0]) is unicode:
            for i, val in enumerate(values):
                if type(val) is unicode:
                    values[i] = str(val)

        axes.append(Axis(values, k))

    if close: f.close()

    return axes
Пример #5
0
def _createVariable(f, name, axes, dims=None, dtype=float, verbose=False, mode='a+', format=FORMAT, **kwargs):
    """ Create empty netCDF4 variable from axes

    Parameters
    ----------
    f: string or netCDF4.Dataset file handle
    name : variable name
    axes : Axes's instance or list of numpy arrays (axis values)
    dims: sequence, optional
        dimension names (to be used in combination with axes to create Axes instance)
    dtype : optional, variable type
    mode : `str`, optional
        {write_modes}
        default is 'a+'

    {netCDF4}

    Examples
    --------
    >>> tmpdir = getfixture('tmpdir').strpath # some temporary directory (py.test)
    >>> outfile = os.path.join(tmpdir, 'test.nc')
    >>> da.write_nc(outfile,'myvar', axes=[[1,2,3,4],['a','b','c']], dims=['dim1', 'dim2'], mode='w')
    >>> a = DimArray([11, 22, 33, 44], axes=[[1, 2, 3, 4]], dims=('dim1',)) # some array slice 
    >>> da.write_nc(outfile, a, 'myvar', indices='b', axis='dim2') 
    >>> da.write_nc(outfile, [111,222,333,444], 'myvar', indices='a', axis='dim2') 
    >>> da.read_nc(outfile,'myvar')
    dimarray: 8 non-null elements (4 null)
    0 / dim1 (4): 1 to 4
    1 / dim2 (3): a to c
    array([[ 111.,   11.,   nan],
           [ 222.,   22.,   nan],
           [ 333.,   33.,   nan],
           [ 444.,   44.,   nan]])
    """
    f, close = _check_file(f, mode=mode, verbose=verbose, format=format)

    # make sure axes is an Axes instance
    if not isinstance(axes, Axes):
        axes = Axes._init(axes, dims=dims)

    _check_dimensions(f, axes)

    # Create Variable
    v = f.createVariable(name, dtype, [ax.name for ax in axes], **kwargs)

    if close: 
        f.close()

    return v
Пример #6
0
def read_dimensions(f, name=None, ix=slice(None), dimensions_mapping=None, verbose=False):
    """ return an Axes object

    Parameters
    ----------
    name : str, optional
        variable name
    ix : integer (position) index
    dimensions_mapping : dict, optional
        mapping between dimension and variable names

    Returns
    -------
    Axes object
    """
    f, close = _check_file(f, mode='r', verbose=verbose)

    # dimensions associated to the variable to load
    if name is None:
        dims = f.dimensions.keys()
    else:
        try:
            dims = f.variables[name].dimensions
        except KeyError:
            print "Available variable names:",f.variables.keys()
            raise

    dims = [str(d) for d in dims] # conversion to string

    # load axes
    axes = Axes()
    for dim in dims:
        if dimensions_mapping is not None:
            # user-provided mapping between dimensions and variable name
            dim_name = dimensions_mapping[dim]
            values = f.variables[dim_name][ix]
        elif dim in f.variables.keys():
            # assume that the variable and dimension have the same name
            values = f.variables[dim][ix]
        else:
            # default, dummy dimension axis
            msg = "'{}' dimension not found, define integer range".format(dim)
            warnings.warn(msg)
            values = np.arange(len(f.dimensions[dim]))

        # replace unicode by str as a temporary bug fix (any string seems otherwise to be treated as unicode in netCDF4)
        if values.size > 0 and type(values[0]) is unicode:
            for i, val in enumerate(values):
                if type(val) is unicode:
                    values[i] = str(val)

        axis = Axis(values, dim)

        # add metadata
        if dim in f.variables.keys():
            meta = _read_attributes(f, dim)
            axis._metadata(meta)

        axes.append(axis)

    if close: f.close()

    return axes