本文整理匯總了Python中xarray.Variable方法的典型用法代碼示例。如果您正苦於以下問題:Python xarray.Variable方法的具體用法?Python xarray.Variable怎麽用?Python xarray.Variable使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類xarray
的用法示例。
在下文中一共展示了xarray.Variable方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _load_GeoTransform
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def _load_GeoTransform(self):
"""Calculate latitude and longitude variable calculated from the
gdal.Open.GetGeoTransform method"""
def load_lon():
return arange(ds.RasterXSize)*b[1]+b[0]
def load_lat():
return arange(ds.RasterYSize)*b[5]+b[3]
ds = self.ds
b = self.ds.GetGeoTransform() # bbox, interval
if with_dask:
lat = Array(
{('lat', 0): (load_lat,)}, 'lat', (self.ds.RasterYSize,),
shape=(self.ds.RasterYSize,), dtype=float)
lon = Array(
{('lon', 0): (load_lon,)}, 'lon', (self.ds.RasterXSize,),
shape=(self.ds.RasterXSize,), dtype=float)
else:
lat = load_lat()
lon = load_lon()
return Variable(('lat',), lat), Variable(('lon',), lon)
示例2: can_decode
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def can_decode(cls, ds, var):
"""
Class method to determine whether the object can be decoded by this
decoder class.
Parameters
----------
ds: xarray.Dataset
The dataset that contains the given `var`
var: xarray.Variable or xarray.DataArray
The array to decode
Returns
-------
bool
True if the decoder can decode the given array `var`. Otherwise
False
Notes
-----
The default implementation returns True for any argument. Subclass this
method to be specific on what type of data your decoder can decode
"""
return True
示例3: standardize_dims
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def standardize_dims(self, var, dims={}):
"""Replace the coordinate names through x, y, z and t
Parameters
----------
var: xarray.Variable
The variable to use the dimensions of
dims: dict
The dictionary to use for replacing the original dimensions
Returns
-------
dict
The dictionary with replaced dimensions"""
dims = dict(dims)
name_map = {self.get_xname(var, self.ds.coords): 'x',
self.get_yname(var, self.ds.coords): 'y',
self.get_zname(var, self.ds.coords): 'z',
self.get_tname(var, self.ds.coords): 't'}
dims = dict(dims)
for dim in set(dims).intersection(name_map):
dims[name_map[dim]] = dims.pop(dim)
return dims
示例4: get_mesh
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def get_mesh(self, var, coords=None):
"""Get the mesh variable for the given `var`
Parameters
----------
var: xarray.Variable
The data source whith the ``'mesh'`` attribute
coords: dict
The coordinates to use. If None, the coordinates of the dataset of
this decoder is used
Returns
-------
xarray.Coordinate
The mesh coordinate"""
mesh = var.attrs.get('mesh')
if mesh is None:
return None
if coords is None:
coords = self.ds.coords
return coords.get(mesh, self.ds.coords.get(mesh))
示例5: base
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def base(self):
"""Base dataset this instance gets its data from"""
if self._base is None:
if 'variable' in self.arr.dims:
def to_dataset(i):
ret = self.isel(variable=i).to_dataset(
name=self.arr.coords['variable'].values[i])
try:
return ret.drop('variable')
except ValueError: # 'variable' Variable not defined
pass
return ret
ds = to_dataset(0)
if len(self.arr.coords['variable']) > 1:
for i in range(1, len(self.arr.coords['variable'])):
ds.update(ds.merge(to_dataset(i)))
self._base = ds
else:
self._base = self.arr.to_dataset(
name=self.arr.name or self.arr_name)
self.onbasechange.emit()
return self._base
示例6: _insert_fldmean_bounds
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def _insert_fldmean_bounds(self, da, keepdims=False):
xcoord = self.get_coord('x')
ycoord = self.get_coord('y')
sdims = (self.get_dim('y'), self.get_dim('x'))
xbounds = np.array([[xcoord.min(), xcoord.max()]])
ybounds = np.array([[ycoord.min(), ycoord.max()]])
xdims = (sdims[-1], 'bnds') if keepdims else ('bnds', )
ydims = (sdims[0], 'bnds') if keepdims else ('bnds', )
xattrs = xcoord.attrs.copy()
xattrs.pop('bounds', None)
yattrs = ycoord.attrs.copy()
yattrs.pop('bounds', None)
da.psy.base.coords[xcoord.name + '_bnds'] = xr.Variable(
xdims, xbounds if keepdims else xbounds[0], attrs=xattrs)
da.psy.base.coords[ycoord.name + '_bnds'] = xr.Variable(
ydims, ybounds if keepdims else ybounds[0], attrs=yattrs)
示例7: test_plot_bounds_2d
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def test_plot_bounds_2d(self):
x = np.arange(1, 5)
y = np.arange(5, 10)
x2d, y2d = np.meshgrid(x, y)
x_bnds = np.arange(0.5, 4.51, 1.0)
y_bnds = np.arange(4.5, 9.51, 1.0)
# the borders are not modified
x_bnds[0] = 1.0
x_bnds[-1] = 4.0
y_bnds[0] = 5.0
y_bnds[-1] = 9.0
x2d_bnds, y2d_bnds = np.meshgrid(x_bnds, y_bnds)
d = psyd.CFDecoder()
# test x bounds
bounds = d.get_plotbounds(xr.Variable(('y', 'x'), x2d))
self.assertAlmostArrayEqual(bounds, x2d_bnds)
# test y bounds
bounds = d.get_plotbounds(xr.Variable(('y', 'x'), y2d))
self.assertAlmostArrayEqual(bounds, y2d_bnds)
示例8: _from_dataset_test_variables
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def _from_dataset_test_variables(self):
"""The variables and coords needed for the from_dataset tests"""
variables = {
# 3d-variable
'v0': xr.Variable(('time', 'ydim', 'xdim'), np.zeros((4, 4, 4))),
# 2d-variable with time and x
'v1': xr.Variable(('time', 'xdim', ), np.zeros((4, 4))),
# 2d-variable with y and x
'v2': xr.Variable(('ydim', 'xdim', ), np.zeros((4, 4))),
# 1d-variable
'v3': xr.Variable(('xdim', ), np.zeros(4))}
coords = {
'ydim': xr.Variable(('ydim', ), np.arange(1, 5)),
'xdim': xr.Variable(('xdim', ), np.arange(4)),
'time': xr.Variable(
('time', ),
pd.date_range('1999-01-01', '1999-05-01', freq='M').values)}
return variables, coords
示例9: _get_variable_point
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def _get_variable_point(vname, mask_override):
# fix for https://github.com/MITgcm/xmitgcm/issues/191
if vname in mask_override:
return mask_override[vname]
dims = _VAR_METADATA[vname]['dims']
if 'i' in dims and 'j' in dims:
point = 'c'
elif 'i_g' in dims and 'j' in dims:
point = 'w'
elif 'i' in dims and 'j_g' in dims:
point = 's'
elif 'i_g' in dims and 'j_g' in dims:
raise ValueError("Don't have masks for corner points!")
else:
raise ValueError("Variable `%s` is not a horizontal variable." % vname)
return point
示例10: read_data
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def read_data(data_handle, domain=None, is_worker=False,
start=None, stop=None, calendar='standard',
var_dict=None) -> xr.Dataset:
"""Read data directly from an xarray dataset"""
varlist = list(data_handle.keys())
if var_dict is not None:
data_handle = data_handle.rename(var_dict)
varlist = list(var_dict.values())
data_handle = data_handle[varlist]
if start is not None and stop is not None:
data_handle = data_handle.sel(time=slice(start, stop))
dates = data_handle.indexes['time']
data_handle['day_of_year'] = xr.Variable(('time', ), dates.dayofyear)
return data_handle
示例11: get_variables
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def get_variables(self):
def load(band):
band = ds.GetRasterBand(band)
a = band.ReadAsArray()
no_data = band.GetNoDataValue()
if no_data is not None:
try:
a[a == no_data] = a.dtype.type(nan)
except ValueError:
pass
return a
ds = self.ds
dims = ['lat', 'lon']
chunks = ((ds.RasterYSize,), (ds.RasterXSize,))
shape = (ds.RasterYSize, ds.RasterXSize)
variables = OrderedDict()
for iband in range(1, ds.RasterCount+1):
band = ds.GetRasterBand(iband)
dt = dtype(gdal_array.codes[band.DataType])
if with_dask:
dsk = {('x', 0, 0): (load, iband)}
arr = Array(dsk, 'x', chunks, shape=shape, dtype=dt)
else:
arr = load(iband)
attrs = band.GetMetadata_Dict()
try:
dt.type(nan)
attrs['_FillValue'] = nan
except ValueError:
no_data = band.GetNoDataValue()
attrs.update({'_FillValue': no_data} if no_data else {})
variables['Band%i' % iband] = Variable(dims, arr, attrs)
variables['lat'], variables['lon'] = self._load_GeoTransform()
return FrozenOrderedDict(variables)
示例12: get_index_from_coord
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def get_index_from_coord(coord, base_index):
"""Function to return the coordinate as integer, integer array or slice
If `coord` is zero-dimensional, the corresponding integer in `base_index`
will be supplied. Otherwise it is first tried to return a slice, if that
does not work an integer array with the corresponding indices is returned.
Parameters
----------
coord: xarray.Coordinate or xarray.Variable
Coordinate to convert
base_index: pandas.Index
The base index from which the `coord` was extracted
Returns
-------
int, array of ints or slice
The indexer that can be used to access the `coord` in the
`base_index`
"""
try:
values = coord.values
except AttributeError:
values = coord
if values.ndim == 0:
return base_index.get_loc(values[()])
if len(values) == len(base_index) and (values == base_index).all():
return slice(None)
values = np.array(list(map(lambda i: base_index.get_loc(i), values)))
return to_slice(values) or values
#: mapping that translates datetime format strings to regex patterns
示例13: to_netcdf
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def to_netcdf(ds, *args, **kwargs):
"""
Store the given dataset as a netCDF file
This functions works essentially the same as the usual
:meth:`xarray.Dataset.to_netcdf` method but can also encode absolute time
units
Parameters
----------
ds: xarray.Dataset
The dataset to store
%(xarray.Dataset.to_netcdf.parameters)s
"""
to_update = {}
for v, obj in six.iteritems(ds.variables):
units = obj.attrs.get('units', obj.encoding.get('units', None))
if units == 'day as %Y%m%d.%f' and np.issubdtype(
obj.dtype, np.datetime64):
to_update[v] = xr.Variable(
obj.dims, AbsoluteTimeEncoder(obj), attrs=obj.attrs.copy(),
encoding=obj.encoding)
to_update[v].attrs['units'] = units
if to_update:
ds = ds.copy()
ds.update(to_update)
return xarray_api.to_netcdf(ds, *args, **kwargs)
示例14: get_x
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def get_x(self, var, coords=None):
"""
Get the x-coordinate of a variable
This method searches for the x-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'X', otherwise it looks whether there is an intersection
between the :attr:`x` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the last dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the x-coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The y-coordinate or None if it could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 'x', coords)
if coord is not None:
return coord
return coords.get(self.get_xname(var))
示例15: get_y
# 需要導入模塊: import xarray [as 別名]
# 或者: from xarray import Variable [as 別名]
def get_y(self, var, coords=None):
"""
Get the y-coordinate of a variable
This method searches for the y-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'Y', otherwise it looks whether there is an intersection
between the :attr:`y` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the second last dimension of
`var` (or the last if the dimension of var is one-dimensional)
Possible types
--------------
var: xarray.Variable
The variable to get the y-coordinate for
coords: dict
Coordinates to use. If None, the coordinates of the dataset in the
:attr:`ds` attribute are used.
Returns
-------
xarray.Coordinate or None
The y-coordinate or None if it could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 'y', coords)
if coord is not None:
return coord
return coords.get(self.get_yname(var))