sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1 value |
|---|---|---|
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)) | 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 | entailment |
def get_xname(self, var, coords=None):
"""Get the name of the x-dimension
This method gives the name of the x-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_x"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'x', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.x.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for x coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the last position
return var.dims[-1] | Get the name of the x-dimension
This method gives the name of the x-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_x | entailment |
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)) | 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 | entailment |
def get_yname(self, var, coords=None):
"""Get the name of the y-dimension
This method gives the name of the y-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_y"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'y', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.y.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for y coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the last or second last
# position
if self.is_unstructured(var):
return var.dims[-1]
return var.dims[-2 if var.ndim > 1 else -1] | Get the name of the y-dimension
This method gives the name of the y-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str
The coordinate name
See Also
--------
get_y | entailment |
def get_z(self, var, coords=None):
"""
Get the vertical (z-) coordinate of a variable
This method searches for the z-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'Z', otherwise it looks whether there is an intersection
between the :attr:`z` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the third last dimension of
`var` (or the second last or last if var is two or one-dimensional)
Possible types
--------------
var: xarray.Variable
The variable to get the z-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 z-coordinate or None if no z coordinate could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 'z', coords)
if coord is not None:
return coord
zname = self.get_zname(var)
if zname is not None:
return coords.get(zname)
return None | Get the vertical (z-) coordinate of a variable
This method searches for the z-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'Z', otherwise it looks whether there is an intersection
between the :attr:`z` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the third last dimension of
`var` (or the second last or last if var is two or one-dimensional)
Possible types
--------------
var: xarray.Variable
The variable to get the z-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 z-coordinate or None if no z coordinate could be found | entailment |
def get_zname(self, var, coords=None):
"""Get the name of the z-dimension
This method gives the name of the z-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no vertical coordinate could be
found
See Also
--------
get_z"""
if coords is not None:
coord = self.get_variable_by_axis(var, 'z', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.z.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for z coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return the coordinate in the third last position
is_unstructured = self.is_unstructured(var)
icheck = -2 if is_unstructured else -3
min_dim = abs(icheck) if 'variable' not in var.dims else abs(icheck-1)
if var.ndim >= min_dim and var.dims[icheck] != self.get_tname(
var, coords):
return var.dims[icheck]
return None | Get the name of the z-dimension
This method gives the name of the z-dimension (which is not necessarily
the name of the coordinate if the variable has a coordinate attribute)
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no vertical coordinate could be
found
See Also
--------
get_z | entailment |
def get_t(self, var, coords=None):
"""
Get the time coordinate of a variable
This method searches for the time coordinate in the :attr:`ds`. It
first checks whether there is one dimension that holds an ``'axis'``
attribute with 'T', otherwise it looks whether there is an intersection
between the :attr:`t` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the first dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the time 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 time coordinate or None if no time coordinate could be found"""
coords = coords or self.ds.coords
coord = self.get_variable_by_axis(var, 't', coords)
if coord is not None:
return coord
dimlist = list(self.t.intersection(var.dims).intersection(coords))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for time coordinate in the "
"variable: %s. I use %s" % (
', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return coords[dimlist[0]]
tname = self.get_tname(var)
if tname is not None:
return coords.get(tname)
return None | Get the time coordinate of a variable
This method searches for the time coordinate in the :attr:`ds`. It
first checks whether there is one dimension that holds an ``'axis'``
attribute with 'T', otherwise it looks whether there is an intersection
between the :attr:`t` attribute and the variables dimensions, otherwise
it returns the coordinate corresponding to the first dimension of `var`
Possible types
--------------
var: xarray.Variable
The variable to get the time 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 time coordinate or None if no time coordinate could be found | entailment |
def get_tname(self, var, coords=None):
"""Get the name of the t-dimension
This method gives the name of the time dimension
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no time coordinate could be found
See Also
--------
get_t"""
if coords is not None:
coord = self.get_variable_by_axis(var, 't', coords)
if coord is not None and coord.name in var.dims:
return coord.name
dimlist = list(self.t.intersection(var.dims))
if dimlist:
if len(dimlist) > 1:
warn("Found multiple matches for t coordinate in the variable:"
"%s. I use %s" % (', '.join(dimlist), dimlist[0]),
PsyPlotRuntimeWarning)
return dimlist[0]
# otherwise we return None
return None | Get the name of the t-dimension
This method gives the name of the time dimension
Parameters
----------
var: xarray.Variables
The variable to get the dimension for
coords: dict
The coordinates to use for checking the axis attribute. If None,
they are not used
Returns
-------
str or None
The coordinate name or None if no time coordinate could be found
See Also
--------
get_t | entailment |
def get_idims(self, arr, coords=None):
"""Get the coordinates in the :attr:`ds` dataset as int or slice
This method returns a mapping from the coordinate names of the given
`arr` to an integer, slice or an array of integer that represent the
coordinates in the :attr:`ds` dataset and can be used to extract the
given `arr` via the :meth:`xarray.Dataset.isel` method.
Parameters
----------
arr: xarray.DataArray
The data array for which to get the dimensions as integers, slices
or list of integers from the dataset in the :attr:`base` attribute
coords: iterable
The coordinates to use. If not given all coordinates in the
``arr.coords`` attribute are used
Returns
-------
dict
Mapping from coordinate name to integer, list of integer or slice
See Also
--------
xarray.Dataset.isel, InteractiveArray.idims"""
if coords is None:
coords = arr.coords
else:
coords = {
label: coord for label, coord in six.iteritems(arr.coords)
if label in coords}
ret = self.get_coord_idims(coords)
# handle the coordinates that are not in the dataset
missing = set(arr.dims).difference(ret)
if missing:
warn('Could not get slices for the following dimensions: %r' % (
missing, ), PsyPlotRuntimeWarning)
return ret | Get the coordinates in the :attr:`ds` dataset as int or slice
This method returns a mapping from the coordinate names of the given
`arr` to an integer, slice or an array of integer that represent the
coordinates in the :attr:`ds` dataset and can be used to extract the
given `arr` via the :meth:`xarray.Dataset.isel` method.
Parameters
----------
arr: xarray.DataArray
The data array for which to get the dimensions as integers, slices
or list of integers from the dataset in the :attr:`base` attribute
coords: iterable
The coordinates to use. If not given all coordinates in the
``arr.coords`` attribute are used
Returns
-------
dict
Mapping from coordinate name to integer, list of integer or slice
See Also
--------
xarray.Dataset.isel, InteractiveArray.idims | entailment |
def get_coord_idims(self, coords):
"""Get the slicers for the given coordinates from the base dataset
This method converts `coords` to slicers (list of
integers or ``slice`` objects)
Parameters
----------
coords: dict
A subset of the ``ds.coords`` attribute of the base dataset
:attr:`ds`
Returns
-------
dict
Mapping from coordinate name to integer, list of integer or slice
"""
ret = dict(
(label, get_index_from_coord(coord, self.ds.indexes[label]))
for label, coord in six.iteritems(coords)
if label in self.ds.indexes)
return ret | Get the slicers for the given coordinates from the base dataset
This method converts `coords` to slicers (list of
integers or ``slice`` objects)
Parameters
----------
coords: dict
A subset of the ``ds.coords`` attribute of the base dataset
:attr:`ds`
Returns
-------
dict
Mapping from coordinate name to integer, list of integer or slice | entailment |
def get_plotbounds(self, coord, kind=None, ignore_shape=False):
"""
Get the bounds of a coordinate
This method first checks the ``'bounds'`` attribute of the given
`coord` and if it fails, it calculates them.
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
kind: str
The interpolation method (see :func:`scipy.interpolate.interp1d`)
that is used in case of a 2-dimensional coordinate
ignore_shape: bool
If True and the `coord` has a ``'bounds'`` attribute, this
attribute is returned without further check. Otherwise it is tried
to bring the ``'bounds'`` into a format suitable for (e.g.) the
:func:`matplotlib.pyplot.pcolormesh` function.
Returns
-------
bounds: np.ndarray
The bounds with the same number of dimensions as `coord` but one
additional array (i.e. if `coord` has shape (4, ), `bounds` will
have shape (5, ) and if `coord` has shape (4, 5), `bounds` will
have shape (5, 6)"""
if 'bounds' in coord.attrs:
bounds = self.ds.coords[coord.attrs['bounds']]
if ignore_shape:
return bounds.values.ravel()
if not bounds.shape[:-1] == coord.shape:
bounds = self.ds.isel(**self.get_idims(coord))
try:
return self._get_plotbounds_from_cf(coord, bounds)
except ValueError as e:
warn((e.message if six.PY2 else str(e)) +
" Bounds are calculated automatically!")
return self._infer_interval_breaks(coord, kind=kind) | Get the bounds of a coordinate
This method first checks the ``'bounds'`` attribute of the given
`coord` and if it fails, it calculates them.
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
kind: str
The interpolation method (see :func:`scipy.interpolate.interp1d`)
that is used in case of a 2-dimensional coordinate
ignore_shape: bool
If True and the `coord` has a ``'bounds'`` attribute, this
attribute is returned without further check. Otherwise it is tried
to bring the ``'bounds'`` into a format suitable for (e.g.) the
:func:`matplotlib.pyplot.pcolormesh` function.
Returns
-------
bounds: np.ndarray
The bounds with the same number of dimensions as `coord` but one
additional array (i.e. if `coord` has shape (4, ), `bounds` will
have shape (5, ) and if `coord` has shape (4, 5), `bounds` will
have shape (5, 6) | entailment |
def _get_plotbounds_from_cf(coord, bounds):
"""
Get plot bounds from the bounds stored as defined by CFConventions
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
bounds: xarray.DataArray
The bounds as inferred from the attributes of the given `coord`
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids"""
if bounds.shape[:-1] != coord.shape or bounds.shape[-1] != 2:
raise ValueError(
"Cannot interprete bounds with shape {0} for {1} "
"coordinate with shape {2}.".format(
bounds.shape, coord.name, coord.shape))
ret = np.zeros(tuple(map(lambda i: i+1, coord.shape)))
ret[tuple(map(slice, coord.shape))] = bounds[..., 0]
last_slices = tuple(slice(-1, None) for _ in coord.shape)
ret[last_slices] = bounds[tuple(chain(last_slices, [1]))]
return ret | Get plot bounds from the bounds stored as defined by CFConventions
Parameters
----------
coord: xarray.Coordinate
The coordinate to get the bounds for
bounds: xarray.DataArray
The bounds as inferred from the attributes of the given `coord`
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids | entailment |
def get_triangles(self, var, coords=None, convert_radian=True,
copy=False, src_crs=None, target_crs=None,
nans=None, stacklevel=1):
"""
Get the triangles for the variable
Parameters
----------
var: xarray.Variable or xarray.DataArray
The variable to use
coords: dict
Alternative coordinates to use. If None, the coordinates of the
:attr:`ds` dataset are used
convert_radian: bool
If True and the coordinate has units in 'radian', those are
converted to degrees
copy: bool
If True, vertice arrays are copied
src_crs: cartopy.crs.Crs
The source projection of the data. If not None, a transformation
to the given `target_crs` will be done
target_crs: cartopy.crs.Crs
The target projection for which the triangles shall be transformed.
Must only be provided if the `src_crs` is not None.
%(CFDecoder._check_triangular_bounds.parameters.nans)s
Returns
-------
matplotlib.tri.Triangulation
The spatial triangles of the variable
Raises
------
ValueError
If `src_crs` is not None and `target_crs` is None"""
warn("The 'get_triangles' method is depreceated and will be removed "
"soon! Use the 'get_cell_node_coord' method!",
DeprecationWarning, stacklevel=stacklevel)
from matplotlib.tri import Triangulation
def get_vertices(axis):
bounds = self._check_triangular_bounds(var, coords=coords,
axis=axis, nans=nans)[1]
if coords is not None:
bounds = coords.get(bounds.name, bounds)
vertices = bounds.values.ravel()
if convert_radian:
coord = getattr(self, 'get_' + axis)(var)
if coord.attrs.get('units') == 'radian':
vertices = vertices * 180. / np.pi
return vertices if not copy else vertices.copy()
if coords is None:
coords = self.ds.coords
xvert = get_vertices('x')
yvert = get_vertices('y')
if src_crs is not None and src_crs != target_crs:
if target_crs is None:
raise ValueError(
"Found %s for the source crs but got None for the "
"target_crs!" % (src_crs, ))
arr = target_crs.transform_points(src_crs, xvert, yvert)
xvert = arr[:, 0]
yvert = arr[:, 1]
triangles = np.reshape(range(len(xvert)), (len(xvert) // 3, 3))
return Triangulation(xvert, yvert, triangles) | Get the triangles for the variable
Parameters
----------
var: xarray.Variable or xarray.DataArray
The variable to use
coords: dict
Alternative coordinates to use. If None, the coordinates of the
:attr:`ds` dataset are used
convert_radian: bool
If True and the coordinate has units in 'radian', those are
converted to degrees
copy: bool
If True, vertice arrays are copied
src_crs: cartopy.crs.Crs
The source projection of the data. If not None, a transformation
to the given `target_crs` will be done
target_crs: cartopy.crs.Crs
The target projection for which the triangles shall be transformed.
Must only be provided if the `src_crs` is not None.
%(CFDecoder._check_triangular_bounds.parameters.nans)s
Returns
-------
matplotlib.tri.Triangulation
The spatial triangles of the variable
Raises
------
ValueError
If `src_crs` is not None and `target_crs` is None | entailment |
def _infer_interval_breaks(coord, kind=None):
"""
Interpolate the bounds from the data in coord
Parameters
----------
%(CFDecoder.get_plotbounds.parameters.no_ignore_shape)s
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids"""
if coord.ndim == 1:
return _infer_interval_breaks(coord)
elif coord.ndim == 2:
from scipy.interpolate import interp2d
kind = kind or rcParams['decoder.interp_kind']
y, x = map(np.arange, coord.shape)
new_x, new_y = map(_infer_interval_breaks, [x, y])
coord = np.asarray(coord)
return interp2d(x, y, coord, kind=kind, copy=False)(new_x, new_y) | Interpolate the bounds from the data in coord
Parameters
----------
%(CFDecoder.get_plotbounds.parameters.no_ignore_shape)s
Returns
-------
%(CFDecoder.get_plotbounds.returns)s
Notes
-----
this currently only works for rectilinear grids | entailment |
def _decode_ds(cls, ds, gridfile=None, decode_coords=True,
decode_times=True):
"""
Static method to decode coordinates and time informations
This method interpretes absolute time informations (stored with units
``'day as %Y%m%d.%f'``) and coordinates
Parameters
----------
%(CFDecoder.decode_coords.parameters)s
decode_times : bool, optional
If True, decode times encoded in the standard NetCDF datetime
format into datetime objects. Otherwise, leave them encoded as
numbers.
decode_coords : bool, optional
If True, decode the 'coordinates' attribute to identify coordinates
in the resulting dataset."""
if decode_coords:
ds = cls.decode_coords(ds, gridfile=gridfile)
if decode_times:
for k, v in six.iteritems(ds.variables):
# check for absolute time units and make sure the data is not
# already decoded via dtype check
if v.attrs.get('units', '') == 'day as %Y%m%d.%f' and (
np.issubdtype(v.dtype, np.float64)):
decoded = xr.Variable(
v.dims, AbsoluteTimeDecoder(v), attrs=v.attrs,
encoding=v.encoding)
ds.update({k: decoded})
return ds | Static method to decode coordinates and time informations
This method interpretes absolute time informations (stored with units
``'day as %Y%m%d.%f'``) and coordinates
Parameters
----------
%(CFDecoder.decode_coords.parameters)s
decode_times : bool, optional
If True, decode times encoded in the standard NetCDF datetime
format into datetime objects. Otherwise, leave them encoded as
numbers.
decode_coords : bool, optional
If True, decode the 'coordinates' attribute to identify coordinates
in the resulting dataset. | entailment |
def decode_ds(cls, ds, *args, **kwargs):
"""
Static method to decode coordinates and time informations
This method interpretes absolute time informations (stored with units
``'day as %Y%m%d.%f'``) and coordinates
Parameters
----------
%(CFDecoder._decode_ds.parameters)s
Returns
-------
xarray.Dataset
The decoded dataset"""
for decoder_cls in cls._registry + [CFDecoder]:
ds = decoder_cls._decode_ds(ds, *args, **kwargs)
return ds | Static method to decode coordinates and time informations
This method interpretes absolute time informations (stored with units
``'day as %Y%m%d.%f'``) and coordinates
Parameters
----------
%(CFDecoder._decode_ds.parameters)s
Returns
-------
xarray.Dataset
The decoded dataset | entailment |
def correct_dims(self, var, dims={}, remove=True):
"""Expands the dimensions to match the dims in the variable
Parameters
----------
var: xarray.Variable
The variable to get the data for
dims: dict
a mapping from dimension to the slices
remove: bool
If True, dimensions in `dims` that are not in the dimensions of
`var` are removed"""
method_mapping = {'x': self.get_xname,
'z': self.get_zname, 't': self.get_tname}
dims = dict(dims)
if self.is_unstructured(var): # we assume a one-dimensional grid
method_mapping['y'] = self.get_xname
else:
method_mapping['y'] = self.get_yname
for key in six.iterkeys(dims.copy()):
if key in method_mapping and key not in var.dims:
dim_name = method_mapping[key](var, self.ds.coords)
if dim_name in dims:
dims.pop(key)
else:
new_name = method_mapping[key](var)
if new_name is not None:
dims[new_name] = dims.pop(key)
# now remove the unnecessary dimensions
if remove:
for key in set(dims).difference(var.dims):
dims.pop(key)
self.logger.debug(
"Could not find a dimensions matching %s in variable %s!",
key, var)
return dims | Expands the dimensions to match the dims in the variable
Parameters
----------
var: xarray.Variable
The variable to get the data for
dims: dict
a mapping from dimension to the slices
remove: bool
If True, dimensions in `dims` that are not in the dimensions of
`var` are removed | entailment |
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 | 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 | entailment |
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)) | 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 | entailment |
def get_triangles(self, var, coords=None, convert_radian=True, copy=False,
src_crs=None, target_crs=None, nans=None, stacklevel=1):
"""
Get the of the given coordinate.
Parameters
----------
%(CFDecoder.get_triangles.parameters)s
Returns
-------
%(CFDecoder.get_triangles.returns)s
Notes
-----
If the ``'location'`` attribute is set to ``'node'``, a delaunay
triangulation is performed using the
:class:`matplotlib.tri.Triangulation` class.
.. todo::
Implement the visualization for UGrid data shown on the edge of the
triangles"""
warn("The 'get_triangles' method is depreceated and will be removed "
"soon! Use the 'get_cell_node_coord' method!",
DeprecationWarning, stacklevel=stacklevel)
from matplotlib.tri import Triangulation
if coords is None:
coords = self.ds.coords
def get_coord(coord):
return coords.get(coord, self.ds.coords.get(coord))
mesh = self.get_mesh(var, coords)
nodes = self.get_nodes(mesh, coords)
if any(n is None for n in nodes):
raise ValueError("Could not find the nodes variables!")
xvert, yvert = nodes
xvert = xvert.values
yvert = yvert.values
loc = var.attrs.get('location', 'face')
if loc == 'face':
triangles = get_coord(
mesh.attrs.get('face_node_connectivity', '')).values
if triangles is None:
raise ValueError(
"Could not find the connectivity information!")
elif loc == 'node':
triangles = None
else:
raise ValueError(
"Could not interprete location attribute (%s) of mesh "
"variable %s!" % (loc, mesh.name))
if convert_radian:
for coord in nodes:
if coord.attrs.get('units') == 'radian':
coord = coord * 180. / np.pi
if src_crs is not None and src_crs != target_crs:
if target_crs is None:
raise ValueError(
"Found %s for the source crs but got None for the "
"target_crs!" % (src_crs, ))
xvert = xvert[triangles].ravel()
yvert = yvert[triangles].ravel()
arr = target_crs.transform_points(src_crs, xvert, yvert)
xvert = arr[:, 0]
yvert = arr[:, 1]
if loc == 'face':
triangles = np.reshape(range(len(xvert)), (len(xvert) // 3,
3))
return Triangulation(xvert, yvert, triangles) | Get the of the given coordinate.
Parameters
----------
%(CFDecoder.get_triangles.parameters)s
Returns
-------
%(CFDecoder.get_triangles.returns)s
Notes
-----
If the ``'location'`` attribute is set to ``'node'``, a delaunay
triangulation is performed using the
:class:`matplotlib.tri.Triangulation` class.
.. todo::
Implement the visualization for UGrid data shown on the edge of the
triangles | entailment |
def get_cell_node_coord(self, var, coords=None, axis='x', nans=None):
"""
Checks whether the bounds in the variable attribute are triangular
Parameters
----------
%(CFDecoder.get_cell_node_coord.parameters)s
Returns
-------
%(CFDecoder.get_cell_node_coord.returns)s"""
if coords is None:
coords = self.ds.coords
idims = self.get_coord_idims(coords)
def get_coord(coord):
coord = coords.get(coord, self.ds.coords.get(coord))
return coord.isel(**{d: sl for d, sl in idims.items()
if d in coord.dims})
mesh = self.get_mesh(var, coords)
if mesh is None:
return
nodes = self.get_nodes(mesh, coords)
if not len(nodes):
raise ValueError("Could not find the nodes variables for the %s "
"coordinate!" % axis)
vert = nodes[0 if axis == 'x' else 1]
if vert is None:
raise ValueError("Could not find the nodes variables for the %s "
"coordinate!" % axis)
loc = var.attrs.get('location', 'face')
if loc == 'node':
# we assume a triangular grid and use matplotlibs triangulation
from matplotlib.tri import Triangulation
xvert, yvert = nodes
triangles = Triangulation(xvert, yvert)
if axis == 'x':
bounds = triangles.x[triangles.triangles]
else:
bounds = triangles.y[triangles.triangles]
elif loc in ['edge', 'face']:
connectivity = get_coord(
mesh.attrs.get('%s_node_connectivity' % loc, ''))
if connectivity is None:
raise ValueError(
"Could not find the connectivity information!")
connectivity = connectivity.values
bounds = vert.values[
np.where(np.isnan(connectivity), connectivity[:, :1],
connectivity).astype(int)]
else:
raise ValueError(
"Could not interprete location attribute (%s) of mesh "
"variable %s!" % (loc, mesh.name))
dim0 = '__face' if loc == 'node' else var.dims[-1]
return xr.DataArray(
bounds,
coords={key: val for key, val in coords.items()
if (dim0, ) == val.dims},
dims=(dim0, '__bnds', ),
name=vert.name + '_bnds', attrs=vert.attrs.copy()) | Checks whether the bounds in the variable attribute are triangular
Parameters
----------
%(CFDecoder.get_cell_node_coord.parameters)s
Returns
-------
%(CFDecoder.get_cell_node_coord.returns)s | entailment |
def decode_coords(ds, gridfile=None):
"""
Reimplemented to set the mesh variables as coordinates
Parameters
----------
%(CFDecoder.decode_coords.parameters)s
Returns
-------
%(CFDecoder.decode_coords.returns)s"""
extra_coords = set(ds.coords)
for var in six.itervalues(ds.variables):
if 'mesh' in var.attrs:
mesh = var.attrs['mesh']
if mesh not in extra_coords:
extra_coords.add(mesh)
try:
mesh_var = ds.variables[mesh]
except KeyError:
warn('Could not find mesh variable %s' % mesh)
continue
if 'node_coordinates' in mesh_var.attrs:
extra_coords.update(
mesh_var.attrs['node_coordinates'].split())
if 'face_node_connectivity' in mesh_var.attrs:
extra_coords.add(
mesh_var.attrs['face_node_connectivity'])
if gridfile is not None and not isinstance(gridfile, xr.Dataset):
gridfile = open_dataset(gridfile)
ds.update({k: v for k, v in six.iteritems(gridfile.variables)
if k in extra_coords})
if xr_version < (0, 11):
ds.set_coords(extra_coords.intersection(ds.variables),
inplace=True)
else:
ds._coord_names.update(extra_coords.intersection(ds.variables))
return ds | Reimplemented to set the mesh variables as coordinates
Parameters
----------
%(CFDecoder.decode_coords.parameters)s
Returns
-------
%(CFDecoder.decode_coords.returns)s | entailment |
def get_nodes(self, coord, coords):
"""Get the variables containing the definition of the nodes
Parameters
----------
coord: xarray.Coordinate
The mesh variable
coords: dict
The coordinates to use to get node coordinates"""
def get_coord(coord):
return coords.get(coord, self.ds.coords.get(coord))
return list(map(get_coord,
coord.attrs.get('node_coordinates', '').split()[:2])) | Get the variables containing the definition of the nodes
Parameters
----------
coord: xarray.Coordinate
The mesh variable
coords: dict
The coordinates to use to get node coordinates | entailment |
def get_x(self, var, coords=None):
"""
Get the centers of the triangles in the x-dimension
Parameters
----------
%(CFDecoder.get_y.parameters)s
Returns
-------
%(CFDecoder.get_y.returns)s"""
if coords is None:
coords = self.ds.coords
# first we try the super class
ret = super(UGridDecoder, self).get_x(var, coords)
# but if that doesn't work because we get the variable name in the
# dimension of `var`, we use the means of the triangles
if ret is None or ret.name in var.dims:
bounds = self.get_cell_node_coord(var, axis='x', coords=coords)
if bounds is not None:
centers = bounds.mean(axis=-1)
x = self.get_nodes(self.get_mesh(var, coords), coords)[0]
try:
cls = xr.IndexVariable
except AttributeError: # xarray < 0.9
cls = xr.Coordinate
return cls(x.name, centers, attrs=x.attrs.copy()) | Get the centers of the triangles in the x-dimension
Parameters
----------
%(CFDecoder.get_y.parameters)s
Returns
-------
%(CFDecoder.get_y.returns)s | entailment |
def plot(self):
"""An object to visualize this data object
To make a 2D-plot with the :mod:`psy-simple <psy_simple.plugin>`
plugin, you can just type
.. code-block:: python
plotter = da.psy.plot.plot2d()
It will create a new :class:`psyplot.plotter.Plotter` instance with the
extracted and visualized data.
See Also
--------
psyplot.project.DataArrayPlotter: for the different plot methods"""
if self._plot is None:
import psyplot.project as psy
self._plot = psy.DataArrayPlotter(self)
return self._plot | An object to visualize this data object
To make a 2D-plot with the :mod:`psy-simple <psy_simple.plugin>`
plugin, you can just type
.. code-block:: python
plotter = da.psy.plot.plot2d()
It will create a new :class:`psyplot.plotter.Plotter` instance with the
extracted and visualized data.
See Also
--------
psyplot.project.DataArrayPlotter: for the different plot methods | entailment |
def _register_update(self, replot=False, fmt={}, force=False,
todefault=False):
"""
Register new formatoptions for updating
Parameters
----------
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not. Note, if `dims` is not empty
or any coordinate keyword is in ``**kwargs``, this will be set to
True automatically
fmt: dict
Keys may be any valid formatoption of the formatoptions in the
:attr:`plotter`
force: str, list of str or bool
If formatoption key (i.e. string) or list of formatoption keys,
thery are definitely updated whether they changed or not.
If True, all the given formatoptions in this call of the are
:meth:`update` method are updated
todefault: bool
If True, all changed formatoptions (except the registered ones)
are updated to their default value as stored in the
:attr:`~psyplot.plotter.Plotter.rc` attribute
See Also
--------
start_update"""
self.replot = self.replot or replot
if self.plotter is not None:
self.plotter._register_update(replot=self.replot, fmt=fmt,
force=force, todefault=todefault) | Register new formatoptions for updating
Parameters
----------
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not. Note, if `dims` is not empty
or any coordinate keyword is in ``**kwargs``, this will be set to
True automatically
fmt: dict
Keys may be any valid formatoption of the formatoptions in the
:attr:`plotter`
force: str, list of str or bool
If formatoption key (i.e. string) or list of formatoption keys,
thery are definitely updated whether they changed or not.
If True, all the given formatoptions in this call of the are
:meth:`update` method are updated
todefault: bool
If True, all changed formatoptions (except the registered ones)
are updated to their default value as stored in the
:attr:`~psyplot.plotter.Plotter.rc` attribute
See Also
--------
start_update | entailment |
def start_update(self, draw=None, queues=None):
"""
Conduct the formerly registered updates
This method conducts the updates that have been registered via the
:meth:`update` method. You can call this method if the
:attr:`no_auto_update` attribute of this instance and the `auto_update`
parameter in the :meth:`update` method has been set to False
Parameters
----------
draw: bool or None
Boolean to control whether the figure of this array shall be drawn
at the end. If None, it defaults to the `'auto_draw'`` parameter
in the :attr:`psyplot.rcParams` dictionary
queues: list of :class:`Queue.Queue` instances
The queues that are passed to the
:meth:`psyplot.plotter.Plotter.start_update` method to ensure a
thread-safe update. It can be None if only one single plotter is
updated at the same time. The number of jobs that are taken from
the queue is determined by the :meth:`_njobs` attribute. Note that
there this parameter is automatically configured when updating
from a :class:`~psyplot.project.Project`.
Returns
-------
bool
A boolean indicating whether a redrawing is necessary or not
See Also
--------
:attr:`no_auto_update`, update
"""
if self.plotter is not None:
return self.plotter.start_update(draw=draw, queues=queues) | Conduct the formerly registered updates
This method conducts the updates that have been registered via the
:meth:`update` method. You can call this method if the
:attr:`no_auto_update` attribute of this instance and the `auto_update`
parameter in the :meth:`update` method has been set to False
Parameters
----------
draw: bool or None
Boolean to control whether the figure of this array shall be drawn
at the end. If None, it defaults to the `'auto_draw'`` parameter
in the :attr:`psyplot.rcParams` dictionary
queues: list of :class:`Queue.Queue` instances
The queues that are passed to the
:meth:`psyplot.plotter.Plotter.start_update` method to ensure a
thread-safe update. It can be None if only one single plotter is
updated at the same time. The number of jobs that are taken from
the queue is determined by the :meth:`_njobs` attribute. Note that
there this parameter is automatically configured when updating
from a :class:`~psyplot.project.Project`.
Returns
-------
bool
A boolean indicating whether a redrawing is necessary or not
See Also
--------
:attr:`no_auto_update`, update | entailment |
def update(self, fmt={}, replot=False, draw=None, auto_update=False,
force=False, todefault=False, **kwargs):
"""
Update the coordinates and the plot
This method updates all arrays in this list with the given coordinate
values and formatoptions.
Parameters
----------
%(InteractiveBase._register_update.parameters)s
auto_update: bool
Boolean determining whether or not the :meth:`start_update` method
is called at the end. This parameter has no effect if the
:attr:`no_auto_update` attribute is set to ``True``.
%(InteractiveBase.start_update.parameters.draw)s
``**kwargs``
Any other formatoption that shall be updated (additionally to those
in `fmt`)
Notes
-----
If the :attr:`no_auto_update` attribute is True and the given
`auto_update` parameter are is False, the update of the plots are
registered and conducted at the next call of the :meth:`start_update`
method or the next call of this method (if the `auto_update` parameter
is then True).
"""
fmt = dict(fmt)
fmt.update(kwargs)
self._register_update(replot=replot, fmt=fmt, force=force,
todefault=todefault)
if not self.no_auto_update or auto_update:
self.start_update(draw=draw) | Update the coordinates and the plot
This method updates all arrays in this list with the given coordinate
values and formatoptions.
Parameters
----------
%(InteractiveBase._register_update.parameters)s
auto_update: bool
Boolean determining whether or not the :meth:`start_update` method
is called at the end. This parameter has no effect if the
:attr:`no_auto_update` attribute is set to ``True``.
%(InteractiveBase.start_update.parameters.draw)s
``**kwargs``
Any other formatoption that shall be updated (additionally to those
in `fmt`)
Notes
-----
If the :attr:`no_auto_update` attribute is True and the given
`auto_update` parameter are is False, the update of the plots are
registered and conducted at the next call of the :meth:`start_update`
method or the next call of this method (if the `auto_update` parameter
is then True). | entailment |
def dims_intersect(self):
"""Dimensions of the arrays in this list that are used in all arrays
"""
return set.intersection(*map(
set, (getattr(arr, 'dims_intersect', arr.dims) for arr in self))) | Dimensions of the arrays in this list that are used in all arrays | entailment |
def names(self):
"""Set of the variable in this list"""
ret = set()
for arr in self:
if isinstance(arr, InteractiveList):
ret.update(arr.names)
else:
ret.add(arr.name)
return ret | Set of the variable in this list | entailment |
def all_names(self):
"""The variable names for each of the arrays in this list"""
return [
_get_variable_names(arr) if not isinstance(arr, ArrayList) else
arr.all_names
for arr in self] | The variable names for each of the arrays in this list | entailment |
def all_dims(self):
"""The dimensions for each of the arrays in this list"""
return [
_get_dims(arr) if not isinstance(arr, ArrayList) else
arr.all_dims
for arr in self] | The dimensions for each of the arrays in this list | entailment |
def is_unstructured(self):
"""A boolean for each array whether it is unstructured or not"""
return [
arr.psy.decoder.is_unstructured(arr)
if not isinstance(arr, ArrayList) else
arr.is_unstructured
for arr in self] | A boolean for each array whether it is unstructured or not | entailment |
def coords_intersect(self):
"""Coordinates of the arrays in this list that are used in all arrays
"""
return set.intersection(*map(
set, (getattr(arr, 'coords_intersect', arr.coords) for arr in self)
)) | Coordinates of the arrays in this list that are used in all arrays | entailment |
def with_plotter(self):
"""The arrays in this instance that are visualized with a plotter"""
return self.__class__(
(arr for arr in self if arr.psy.plotter is not None),
auto_update=bool(self.auto_update)) | The arrays in this instance that are visualized with a plotter | entailment |
def arrays(self):
"""A list of all the :class:`xarray.DataArray` instances in this list
"""
return list(chain.from_iterable(
([arr] if not isinstance(arr, InteractiveList) else arr.arrays
for arr in self))) | A list of all the :class:`xarray.DataArray` instances in this list | entailment |
def rename(self, arr, new_name=True):
"""
Rename an array to find a name that isn't already in the list
Parameters
----------
arr: InteractiveBase
A :class:`InteractiveArray` or :class:`InteractiveList` instance
whose name shall be checked
new_name: bool or str
If False, and the ``arr_name`` attribute of the new array is
already in the list, a ValueError is raised.
If True and the ``arr_name`` attribute of the new array is not
already in the list, the name is not changed. Otherwise, if the
array name is already in use, `new_name` is set to 'arr{0}'.
If not True, this will be used for renaming (if the array name of
`arr` is in use or not). ``'{0}'`` is replaced by a counter
Returns
-------
InteractiveBase
`arr` with changed ``arr_name`` attribute
bool or None
True, if the array has been renamed, False if not and None if the
array is already in the list
Raises
------
ValueError
If it was impossible to find a name that isn't already in the list
ValueError
If `new_name` is False and the array is already in the list"""
name_in_me = arr.psy.arr_name in self.arr_names
if not name_in_me:
return arr, False
elif name_in_me and not self._contains_array(arr):
if new_name is False:
raise ValueError(
"Array name %s is already in use! Set the `new_name` "
"parameter to None for renaming!" % arr.psy.arr_name)
elif new_name is True:
new_name = new_name if isstring(new_name) else 'arr{0}'
arr.psy.arr_name = self.next_available_name(new_name)
return arr, True
return arr, None | Rename an array to find a name that isn't already in the list
Parameters
----------
arr: InteractiveBase
A :class:`InteractiveArray` or :class:`InteractiveList` instance
whose name shall be checked
new_name: bool or str
If False, and the ``arr_name`` attribute of the new array is
already in the list, a ValueError is raised.
If True and the ``arr_name`` attribute of the new array is not
already in the list, the name is not changed. Otherwise, if the
array name is already in use, `new_name` is set to 'arr{0}'.
If not True, this will be used for renaming (if the array name of
`arr` is in use or not). ``'{0}'`` is replaced by a counter
Returns
-------
InteractiveBase
`arr` with changed ``arr_name`` attribute
bool or None
True, if the array has been renamed, False if not and None if the
array is already in the list
Raises
------
ValueError
If it was impossible to find a name that isn't already in the list
ValueError
If `new_name` is False and the array is already in the list | entailment |
def copy(self, deep=False):
"""Returns a copy of the list
Parameters
----------
deep: bool
If False (default), only the list is copied and not the contained
arrays, otherwise the contained arrays are deep copied"""
if not deep:
return self.__class__(self[:], attrs=self.attrs.copy(),
auto_update=not bool(self.no_auto_update))
else:
return self.__class__(
[arr.psy.copy(deep) for arr in self], attrs=self.attrs.copy(),
auto_update=not bool(self.auto_update)) | Returns a copy of the list
Parameters
----------
deep: bool
If False (default), only the list is copied and not the contained
arrays, otherwise the contained arrays are deep copied | entailment |
def from_dataset(cls, base, method='isel', default_slice=None,
decoder=None, auto_update=None, prefer_list=False,
squeeze=True, attrs=None, load=False, **kwargs):
"""
Construct an ArrayList instance from an existing base dataset
Parameters
----------
base: xarray.Dataset
Dataset instance that is used as reference
%(InteractiveArray.update.parameters.method)s
%(InteractiveBase.parameters.auto_update)s
prefer_list: bool
If True and multiple variable names pher array are found, the
:class:`InteractiveList` class is used. Otherwise the arrays are
put together into one :class:`InteractiveArray`.
default_slice: indexer
Index (e.g. 0 if `method` is 'isel') that shall be used for
dimensions not covered by `dims` and `furtherdims`. If None, the
whole slice will be used.
decoder: CFDecoder
The decoder that shall be used to decoder the `base` dataset
squeeze: bool, optional
Default True. If True, and the created arrays have a an axes with
length 1, it is removed from the dimension list (e.g. an array
with shape (3, 4, 1, 5) will be squeezed to shape (3, 4, 5))
attrs: dict, optional
Meta attributes that shall be assigned to the selected data arrays
(additional to those stored in the `base` dataset)
load: bool or dict
If True, load the data from the dataset using the
:meth:`xarray.DataArray.load` method. If :class:`dict`, those will
be given to the above mentioned ``load`` method
Other Parameters
----------------
%(setup_coords.parameters)s
Returns
-------
ArrayList
The list with the specified :class:`InteractiveArray` instances
that hold a reference to the given `base`"""
try:
load = dict(load)
except (TypeError, ValueError):
def maybe_load(arr):
return arr.load() if load else arr
else:
def maybe_load(arr):
return arr.load(**load)
def iter_dims(dims):
"""Split the given dictionary into multiples and iterate over it"""
if not dims:
while 1:
yield {}
else:
dims = OrderedDict(dims)
keys = dims.keys()
for vals in zip(*map(cycle, map(safe_list, dims.values()))):
yield dict(zip(keys, vals))
def recursive_selection(key, dims, names):
names = safe_list(names)
if len(names) > 1 and prefer_list:
keys = ('arr%i' % i for i in range(len(names)))
return InteractiveList(
starmap(sel_method, zip(keys, iter_dims(dims), names)),
auto_update=auto_update, arr_name=key)
elif len(names) > 1:
return sel_method(key, dims, tuple(names))
else:
return sel_method(key, dims, names[0])
def ds2arr(arr):
base_var = next(var for key, var in arr.variables.items()
if key not in arr.coords)
attrs = base_var.attrs
arr = arr.to_array()
if 'coordinates' in base_var.encoding:
arr.encoding['coordinates'] = base_var.encoding[
'coordinates']
arr.attrs.update(attrs)
return arr
if decoder is not None:
def get_decoder(arr):
return decoder
else:
def get_decoder(arr):
return CFDecoder.get_decoder(base, arr)
def add_missing_dimensions(arr):
# add the missing dimensions to the dataset. This is not anymore
# done by default from xarray >= 0.9 but we need it to ensure the
# interactive treatment of DataArrays
missing = set(arr.dims).difference(base.coords) - {'variable'}
for dim in missing:
base[dim] = arr.coords[dim] = np.arange(base.dims[dim])
if squeeze:
def squeeze_array(arr):
return arr.isel(**{dim: 0 for i, dim in enumerate(arr.dims)
if arr.shape[i] == 1})
else:
def squeeze_array(arr):
return arr
if method == 'isel':
def sel_method(key, dims, name=None):
if name is None:
return recursive_selection(key, dims, dims.pop('name'))
elif (isinstance(name, six.string_types) or
not utils.is_iterable(name)):
arr = base[name]
else:
arr = base[list(name)]
add_missing_dimensions(arr)
if not isinstance(arr, xr.DataArray):
arr = ds2arr(arr)
def_slice = slice(None) if default_slice is None else \
default_slice
decoder = get_decoder(arr)
dims = decoder.correct_dims(arr, dims)
dims.update({
dim: def_slice for dim in set(arr.dims).difference(
dims) if dim != 'variable'})
ret = squeeze_array(arr.isel(**dims))
# delete the variable dimension for the idims
dims.pop('variable', None)
ret.psy.init_accessor(arr_name=key, base=base, idims=dims)
return maybe_load(ret)
else:
def sel_method(key, dims, name=None):
if name is None:
return recursive_selection(key, dims, dims.pop('name'))
elif (isinstance(name, six.string_types) or
not utils.is_iterable(name)):
arr = base[name]
else:
arr = base[list(name)]
add_missing_dimensions(arr)
if not isinstance(arr, xr.DataArray):
arr = ds2arr(arr)
# idims will be calculated by the array (maybe not the most
# efficient way...)
decoder = get_decoder(arr)
dims = decoder.correct_dims(arr, dims)
if default_slice is not None:
dims.update({
key: default_slice for key in set(arr.dims).difference(
dims) if key != 'variable'})
# the sel method does not work with slice objects
if any(isinstance(idx, slice) for idx in dims.values()):
# ignore method argument
ret = squeeze_array(arr.sel(**dims))
else:
ret = squeeze_array(arr.sel(method=method, **dims))
ret.psy.init_accessor(arr_name=key, base=base)
return maybe_load(ret)
if 'name' not in kwargs:
default_names = list(
key for key in base.variables if key not in base.coords)
try:
default_names.sort()
except TypeError:
pass
kwargs['name'] = default_names
names = setup_coords(**kwargs)
# check coordinates
possible_keys = ['t', 'x', 'y', 'z', 'name'] + list(base.dims)
for key in set(chain(*six.itervalues(names))):
utils.check_key(key, possible_keys, name='dimension')
instance = cls(starmap(sel_method, six.iteritems(names)),
attrs=base.attrs, auto_update=auto_update)
# convert to interactive lists if an instance is not
if prefer_list and any(
not isinstance(arr, InteractiveList) for arr in instance):
# if any instance is an interactive list, than convert the others
if any(isinstance(arr, InteractiveList) for arr in instance):
for i, arr in enumerate(instance):
if not isinstance(arr, InteractiveList):
instance[i] = InteractiveList([arr])
else: # put everything into one single interactive list
instance = cls([InteractiveList(instance, attrs=base.attrs,
auto_update=auto_update)])
instance[0].psy.arr_name = instance[0][0].psy.arr_name
if attrs is not None:
for arr in instance:
arr.attrs.update(attrs)
return instance | Construct an ArrayList instance from an existing base dataset
Parameters
----------
base: xarray.Dataset
Dataset instance that is used as reference
%(InteractiveArray.update.parameters.method)s
%(InteractiveBase.parameters.auto_update)s
prefer_list: bool
If True and multiple variable names pher array are found, the
:class:`InteractiveList` class is used. Otherwise the arrays are
put together into one :class:`InteractiveArray`.
default_slice: indexer
Index (e.g. 0 if `method` is 'isel') that shall be used for
dimensions not covered by `dims` and `furtherdims`. If None, the
whole slice will be used.
decoder: CFDecoder
The decoder that shall be used to decoder the `base` dataset
squeeze: bool, optional
Default True. If True, and the created arrays have a an axes with
length 1, it is removed from the dimension list (e.g. an array
with shape (3, 4, 1, 5) will be squeezed to shape (3, 4, 5))
attrs: dict, optional
Meta attributes that shall be assigned to the selected data arrays
(additional to those stored in the `base` dataset)
load: bool or dict
If True, load the data from the dataset using the
:meth:`xarray.DataArray.load` method. If :class:`dict`, those will
be given to the above mentioned ``load`` method
Other Parameters
----------------
%(setup_coords.parameters)s
Returns
-------
ArrayList
The list with the specified :class:`InteractiveArray` instances
that hold a reference to the given `base` | entailment |
def _get_dsnames(cls, data, ignore_keys=['attrs', 'plotter', 'ds'],
concat_dim=False):
"""Recursive method to get all the file names out of a dictionary
`data` created with the :meth`array_info` method"""
def filter_ignores(item):
return item[0] not in ignore_keys and isinstance(item[1], dict)
if 'fname' in data:
return {tuple(
[data['fname'], data['store']] +
([data.get('concat_dim')] if concat_dim else []))}
return set(chain(*map(partial(cls._get_dsnames, concat_dim=concat_dim,
ignore_keys=ignore_keys),
dict(filter(filter_ignores,
six.iteritems(data))).values()))) | Recursive method to get all the file names out of a dictionary
`data` created with the :meth`array_info` method | entailment |
def _get_ds_descriptions_unsorted(
cls, data, ignore_keys=['attrs', 'plotter'], nums=None):
"""Recursive method to get all the file names or datasets out of a
dictionary `data` created with the :meth`array_info` method"""
ds_description = {'ds', 'fname', 'num', 'arr', 'store'}
if 'ds' in data:
# make sure that the data set has a number assigned to it
data['ds'].psy.num
keys_in_data = ds_description.intersection(data)
if keys_in_data:
return {key: data[key] for key in keys_in_data}
for key in ignore_keys:
data.pop(key, None)
func = partial(cls._get_ds_descriptions_unsorted,
ignore_keys=ignore_keys, nums=nums)
return chain(*map(lambda d: [d] if isinstance(d, dict) else d,
map(func, six.itervalues(data)))) | Recursive method to get all the file names or datasets out of a
dictionary `data` created with the :meth`array_info` method | entailment |
def from_dict(cls, d, alternative_paths={}, datasets=None,
pwd=None, ignore_keys=['attrs', 'plotter', 'ds'],
only=None, chname={}, **kwargs):
"""
Create a list from the dictionary returned by :meth:`array_info`
This classmethod creates an :class:`~psyplot.data.ArrayList` instance
from a dictionary containing filename, dimension infos and array names
Parameters
----------
d: dict
The dictionary holding the data
alternative_paths: dict or list or str
A mapping from original filenames as used in `d` to filenames that
shall be used instead. If `alternative_paths` is not None,
datasets must be None. Paths must be accessible from the current
working directory.
If `alternative_paths` is a list (or any other iterable) is
provided, the file names will be replaced as they appear in `d`
(note that this is very unsafe if `d` is not and OrderedDict)
datasets: dict or list or None
A mapping from original filenames in `d` to the instances of
:class:`xarray.Dataset` to use. If it is an iterable, the same
holds as for the `alternative_paths` parameter
pwd: str
Path to the working directory from where the data can be imported.
If None, use the current working directory.
ignore_keys: list of str
Keys specified in this list are ignored and not seen as array
information (note that ``attrs`` are used anyway)
only: string, list or callable
Can be one of the following three things:
- a string that represents a pattern to match the array names
that shall be included
- a list of array names to include
- a callable with two arguments, a string and a dict such as
.. code-block:: python
def filter_func(arr_name: str, info: dict): -> bool
'''
Filter the array names
This function should return True if the array shall be
included, else False
Parameters
----------
arr_name: str
The array name (i.e. the ``arr_name`` attribute)
info: dict
The dictionary with the array informations. Common
keys are ``'name'`` that points to the variable name
and ``'dims'`` that points to the dimensions and
``'fname'`` that points to the file name
'''
return True or False
The function should return ``True`` if the array shall be
included, else ``False``. This function will also be given to
subsequents instances of :class:`InteractiveList` objects that
are contained in the returned value
chname: dict
A mapping from variable names in the project to variable names
that should be used instead
Other Parameters
----------------
``**kwargs``
Any other parameter from the `psyplot.data.open_dataset` function
%(open_dataset.parameters)s
Returns
-------
psyplot.data.ArrayList
The list with the interactive objects
See Also
--------
from_dataset, array_info"""
pwd = pwd or getcwd()
if only is None:
def only_filter(arr_name, info):
return True
elif callable(only):
only_filter = only
elif isstring(only):
def only_filter(arr_name, info):
return patt.search(arr_name) is not None
patt = re.compile(only)
only = None
else:
def only_filter(arr_name, info):
return arr_name in save_only
save_only = only
only = None
def get_fname_use(fname):
squeeze = isstring(fname)
fname = safe_list(fname)
ret = tuple(f if utils.is_remote_url(f) or osp.isabs(f) else
osp.join(pwd, f)
for f in fname)
return ret[0] if squeeze else ret
def get_name(name):
if not isstring(name):
return list(map(get_name, name))
else:
return chname.get(name, name)
if not isinstance(alternative_paths, dict):
it = iter(alternative_paths)
alternative_paths = defaultdict(partial(next, it, None))
# first open all datasets if not already done
if datasets is None:
replace_concat_dim = 'concat_dim' not in kwargs
names_and_stores = cls._get_dsnames(d, concat_dim=True)
datasets = {}
for fname, (store_mod, store_cls), concat_dim in names_and_stores:
fname_use = fname
got = True
if replace_concat_dim and concat_dim is not None:
kwargs['concat_dim'] = concat_dim
elif replace_concat_dim and concat_dim is None:
kwargs.pop('concat_dim', None)
try:
fname_use = alternative_paths[fname]
except KeyError:
got = False
if not got or not fname_use:
if fname is not None:
fname_use = get_fname_use(fname)
if fname_use is not None:
datasets[fname] = _open_ds_from_store(
fname_use, store_mod, store_cls, **kwargs)
if alternative_paths is not None:
for fname in set(alternative_paths).difference(datasets):
datasets[fname] = _open_ds_from_store(fname, **kwargs)
elif not isinstance(datasets, dict):
it_datasets = iter(datasets)
datasets = defaultdict(partial(next, it_datasets, None))
arrays = [0] * len(d)
i = 0
for arr_name, info in six.iteritems(d):
if arr_name in ignore_keys or not only_filter(arr_name, info):
arrays.pop(i)
continue
if not {'fname', 'ds', 'arr'}.intersection(info):
# the described object is an InteractiveList
arr = InteractiveList.from_dict(
info, alternative_paths=alternative_paths,
datasets=datasets, chname=chname)
if not arr:
warn("Skipping empty list %s!" % arr_name)
arrays.pop(i)
continue
else:
if 'arr' in info:
arr = info.pop('arr')
elif 'ds' in info:
arr = cls.from_dataset(
info['ds'], dims=info['dims'],
name=get_name(info['name']))[0]
else:
fname = info['fname']
if fname is None:
warn("Could not open array %s because no filename was "
"specified!" % arr_name)
arrays.pop(i)
continue
try: # in case, datasets is a defaultdict
datasets[fname]
except KeyError:
pass
if fname not in datasets:
warn("Could not open array %s because %s was not in "
"the list of datasets!" % (arr_name, fname))
arrays.pop(i)
continue
arr = cls.from_dataset(
datasets[fname], dims=info['dims'],
name=get_name(info['name']))[0]
for key, val in six.iteritems(info.get('attrs', {})):
arr.attrs.setdefault(key, val)
arr.psy.arr_name = arr_name
arrays[i] = arr
i += 1
return cls(arrays, attrs=d.get('attrs', {})) | Create a list from the dictionary returned by :meth:`array_info`
This classmethod creates an :class:`~psyplot.data.ArrayList` instance
from a dictionary containing filename, dimension infos and array names
Parameters
----------
d: dict
The dictionary holding the data
alternative_paths: dict or list or str
A mapping from original filenames as used in `d` to filenames that
shall be used instead. If `alternative_paths` is not None,
datasets must be None. Paths must be accessible from the current
working directory.
If `alternative_paths` is a list (or any other iterable) is
provided, the file names will be replaced as they appear in `d`
(note that this is very unsafe if `d` is not and OrderedDict)
datasets: dict or list or None
A mapping from original filenames in `d` to the instances of
:class:`xarray.Dataset` to use. If it is an iterable, the same
holds as for the `alternative_paths` parameter
pwd: str
Path to the working directory from where the data can be imported.
If None, use the current working directory.
ignore_keys: list of str
Keys specified in this list are ignored and not seen as array
information (note that ``attrs`` are used anyway)
only: string, list or callable
Can be one of the following three things:
- a string that represents a pattern to match the array names
that shall be included
- a list of array names to include
- a callable with two arguments, a string and a dict such as
.. code-block:: python
def filter_func(arr_name: str, info: dict): -> bool
'''
Filter the array names
This function should return True if the array shall be
included, else False
Parameters
----------
arr_name: str
The array name (i.e. the ``arr_name`` attribute)
info: dict
The dictionary with the array informations. Common
keys are ``'name'`` that points to the variable name
and ``'dims'`` that points to the dimensions and
``'fname'`` that points to the file name
'''
return True or False
The function should return ``True`` if the array shall be
included, else ``False``. This function will also be given to
subsequents instances of :class:`InteractiveList` objects that
are contained in the returned value
chname: dict
A mapping from variable names in the project to variable names
that should be used instead
Other Parameters
----------------
``**kwargs``
Any other parameter from the `psyplot.data.open_dataset` function
%(open_dataset.parameters)s
Returns
-------
psyplot.data.ArrayList
The list with the interactive objects
See Also
--------
from_dataset, array_info | entailment |
def array_info(self, dump=None, paths=None, attrs=True,
standardize_dims=True, pwd=None, use_rel_paths=True,
alternative_paths={}, ds_description={'fname', 'store'},
full_ds=True, copy=False, **kwargs):
"""
Get dimension informations on you arrays
This method returns a dictionary containing informations on the
array in this instance
Parameters
----------
dump: bool
If True and the dataset has not been dumped so far, it is dumped to
a temporary file or the one generated by `paths` is used. If it is
False or both, `dump` and `paths` are None, no data will be stored.
If it is None and `paths` is not None, `dump` is set to True.
%(get_filename_ds.parameters.no_ds|dump)s
attrs: bool, optional
If True (default), the :attr:`ArrayList.attrs` and
:attr:`xarray.DataArray.attrs` attributes are included in the
returning dictionary
standardize_dims: bool, optional
If True (default), the real dimension names in the dataset are
replaced by x, y, z and t to be more general.
pwd: str
Path to the working directory from where the data can be imported.
If None, use the current working directory.
use_rel_paths: bool, optional
If True (default), paths relative to the current working directory
are used. Otherwise absolute paths to `pwd` are used
ds_description: 'all' or set of {'fname', 'ds', 'num', 'arr', 'store'}
Keys to describe the datasets of the arrays. If all, all keys
are used. The key descriptions are
fname
the file name is inserted in the ``'fname'`` key
store
the data store class and module is inserted in the ``'store'``
key
ds
the dataset is inserted in the ``'ds'`` key
num
The unique number assigned to the dataset is inserted in the
``'num'`` key
arr
The array itself is inserted in the ``'arr'`` key
full_ds: bool
If True and ``'ds'`` is in `ds_description`, the entire dataset is
included. Otherwise, only the DataArray converted to a dataset is
included
copy: bool
If True, the arrays and datasets are deep copied
Other Parameters
----------------
%(get_filename_ds.other_parameters)s
Returns
-------
OrderedDict
An ordered mapping from array names to dimensions and filename
corresponding to the array
See Also
--------
from_dict"""
saved_ds = kwargs.pop('_saved_ds', {})
def get_alternative(f):
return next(filter(lambda t: osp.samefile(f, t[0]),
six.iteritems(alternative_paths)), [False, f])
if copy:
def copy_obj(obj):
# try to get the number of the dataset and create only one copy
# copy for each dataset
try:
num = obj.psy.num
except AttributeError:
pass
else:
try:
return saved_ds[num]
except KeyError:
saved_ds[num] = obj.psy.copy(True)
return saved_ds[num]
return obj.psy.copy(True)
else:
def copy_obj(obj):
return obj
ret = OrderedDict()
if ds_description == 'all':
ds_description = {'fname', 'ds', 'num', 'arr', 'store'}
if paths is not None:
if dump is None:
dump = True
paths = iter(paths)
elif dump is None:
dump = False
if pwd is None:
pwd = getcwd()
for arr in self:
if isinstance(arr, InteractiveList):
ret[arr.arr_name] = arr.array_info(
dump, paths, pwd=pwd, attrs=attrs,
standardize_dims=standardize_dims,
use_rel_paths=use_rel_paths, ds_description=ds_description,
alternative_paths=alternative_paths, copy=copy,
_saved_ds=saved_ds, **kwargs)
else:
if standardize_dims:
idims = arr.psy.decoder.standardize_dims(
next(arr.psy.iter_base_variables), arr.psy.idims)
else:
idims = arr.psy.idims
ret[arr.psy.arr_name] = d = {'dims': idims}
if 'variable' in arr.coords:
d['name'] = [list(arr.coords['variable'].values)]
else:
d['name'] = arr.name
if 'fname' in ds_description or 'store' in ds_description:
fname, store_mod, store_cls = get_filename_ds(
arr.psy.base, dump=dump, paths=paths, **kwargs)
if 'store' in ds_description:
d['store'] = (store_mod, store_cls)
if 'fname' in ds_description:
d['fname'] = []
for i, f in enumerate(safe_list(fname)):
if (f is None or utils.is_remote_url(f)):
d['fname'].append(f)
else:
found, f = get_alternative(f)
if use_rel_paths:
f = osp.relpath(f, pwd)
else:
f = osp.abspath(f)
d['fname'].append(f)
if fname is None or isinstance(fname,
six.string_types):
d['fname'] = d['fname'][0]
else:
d['fname'] = tuple(safe_list(fname))
if arr.psy.base.psy._concat_dim is not None:
d['concat_dim'] = arr.psy.base.psy._concat_dim
if 'ds' in ds_description:
if full_ds:
d['ds'] = copy_obj(arr.psy.base)
else:
d['ds'] = copy_obj(arr.to_dataset())
if 'num' in ds_description:
d['num'] = arr.psy.base.psy.num
if 'arr' in ds_description:
d['arr'] = copy_obj(arr)
if attrs:
d['attrs'] = arr.attrs
ret['attrs'] = self.attrs
return ret | Get dimension informations on you arrays
This method returns a dictionary containing informations on the
array in this instance
Parameters
----------
dump: bool
If True and the dataset has not been dumped so far, it is dumped to
a temporary file or the one generated by `paths` is used. If it is
False or both, `dump` and `paths` are None, no data will be stored.
If it is None and `paths` is not None, `dump` is set to True.
%(get_filename_ds.parameters.no_ds|dump)s
attrs: bool, optional
If True (default), the :attr:`ArrayList.attrs` and
:attr:`xarray.DataArray.attrs` attributes are included in the
returning dictionary
standardize_dims: bool, optional
If True (default), the real dimension names in the dataset are
replaced by x, y, z and t to be more general.
pwd: str
Path to the working directory from where the data can be imported.
If None, use the current working directory.
use_rel_paths: bool, optional
If True (default), paths relative to the current working directory
are used. Otherwise absolute paths to `pwd` are used
ds_description: 'all' or set of {'fname', 'ds', 'num', 'arr', 'store'}
Keys to describe the datasets of the arrays. If all, all keys
are used. The key descriptions are
fname
the file name is inserted in the ``'fname'`` key
store
the data store class and module is inserted in the ``'store'``
key
ds
the dataset is inserted in the ``'ds'`` key
num
The unique number assigned to the dataset is inserted in the
``'num'`` key
arr
The array itself is inserted in the ``'arr'`` key
full_ds: bool
If True and ``'ds'`` is in `ds_description`, the entire dataset is
included. Otherwise, only the DataArray converted to a dataset is
included
copy: bool
If True, the arrays and datasets are deep copied
Other Parameters
----------------
%(get_filename_ds.other_parameters)s
Returns
-------
OrderedDict
An ordered mapping from array names to dimensions and filename
corresponding to the array
See Also
--------
from_dict | entailment |
def _get_tnames(self):
"""Get the name of the time coordinate of the objects in this list"""
tnames = set()
for arr in self:
if isinstance(arr, InteractiveList):
tnames.update(arr.get_tnames())
else:
tnames.add(arr.psy.decoder.get_tname(
next(arr.psy.iter_base_variables), arr.coords))
return tnames - {None} | Get the name of the time coordinate of the objects in this list | entailment |
def _register_update(self, method='isel', replot=False, dims={}, fmt={},
force=False, todefault=False):
"""
Register new dimensions and formatoptions for updating. The keywords
are the same as for each single array
Parameters
----------
%(InteractiveArray._register_update.parameters)s"""
for arr in self:
arr.psy._register_update(method=method, replot=replot, dims=dims,
fmt=fmt, force=force, todefault=todefault) | Register new dimensions and formatoptions for updating. The keywords
are the same as for each single array
Parameters
----------
%(InteractiveArray._register_update.parameters)s | entailment |
def start_update(self, draw=None):
"""
Conduct the registered plot updates
This method starts the updates from what has been registered by the
:meth:`update` method. You can call this method if you did not set the
`auto_update` parameter when calling the :meth:`update` method to True
and when the :attr:`no_auto_update` attribute is True.
Parameters
----------
draw: bool or None
If True, all the figures of the arrays contained in this list will
be drawn at the end. If None, it defaults to the `'auto_draw'``
parameter in the :attr:`psyplot.rcParams` dictionary
See Also
--------
:attr:`no_auto_update`, update"""
def worker(arr):
results[arr.psy.arr_name] = arr.psy.start_update(
draw=False, queues=queues)
if len(self) == 0:
return
results = {}
threads = [Thread(target=worker, args=(arr,),
name='update_%s' % arr.psy.arr_name)
for arr in self]
jobs = [arr.psy._njobs for arr in self]
queues = [Queue() for _ in range(max(map(len, jobs)))]
# populate the queues
for i, arr in enumerate(self):
for j, n in enumerate(jobs[i]):
for k in range(n):
queues[j].put(arr.psy.arr_name)
for thread in threads:
thread.setDaemon(True)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if draw is None:
draw = rcParams['auto_draw']
if draw:
self(arr_name=[name for name, adraw in six.iteritems(results)
if adraw]).draw()
if rcParams['auto_show']:
self.show() | Conduct the registered plot updates
This method starts the updates from what has been registered by the
:meth:`update` method. You can call this method if you did not set the
`auto_update` parameter when calling the :meth:`update` method to True
and when the :attr:`no_auto_update` attribute is True.
Parameters
----------
draw: bool or None
If True, all the figures of the arrays contained in this list will
be drawn at the end. If None, it defaults to the `'auto_draw'``
parameter in the :attr:`psyplot.rcParams` dictionary
See Also
--------
:attr:`no_auto_update`, update | entailment |
def update(self, method='isel', dims={}, fmt={}, replot=False,
auto_update=False, draw=None, force=False, todefault=False,
enable_post=None, **kwargs):
"""
Update the coordinates and the plot
This method updates all arrays in this list with the given coordinate
values and formatoptions.
Parameters
----------
%(InteractiveArray._register_update.parameters)s
%(InteractiveArray.update.parameters.auto_update)s
%(ArrayList.start_update.parameters)s
enable_post: bool
If not None, enable (``True``) or disable (``False``) the
:attr:`~psyplot.plotter.Plotter.post` formatoption in the plotters
``**kwargs``
Any other formatoption or dimension that shall be updated
(additionally to those in `fmt` and `dims`)
Notes
-----
%(InteractiveArray.update.notes)s
See Also
--------
no_auto_update, start_update"""
dims = dict(dims)
fmt = dict(fmt)
vars_and_coords = set(chain(
self.dims, self.coords, ['name', 'x', 'y', 'z', 't']))
furtherdims, furtherfmt = utils.sort_kwargs(kwargs, vars_and_coords)
dims.update(furtherdims)
fmt.update(furtherfmt)
self._register_update(method=method, replot=replot, dims=dims, fmt=fmt,
force=force, todefault=todefault)
if enable_post is not None:
for arr in self.with_plotter:
arr.psy.plotter.enable_post = enable_post
if not self.no_auto_update or auto_update:
self.start_update(draw) | Update the coordinates and the plot
This method updates all arrays in this list with the given coordinate
values and formatoptions.
Parameters
----------
%(InteractiveArray._register_update.parameters)s
%(InteractiveArray.update.parameters.auto_update)s
%(ArrayList.start_update.parameters)s
enable_post: bool
If not None, enable (``True``) or disable (``False``) the
:attr:`~psyplot.plotter.Plotter.post` formatoption in the plotters
``**kwargs``
Any other formatoption or dimension that shall be updated
(additionally to those in `fmt` and `dims`)
Notes
-----
%(InteractiveArray.update.notes)s
See Also
--------
no_auto_update, start_update | entailment |
def draw(self):
"""Draws all the figures in this instance"""
for fig in set(chain(*map(
lambda arr: arr.psy.plotter.figs2draw, self.with_plotter))):
self.logger.debug("Drawing figure %s", fig.number)
fig.canvas.draw()
for arr in self:
if arr.psy.plotter is not None:
arr.psy.plotter._figs2draw.clear()
self.logger.debug("Done drawing.") | Draws all the figures in this instance | entailment |
def _contains_array(self, val):
"""Checks whether exactly this array is in the list"""
arr = self(arr_name=val.psy.arr_name)[0]
is_not_list = any(
map(lambda a: not isinstance(a, InteractiveList),
[arr, val]))
is_list = any(map(lambda a: isinstance(a, InteractiveList),
[arr, val]))
# if one is an InteractiveList and the other not, they differ
if is_list and is_not_list:
return False
# if both are interactive lists, check the lists
if is_list:
return all(a in arr for a in val) and all(a in val for a in arr)
# else we check the shapes and values
return arr is val | Checks whether exactly this array is in the list | entailment |
def next_available_name(self, fmt_str='arr{0}', counter=None):
"""Create a new array out of the given format string
Parameters
----------
format_str: str
The base string to use. ``'{0}'`` will be replaced by a counter
counter: iterable
An iterable where the numbers should be drawn from. If None,
``range(100)`` is used
Returns
-------
str
A possible name that is not in the current project"""
names = self.arr_names
counter = counter or iter(range(1000))
try:
new_name = next(
filter(lambda n: n not in names,
map(fmt_str.format, counter)))
except StopIteration:
raise ValueError(
"{0} already in the list".format(fmt_str))
return new_name | Create a new array out of the given format string
Parameters
----------
format_str: str
The base string to use. ``'{0}'`` will be replaced by a counter
counter: iterable
An iterable where the numbers should be drawn from. If None,
``range(100)`` is used
Returns
-------
str
A possible name that is not in the current project | entailment |
def append(self, value, new_name=False):
"""
Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.append, extend, rename"""
arr, renamed = self.rename(value, new_name)
if renamed is not None:
super(ArrayList, self).append(value) | Append a new array to the list
Parameters
----------
value: InteractiveBase
The data object to append to this list
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.append, extend, rename | entailment |
def extend(self, iterable, new_name=False):
"""
Add further arrays from an iterable to this list
Parameters
----------
iterable
Any iterable that contains :class:`InteractiveBase` instances
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.extend, append, rename"""
# extend those arrays that aren't alredy in the list
super(ArrayList, self).extend(t[0] for t in filter(
lambda t: t[1] is not None, (
self.rename(arr, new_name) for arr in iterable))) | Add further arrays from an iterable to this list
Parameters
----------
iterable
Any iterable that contains :class:`InteractiveBase` instances
%(ArrayList.rename.parameters.new_name)s
Raises
------
%(ArrayList.rename.raises)s
See Also
--------
list.extend, append, rename | entailment |
def remove(self, arr):
"""Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array name is in the list"""
name = arr if isinstance(arr, six.string_types) else arr.psy.arr_name
if arr not in self:
raise ValueError(
"Array {0} not in the list".format(name))
for i, arr in enumerate(self):
if arr.psy.arr_name == name:
del self[i]
return
raise ValueError(
"No array found with name {0}".format(name)) | Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array name is in the list | entailment |
def _njobs(self):
"""%(InteractiveBase._njobs)s"""
ret = super(self.__class__, self)._njobs or [0]
ret[0] += 1
return ret | %(InteractiveBase._njobs)s | entailment |
def _register_update(self, method='isel', replot=False, dims={}, fmt={},
force=False, todefault=False):
"""
Register new dimensions and formatoptions for updating
Parameters
----------
%(InteractiveArray._register_update.parameters)s"""
ArrayList._register_update(self, method=method, dims=dims)
InteractiveBase._register_update(self, fmt=fmt, todefault=todefault,
replot=bool(dims) or replot,
force=force) | Register new dimensions and formatoptions for updating
Parameters
----------
%(InteractiveArray._register_update.parameters)s | entailment |
def start_update(self, draw=None, queues=None):
"""
Conduct the formerly registered updates
This method conducts the updates that have been registered via the
:meth:`update` method. You can call this method if the
:attr:`auto_update` attribute of this instance is True and the
`auto_update` parameter in the :meth:`update` method has been set to
False
Parameters
----------
%(InteractiveBase.start_update.parameters)s
Returns
-------
%(InteractiveBase.start_update.returns)s
See Also
--------
:attr:`no_auto_update`, update
"""
if queues is not None:
queues[0].get()
try:
for arr in self:
arr.psy.start_update(draw=False)
self.onupdate.emit()
except Exception:
self._finish_all(queues)
raise
if queues is not None:
queues[0].task_done()
return InteractiveBase.start_update(self, draw=draw, queues=queues) | Conduct the formerly registered updates
This method conducts the updates that have been registered via the
:meth:`update` method. You can call this method if the
:attr:`auto_update` attribute of this instance is True and the
`auto_update` parameter in the :meth:`update` method has been set to
False
Parameters
----------
%(InteractiveBase.start_update.parameters)s
Returns
-------
%(InteractiveBase.start_update.returns)s
See Also
--------
:attr:`no_auto_update`, update | entailment |
def from_dataset(cls, *args, **kwargs):
"""
Create an InteractiveList instance from the given base dataset
Parameters
----------
%(ArrayList.from_dataset.parameters.no_plotter)s
plotter: psyplot.plotter.Plotter
The plotter instance that is used to visualize the data in this
list
make_plot: bool
If True, the plot is made
Other Parameters
----------------
%(ArrayList.from_dataset.other_parameters.no_args_kwargs)s
``**kwargs``
Further keyword arguments may point to any of the dimensions of the
data (see `dims`)
Returns
-------
%(ArrayList.from_dataset.returns)s"""
plotter = kwargs.pop('plotter', None)
make_plot = kwargs.pop('make_plot', True)
instance = super(InteractiveList, cls).from_dataset(*args, **kwargs)
if plotter is not None:
plotter.initialize_plot(instance, make_plot=make_plot)
return instance | Create an InteractiveList instance from the given base dataset
Parameters
----------
%(ArrayList.from_dataset.parameters.no_plotter)s
plotter: psyplot.plotter.Plotter
The plotter instance that is used to visualize the data in this
list
make_plot: bool
If True, the plot is made
Other Parameters
----------------
%(ArrayList.from_dataset.other_parameters.no_args_kwargs)s
``**kwargs``
Further keyword arguments may point to any of the dimensions of the
data (see `dims`)
Returns
-------
%(ArrayList.from_dataset.returns)s | entailment |
def createVM(rh):
"""
Create a virtual machine in z/VM.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error
"""
rh.printSysLog("Enter makeVM.createVM")
dirLines = []
dirLines.append("USER " + rh.userid + " " + rh.parms['pw'] +
" " + rh.parms['priMemSize'] + " " +
rh.parms['maxMemSize'] + " " + rh.parms['privClasses'])
if 'profName' in rh.parms:
dirLines.append("INCLUDE " + rh.parms['profName'])
if 'maxCPU' in rh.parms:
dirLines.append("MACHINE ESA %i" % rh.parms['maxCPU'])
dirLines.append("CPU 00 BASE")
if 'cpuCnt' in rh.parms:
for i in range(1, rh.parms['cpuCnt']):
dirLines.append("CPU %0.2X" % i)
if 'ipl' in rh.parms:
ipl_string = "IPL %s " % rh.parms['ipl']
if 'iplParam' in rh.parms:
ipl_string += ("PARM %s " % rh.parms['iplParam'])
if 'iplLoadparam' in rh.parms:
ipl_string += ("LOADPARM %s " % rh.parms['iplLoadparam'])
dirLines.append(ipl_string)
if 'byUsers' in rh.parms:
for user in rh.parms['byUsers']:
dirLines.append("LOGONBY " + user)
priMem = rh.parms['priMemSize'].upper()
maxMem = rh.parms['maxMemSize'].upper()
if 'setReservedMem' in rh.parms and (priMem != maxMem):
reservedSize = getReservedMemSize(rh, priMem, maxMem)
if rh.results['overallRC'] != 0:
rh.printSysLog("Exit makeVM.createVM, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC']
if reservedSize != '0M':
dirLines.append("COMMAND DEF STOR RESERVED %s" % reservedSize)
# Construct the temporary file for the USER entry.
fd, tempFile = mkstemp()
to_write = '\n'.join(dirLines) + '\n'
os.write(fd, to_write.encode())
os.close(fd)
parms = ["-T", rh.userid, "-f", tempFile]
results = invokeSMCLI(rh, "Image_Create_DM", parms)
if results['overallRC'] != 0:
# SMAPI API failed.
rh.printLn("ES", results['response'])
rh.updateResults(results) # Use results from invokeSMCLI
os.remove(tempFile)
rh.printSysLog("Exit makeVM.createVM, rc: " +
str(rh.results['overallRC']))
return rh.results['overallRC'] | Create a virtual machine in z/VM.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero: error | entailment |
def showOperandLines(rh):
"""
Produce help output related to operands.
Input:
Request Handle
"""
if rh.function == 'HELP':
rh.printLn("N", " For the MakeVM function:")
else:
rh.printLn("N", "Sub-Functions(s):")
rh.printLn("N", " directory - " +
"Create a virtual machine in the z/VM user directory.")
rh.printLn("N", " help - Displays this help information.")
rh.printLn("N", " version - " +
"show the version of the makeVM function")
if rh.subfunction != '':
rh.printLn("N", "Operand(s):")
rh.printLn("N", " --cpus <cpuCnt> - " +
"Specifies the desired number of virtual CPUs the")
rh.printLn("N", " " +
"guest will have.")
rh.printLn("N", " --maxcpu <maxCpuCnt> - " +
"Specifies the maximum number of virtual CPUs the")
rh.printLn("N", " " +
"guest is allowed to define.")
rh.printLn("N", " --ipl <ipl> - " +
"Specifies an IPL disk or NSS for the virtual")
rh.printLn("N", " " +
"machine's directory entry.")
rh.printLn("N", " --logonby <byUsers> - " +
"Specifies a list of up to 8 z/VM userids who can log")
rh.printLn("N", " " +
"on to the virtual machine using their id and password.")
rh.printLn("N", " --maxMemSize <maxMem> - " +
"Specifies the maximum memory the virtual machine")
rh.printLn("N", " " +
"is allowed to define.")
rh.printLn("N", " --setReservedMem - " +
"Set the additional memory space (maxMemSize - priMemSize)")
rh.printLn("N", " " +
"as reserved memory of the virtual machine.")
rh.printLn("N", " <password> - " +
"Specifies the password for the new virtual")
rh.printLn("N", " " +
"machine.")
rh.printLn("N", " <priMemSize> - " +
"Specifies the initial memory size for the new virtual")
rh.printLn("N", " " +
"machine.")
rh.printLn("N", " <privClasses> - " +
"Specifies the privilege classes for the new virtual")
rh.printLn("N", " " +
"machine.")
rh.printLn("N", " --profile <profName> - " +
"Specifies the z/VM PROFILE to include in the")
rh.printLn("N", " " +
"virtual machine's directory entry.")
rh.printLn("N", " <userid> - " +
"Userid of the virtual machine to create.")
return | Produce help output related to operands.
Input:
Request Handle | entailment |
def capture_guest(userid):
"""Caputre a virtual machine image.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
Output parameters:
:image_name: Image name that captured
"""
# check power state, if down, start it
ret = sdk_client.send_request('guest_get_power_state', userid)
power_status = ret['output']
if power_status == 'off':
sdk_client.send_request('guest_start', userid)
# TODO: how much time?
time.sleep(1)
# do capture
image_name = 'image_captured_%03d' % (time.time() % 1000)
sdk_client.send_request('guest_capture', userid, image_name,
capture_type='rootonly', compress_level=6)
return image_name | Caputre a virtual machine image.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
Output parameters:
:image_name: Image name that captured | entailment |
def import_image(image_path, os_version):
"""Import image.
Input parameters:
:image_path: Image file path
:os_version: Operating system version. e.g. rhel7.2
"""
image_name = os.path.basename(image_path)
print("Checking if image %s exists or not, import it if not exists" %
image_name)
image_info = sdk_client.send_request('image_query', imagename=image_name)
if 'overallRC' in image_info and image_info['overallRC']:
print("Importing image %s ..." % image_name)
url = 'file://' + image_path
ret = sdk_client.send_request('image_import', image_name, url,
{'os_version': os_version})
else:
print("Image %s already exists" % image_name) | Import image.
Input parameters:
:image_path: Image file path
:os_version: Operating system version. e.g. rhel7.2 | entailment |
def _run_guest(userid, image_path, os_version, profile,
cpu, memory, network_info, disks_list):
"""Deploy and provision a virtual machine.
Input parameters:
:userid: USERID of the guest, no more than 8.
:image_name: path of the image file
:os_version: os version of the image file
:profile: profile of the userid
:cpu: the number of vcpus
:memory: memory
:network_info: dict of network info.members:
:ip_addr: ip address of vm
:gateway: gateway of net
:vswitch_name: switch name
:cidr: CIDR
:disks_list: list of disks to add.eg:
disks_list = [{'size': '3g',
'is_boot_disk': True,
'disk_pool': 'ECKD:xcateckd'}]
"""
# Import image if not exists
import_image(image_path, os_version)
# Start time
spawn_start = time.time()
# Create userid
print("Creating userid %s ..." % userid)
ret = sdk_client.send_request('guest_create', userid, cpu, memory,
disk_list=disks_list,
user_profile=profile)
if ret['overallRC']:
print 'guest_create error:%s' % ret
return -1
# Deploy image to root disk
image_name = os.path.basename(image_path)
print("Deploying %s to %s ..." % (image_name, userid))
ret = sdk_client.send_request('guest_deploy', userid, image_name)
if ret['overallRC']:
print 'guest_deploy error:%s' % ret
return -2
# Create network device and configure network interface
print("Configuring network interface for %s ..." % userid)
ret = sdk_client.send_request('guest_create_network_interface', userid,
os_version, [network_info])
if ret['overallRC']:
print 'guest_create_network error:%s' % ret
return -3
# Couple to vswitch
ret = sdk_client.send_request('guest_nic_couple_to_vswitch', userid,
'1000', network_info['vswitch_name'])
if ret['overallRC']:
print 'guest_nic_couple error:%s' % ret
return -4
# Grant user
ret = sdk_client.send_request('vswitch_grant_user',
network_info['vswitch_name'],
userid)
if ret['overallRC']:
print 'vswitch_grant_user error:%s' % ret
return -5
# Power on the vm
print("Starting guest %s" % userid)
ret = sdk_client.send_request('guest_start', userid)
if ret['overallRC']:
print 'guest_start error:%s' % ret
return -6
# End time
spawn_time = time.time() - spawn_start
print "Instance-%s pawned succeeded in %s seconds" % (userid, spawn_time) | Deploy and provision a virtual machine.
Input parameters:
:userid: USERID of the guest, no more than 8.
:image_name: path of the image file
:os_version: os version of the image file
:profile: profile of the userid
:cpu: the number of vcpus
:memory: memory
:network_info: dict of network info.members:
:ip_addr: ip address of vm
:gateway: gateway of net
:vswitch_name: switch name
:cidr: CIDR
:disks_list: list of disks to add.eg:
disks_list = [{'size': '3g',
'is_boot_disk': True,
'disk_pool': 'ECKD:xcateckd'}] | entailment |
def run_guest():
""" A sample for quick deploy and start a virtual guest."""
global GUEST_USERID
global GUEST_PROFILE
global GUEST_VCPUS
global GUEST_MEMORY
global GUEST_ROOT_DISK_SIZE
global DISK_POOL
global IMAGE_PATH
global IMAGE_OS_VERSION
global GUEST_IP_ADDR
global GATEWAY
global CIDR
global VSWITCH_NAME
network_info = {'ip_addr': GUEST_IP_ADDR,
'gateway_addr': GATEWAY,
'cidr': CIDR,
'vswitch_name': VSWITCH_NAME}
disks_list = [{'size': '%ig' % GUEST_ROOT_DISK_SIZE,
'is_boot_disk': True,
'disk_pool': DISK_POOL}]
_run_guest(GUEST_USERID, IMAGE_PATH, IMAGE_OS_VERSION, GUEST_PROFILE,
GUEST_VCPUS, GUEST_MEMORY, network_info, disks_list) | A sample for quick deploy and start a virtual guest. | entailment |
def _remove_unexpected_query_parameters(schema, req):
"""Remove unexpected properties from the req.GET."""
additional_properties = schema.get('addtionalProperties', True)
if additional_properties:
pattern_regexes = []
patterns = schema.get('patternProperties', None)
if patterns:
for regex in patterns:
pattern_regexes.append(re.compile(regex))
for param in set(req.GET.keys()):
if param not in schema['properties'].keys():
if not (list(regex for regex in pattern_regexes if
regex.match(param))):
del req.GET[param] | Remove unexpected properties from the req.GET. | entailment |
def query_schema(query_params_schema, min_version=None,
max_version=None):
"""Register a schema to validate request query parameters."""
def add_validator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if 'req' in kwargs:
req = kwargs['req']
else:
req = args[1]
if req.environ['wsgiorg.routing_args'][1]:
if _schema_validation_helper(query_params_schema,
req.environ['wsgiorg.routing_args'][1],
args, kwargs, is_body=False):
_remove_unexpected_query_parameters(query_params_schema,
req)
else:
if _schema_validation_helper(query_params_schema,
req.GET.dict_of_lists(),
args, kwargs, is_body=False):
_remove_unexpected_query_parameters(query_params_schema,
req)
return func(*args, **kwargs)
return wrapper
return add_validator | Register a schema to validate request query parameters. | entailment |
def _close_after_stream(self, response, chunk_size):
"""Iterate over the content and ensure the response is closed after."""
# Yield each chunk in the response body
for chunk in response.iter_content(chunk_size=chunk_size):
yield chunk
# Once we're done streaming the body, ensure everything is closed.
response.close() | Iterate over the content and ensure the response is closed after. | entailment |
def _save_file(self, data, path):
"""Save an file to the specified path.
:param data: binary data of the file
:param path: path to save the file to
"""
with open(path, 'wb') as tfile:
for chunk in data:
tfile.write(chunk) | Save an file to the specified path.
:param data: binary data of the file
:param path: path to save the file to | entailment |
def process_docstring(app, what, name, obj, options, lines):
"""Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following settings in conf.py control what styles of docstrings will
be parsed:
* ``napoleon_google_docstring`` -- parse Google style docstrings
* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process.
what : str
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
directive.
lines : list of str
The lines of the docstring, see above.
.. note:: `lines` is modified *in place*
Notes
-----
This function is (to most parts) taken from the :mod:`sphinx.ext.napoleon`
module, sphinx version 1.3.1, and adapted to the classes defined here"""
result_lines = lines
if app.config.napoleon_numpy_docstring:
docstring = ExtendedNumpyDocstring(
result_lines, app.config, app, what, name, obj, options)
result_lines = docstring.lines()
if app.config.napoleon_google_docstring:
docstring = ExtendedGoogleDocstring(
result_lines, app.config, app, what, name, obj, options)
result_lines = docstring.lines()
lines[:] = result_lines[:] | Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following settings in conf.py control what styles of docstrings will
be parsed:
* ``napoleon_google_docstring`` -- parse Google style docstrings
* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process.
what : str
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
directive.
lines : list of str
The lines of the docstring, see above.
.. note:: `lines` is modified *in place*
Notes
-----
This function is (to most parts) taken from the :mod:`sphinx.ext.napoleon`
module, sphinx version 1.3.1, and adapted to the classes defined here | entailment |
def setup(app):
"""Sphinx extension setup function
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
Notes
-----
This function uses the setup function of the :mod:`sphinx.ext.napoleon`
module"""
from sphinx.application import Sphinx
if not isinstance(app, Sphinx):
return # probably called by tests
app.connect('autodoc-process-docstring', process_docstring)
return napoleon_setup(app) | Sphinx extension setup function
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
Notes
-----
This function uses the setup function of the :mod:`sphinx.ext.napoleon`
module | entailment |
def format_time(x):
"""Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
x: object
The value to format. If not a time object, the value is returned
Returns
-------
str or `x`
Either the formatted time object or the initial `x`"""
if isinstance(x, (datetime64, datetime)):
return format_timestamp(x)
elif isinstance(x, (timedelta64, timedelta)):
return format_timedelta(x)
elif isinstance(x, ndarray):
return list(x) if x.ndim else x[()]
return x | Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
x: object
The value to format. If not a time object, the value is returned
Returns
-------
str or `x`
Either the formatted time object or the initial `x` | entailment |
def is_data_dependent(fmto, data):
"""Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a callable
Returns
-------
bool
True, if the formatoption depends on the data"""
if callable(fmto.data_dependent):
return fmto.data_dependent(data)
return fmto.data_dependent | Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a callable
Returns
-------
bool
True, if the formatoption depends on the data | entailment |
def set_value(self, value, validate=True, todefault=False):
"""
Set (and validate) the value in the plotter
Parameters
----------
%(Formatoption.set_value.parameters)s
Notes
-----
- If the current value in the plotter is None, then it will be set with
the given `value`, otherwise the current value in the plotter is
updated
- If the value is an empty dictionary, the value in the plotter is
cleared"""
value = value if not validate else self.validate(value)
# if the key in the plotter is not already set (i.e. it is initialized
# with None, we set it)
if self.plotter[self.key] is None:
with self.plotter.no_validation:
self.plotter[self.key] = value.copy()
# in case of an empty dict, clear the value
elif not value:
self.plotter[self.key].clear()
# otherwhise we update the dictionary
else:
if todefault:
self.plotter[self.key].clear()
self.plotter[self.key].update(value) | Set (and validate) the value in the plotter
Parameters
----------
%(Formatoption.set_value.parameters)s
Notes
-----
- If the current value in the plotter is None, then it will be set with
the given `value`, otherwise the current value in the plotter is
updated
- If the value is an empty dictionary, the value in the plotter is
cleared | entailment |
def ax(self):
"""Axes instance of the plot"""
if self._ax is None:
import matplotlib.pyplot as plt
plt.figure()
self._ax = plt.axes(projection=self._get_sample_projection())
return self._ax | Axes instance of the plot | entailment |
def base_variables(self):
"""A mapping from the base_variable names to the variables"""
if isinstance(self.data, InteractiveList):
return dict(chain(*map(
lambda arr: six.iteritems(arr.psy.base_variables),
self.data)))
else:
return self.data.psy.base_variables | A mapping from the base_variable names to the variables | entailment |
def iter_base_variables(self):
"""A mapping from the base_variable names to the variables"""
if isinstance(self.data, InteractiveList):
return chain(*(arr.psy.iter_base_variables for arr in self.data))
else:
return self.data.psy.iter_base_variables | A mapping from the base_variable names to the variables | entailment |
def changed(self):
""":class:`dict` containing the key value pairs that are not the
default"""
return {key: value for key, value in six.iteritems(self)
if getattr(self, key).changed} | :class:`dict` containing the key value pairs that are not the
default | entailment |
def _fmto_groups(self):
"""Mapping from group to a set of formatoptions"""
ret = defaultdict(set)
for key in self:
ret[getattr(self, key).group].add(getattr(self, key))
return dict(ret) | Mapping from group to a set of formatoptions | entailment |
def logger(self):
""":class:`logging.Logger` of this plotter"""
try:
return self.data.psy.logger.getChild(self.__class__.__name__)
except AttributeError:
name = '%s.%s' % (self.__module__, self.__class__.__name__)
return logging.getLogger(name) | :class:`logging.Logger` of this plotter | entailment |
def _try2set(self, fmto, *args, **kwargs):
"""Sets the value in `fmto` and gives additional informations when fail
Parameters
----------
fmto: Formatoption
``*args`` and ``**kwargs``
Anything that is passed to `fmto`s :meth:`~Formatoption.set_value`
method"""
try:
fmto.set_value(*args, **kwargs)
except Exception as e:
critical("Error while setting %s!" % fmto.key,
logger=getattr(self, 'logger', None))
raise e | Sets the value in `fmto` and gives additional informations when fail
Parameters
----------
fmto: Formatoption
``*args`` and ``**kwargs``
Anything that is passed to `fmto`s :meth:`~Formatoption.set_value`
method | entailment |
def check_key(self, key, raise_error=True, *args, **kwargs):
"""
Checks whether the key is a valid formatoption
Parameters
----------
%(check_key.parameters.no_possible_keys|name)s
Returns
-------
%(check_key.returns)s
Raises
------
%(check_key.raises)s"""
return check_key(
key, possible_keys=list(self), raise_error=raise_error,
name='formatoption keyword', *args, **kwargs) | Checks whether the key is a valid formatoption
Parameters
----------
%(check_key.parameters.no_possible_keys|name)s
Returns
-------
%(check_key.returns)s
Raises
------
%(check_key.raises)s | entailment |
def check_data(cls, name, dims, is_unstructured):
"""
A validation method for the data shape
The default method does nothing and should be subclassed to validate
the results. If the plotter accepts a :class:`InteractiveList`, it
should accept a list for name and dims
Parameters
----------
name: str or list of str
The variable name(s) of the data
dims: list of str or list of lists of str
The dimension name(s) of the data
is_unstructured: bool or list of bool
True if the corresponding array is unstructured
Returns
-------
list of bool or None
True, if everything is okay, False in case of a serious error,
None if it is intermediate. Each object in this list corresponds to
one in the given `name`
list of str
The message giving more information on the reason. Each object in
this list corresponds to one in the given `name`"""
if isinstance(name, six.string_types):
name = [name]
dims = [dims]
is_unstructured = [is_unstructured]
N = len(name)
if len(dims) != N or len(is_unstructured) != N:
return [False] * N, [
'Number of provided names (%i) and dimensions '
'(%i) or unstructured information (%i) are not the same' % (
N, len(dims), len(is_unstructured))] * N
return [True] * N, [''] * N | A validation method for the data shape
The default method does nothing and should be subclassed to validate
the results. If the plotter accepts a :class:`InteractiveList`, it
should accept a list for name and dims
Parameters
----------
name: str or list of str
The variable name(s) of the data
dims: list of str or list of lists of str
The dimension name(s) of the data
is_unstructured: bool or list of bool
True if the corresponding array is unstructured
Returns
-------
list of bool or None
True, if everything is okay, False in case of a serious error,
None if it is intermediate. Each object in this list corresponds to
one in the given `name`
list of str
The message giving more information on the reason. Each object in
this list corresponds to one in the given `name` | entailment |
def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False,
draw=False, remove=False, priority=None):
"""
Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that shall be visualized.
- If not None and `plot` is True, the given data is visualized.
- If None and the :attr:`data` attribute is not None, the data in
the :attr:`data` attribute is visualized
- If both are None, nothing is done.
%(Plotter.parameters.ax|make_plot|clear)s
%(InteractiveBase.start_update.parameters.draw)s
remove: bool
If True, old effects by the formatoptions in this plotter are
undone first
priority: int
If given, initialize only the formatoption with the given priority.
This value must be out of :data:`START`, :data:`BEFOREPLOTTING` or
:data:`END`
"""
if data is None and self.data is not None:
data = self.data
else:
self.data = data
self.ax = ax
if data is None: # nothing to do if no data is given
return
self.no_auto_update = not (
not self.no_auto_update or not data.psy.no_auto_update)
data.psy.plotter = self
if not make_plot: # stop here if we shall not plot
return
self.logger.debug("Initializing plot...")
if remove:
self.logger.debug(" Removing old formatoptions...")
for fmto in self._fmtos:
try:
fmto.remove()
except Exception:
self.logger.debug(
"Could not remove %s while initializing", fmto.key,
exc_info=True)
if clear:
self.logger.debug(" Clearing axes...")
self.ax.clear()
self.cleared = True
# get the formatoptions. We sort them here by key to make sure that the
# order always stays the same (easier for debugging)
fmto_groups = self._grouped_fmtos(self._sorted_by_priority(
sorted(self._fmtos, key=lambda fmto: fmto.key)))
self.plot_data = self.data
self._updating = True
for fmto_priority, grouper in fmto_groups:
if priority is None or fmto_priority == priority:
self._plot_by_priority(fmto_priority, grouper,
initializing=True)
self._release_all(True) # finish the update
self.cleared = False
self.replot = False
self._initialized = True
self._updating = False
if draw is None:
draw = rcParams['auto_draw']
if draw:
self.draw()
if rcParams['auto_show']:
self.show() | Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that shall be visualized.
- If not None and `plot` is True, the given data is visualized.
- If None and the :attr:`data` attribute is not None, the data in
the :attr:`data` attribute is visualized
- If both are None, nothing is done.
%(Plotter.parameters.ax|make_plot|clear)s
%(InteractiveBase.start_update.parameters.draw)s
remove: bool
If True, old effects by the formatoptions in this plotter are
undone first
priority: int
If given, initialize only the formatoption with the given priority.
This value must be out of :data:`START`, :data:`BEFOREPLOTTING` or
:data:`END` | entailment |
def _register_update(self, fmt={}, replot=False, force=False,
todefault=False):
"""
Register formatoptions for the update
Parameters
----------
fmt: dict
Keys can be any valid formatoptions with the corresponding values
(see the :attr:`formatoptions` attribute)
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not.
%(InteractiveBase._register_update.parameters.force|todefault)s"""
if self.disabled:
return
self.replot = self.replot or replot
self._todefault = self._todefault or todefault
if force is True:
force = list(fmt)
self._force.update(
[ret[0] for ret in map(self.check_key, force or [])])
# check the keys
list(map(self.check_key, fmt))
self._registered_updates.update(fmt) | Register formatoptions for the update
Parameters
----------
fmt: dict
Keys can be any valid formatoptions with the corresponding values
(see the :attr:`formatoptions` attribute)
replot: bool
Boolean that determines whether the data specific formatoptions
shall be updated in any case or not.
%(InteractiveBase._register_update.parameters.force|todefault)s | entailment |
def start_update(self, draw=None, queues=None, update_shared=True):
"""
Conduct the registered plot updates
This method starts the updates from what has been registered by the
:meth:`update` method. You can call this method if you did not set the
`auto_update` parameter to True when calling the :meth:`update` method
and when the :attr:`no_auto_update` attribute is True.
Parameters
----------
%(InteractiveBase.start_update.parameters)s
Returns
-------
%(InteractiveBase.start_update.returns)s
See Also
--------
:attr:`no_auto_update`, update"""
def update_the_others():
for fmto in fmtos:
for other_fmto in fmto.shared:
if not other_fmto.plotter._updating:
other_fmto.plotter._register_update(
force=[other_fmto.key])
for fmto in fmtos:
for other_fmto in fmto.shared:
if not other_fmto.plotter._updating:
other_draw = other_fmto.plotter.start_update(
draw=False, update_shared=False)
if other_draw:
self._figs2draw.add(
other_fmto.plotter.ax.get_figure())
if self.disabled:
return False
if queues is not None:
queues[0].get()
self.logger.debug("Starting update of %r",
self._registered_updates.keys())
# update the formatoptions
self._save_state()
try:
# get the formatoptions. We sort them here by key to make sure that
# the order always stays the same (easier for debugging)
fmtos = sorted(self._set_and_filter(), key=lambda fmto: fmto.key)
except Exception:
# restore last (working) state
last_state = self._old_fmt.pop(-1)
with self.no_validation:
for key in self:
self[key] = last_state.get(key, getattr(self, key).default)
if queues is not None:
queues[0].task_done()
self._release_all(queue=None if queues is None else queues[1])
# raise the error
raise
for fmto in fmtos:
for fmto2 in fmto.shared:
fmto2.plotter._to_update[fmto2] = self
if queues is not None:
self._updating = True
queues[0].task_done()
# wait for the other tasks to finish
queues[0].join()
queues[1].get()
fmtos.extend([fmto for fmto in self._insert_additionals(list(
self._to_update)) if fmto not in fmtos])
self._to_update.clear()
fmto_groups = self._grouped_fmtos(self._sorted_by_priority(fmtos[:]))
# if any formatoption requires a clearing of the axes is updated,
# we reinitialize the plot
if self.cleared:
self.reinit(draw=draw)
update_the_others()
self._release_all(queue=None if queues is None else queues[1])
return True
# otherwise we update it
arr_draw = False
try:
for priority, grouper in fmto_groups:
arr_draw = True
self._plot_by_priority(priority, grouper)
update_the_others()
except Exception:
raise
finally:
# make sure that all locks are released
self._release_all(finish=True,
queue=None if queues is None else queues[1])
if draw is None:
draw = rcParams['auto_draw']
if draw and arr_draw:
self.draw()
if rcParams['auto_show']:
self.show()
self.replot = False
return arr_draw | Conduct the registered plot updates
This method starts the updates from what has been registered by the
:meth:`update` method. You can call this method if you did not set the
`auto_update` parameter to True when calling the :meth:`update` method
and when the :attr:`no_auto_update` attribute is True.
Parameters
----------
%(InteractiveBase.start_update.parameters)s
Returns
-------
%(InteractiveBase.start_update.returns)s
See Also
--------
:attr:`no_auto_update`, update | entailment |
def reinit(self, draw=None, clear=False):
"""
Reinitializes the plot with the same data and on the same axes.
Parameters
----------
%(InteractiveBase.start_update.parameters.draw)s
clear: bool
Whether to clear the axes or not
Warnings
--------
The axes may be cleared when calling this method (even if `clear` is
set to False)!"""
# call the initialize_plot method. Note that clear can be set to
# False if any fmto has requires_clearing attribute set to True,
# because this then has been cleared before
self.initialize_plot(
self.data, self._ax, draw=draw, clear=clear or any(
fmto.requires_clearing for fmto in self._fmtos),
remove=True) | Reinitializes the plot with the same data and on the same axes.
Parameters
----------
%(InteractiveBase.start_update.parameters.draw)s
clear: bool
Whether to clear the axes or not
Warnings
--------
The axes may be cleared when calling this method (even if `clear` is
set to False)! | entailment |
def draw(self):
"""Draw the figures and those that are shared and have been changed"""
for fig in self.figs2draw:
fig.canvas.draw()
self._figs2draw.clear() | Draw the figures and those that are shared and have been changed | entailment |
def _set_and_filter(self):
"""Filters the registered updates and sort out what is not needed
This method filters out the formatoptions that have not changed, sets
the new value and returns an iterable that is sorted by the priority
(highest priority comes first) and dependencies
Returns
-------
list
list of :class:`Formatoption` objects that have to be updated"""
fmtos = []
seen = set()
for key in self._force:
self._registered_updates.setdefault(key, getattr(self, key).value)
for key, value in chain(
six.iteritems(self._registered_updates),
six.iteritems(
{key: getattr(self, key).default for key in self})
if self._todefault else ()):
if key in seen:
continue
seen.add(key)
fmto = getattr(self, key)
# if the key is shared, a warning will be printed as long as
# this plotter is not also updating (for example due to a whole
# project update)
if key in self._shared and key not in self._force:
if not self._shared[key].plotter._updating:
warn(("%s formatoption is shared with another plotter."
" Use the unshare method to enable the updating") % (
fmto.key),
logger=self.logger)
changed = False
else:
try:
changed = fmto.check_and_set(
value, todefault=self._todefault,
validate=not self.no_validation)
except Exception as e:
self._registered_updates.pop(key, None)
self.logger.debug('Failed to set %s', key)
raise e
changed = changed or key in self._force
if changed:
fmtos.append(fmto)
fmtos = self._insert_additionals(fmtos, seen)
for fmto in fmtos:
fmto.lock.acquire()
self._todefault = False
self._registered_updates.clear()
self._force.clear()
return fmtos | Filters the registered updates and sort out what is not needed
This method filters out the formatoptions that have not changed, sets
the new value and returns an iterable that is sorted by the priority
(highest priority comes first) and dependencies
Returns
-------
list
list of :class:`Formatoption` objects that have to be updated | entailment |
def _insert_additionals(self, fmtos, seen=None):
"""
Insert additional formatoptions into `fmtos`.
This method inserts those formatoptions into `fmtos` that are required
because one of the following criteria is fullfilled:
1. The :attr:`replot` attribute is True
2. Any formatoption with START priority is in `fmtos`
3. A dependency of one formatoption is in `fmtos`
Parameters
----------
fmtos: list
The list of formatoptions that shall be updated
seen: set
The formatoption keys that shall not be included. If None, all
formatoptions in `fmtos` are used
Returns
-------
fmtos
The initial `fmtos` plus further formatoptions
Notes
-----
`fmtos` and `seen` are modified in place (except that any formatoption
in the initial `fmtos` has :attr:`~Formatoption.requires_clearing`
attribute set to True)"""
def get_dependencies(fmto):
if fmto is None:
return []
return fmto.dependencies + list(chain(*map(
lambda key: get_dependencies(getattr(self, key, None)),
fmto.dependencies)))
seen = seen or {fmto.key for fmto in fmtos}
keys = {fmto.key for fmto in fmtos}
self.replot = self.replot or any(
fmto.requires_replot for fmto in fmtos)
if self.replot or any(fmto.priority >= START for fmto in fmtos):
self.replot = True
self.plot_data = self.data
new_fmtos = dict((f.key, f) for f in self._fmtos
if ((f not in fmtos and is_data_dependent(
f, self.data))))
seen.update(new_fmtos)
keys.update(new_fmtos)
fmtos += list(new_fmtos.values())
# insert the formatoptions that have to be updated if the plot is
# changed
if any(fmto.priority >= BEFOREPLOTTING for fmto in fmtos):
new_fmtos = dict((f.key, f) for f in self._fmtos
if ((f not in fmtos and f.update_after_plot)))
fmtos += list(new_fmtos.values())
for fmto in set(self._fmtos).difference(fmtos):
all_dependencies = get_dependencies(fmto)
if keys.intersection(all_dependencies):
fmtos.append(fmto)
if any(fmto.requires_clearing for fmto in fmtos):
self.cleared = True
return list(self._fmtos)
return fmtos | Insert additional formatoptions into `fmtos`.
This method inserts those formatoptions into `fmtos` that are required
because one of the following criteria is fullfilled:
1. The :attr:`replot` attribute is True
2. Any formatoption with START priority is in `fmtos`
3. A dependency of one formatoption is in `fmtos`
Parameters
----------
fmtos: list
The list of formatoptions that shall be updated
seen: set
The formatoption keys that shall not be included. If None, all
formatoptions in `fmtos` are used
Returns
-------
fmtos
The initial `fmtos` plus further formatoptions
Notes
-----
`fmtos` and `seen` are modified in place (except that any formatoption
in the initial `fmtos` has :attr:`~Formatoption.requires_clearing`
attribute set to True) | entailment |
def _sorted_by_priority(self, fmtos, changed=None):
"""Sort the formatoption objects by their priority and dependency
Parameters
----------
fmtos: list
list of :class:`Formatoption` instances
changed: list
the list of formatoption keys that have changed
Yields
------
Formatoption
The next formatoption as it comes by the sorting
Warnings
--------
The list `fmtos` is cleared by this method!"""
def pop_fmto(key):
idx = fmtos_keys.index(key)
del fmtos_keys[idx]
return fmtos.pop(idx)
def get_children(fmto, parents_keys):
all_fmtos = fmtos_keys + parents_keys
for key in fmto.children + fmto.dependencies:
if key not in fmtos_keys:
continue
child_fmto = pop_fmto(key)
for childs_child in get_children(
child_fmto, parents_keys + [child_fmto.key]):
yield childs_child
# filter out if parent is in update list
if (any(key in all_fmtos for key in child_fmto.parents) or
fmto.key in child_fmto.parents):
continue
yield child_fmto
fmtos.sort(key=lambda fmto: fmto.priority, reverse=True)
fmtos_keys = [fmto.key for fmto in fmtos]
self._last_update = changed or fmtos_keys[:]
self.logger.debug("Update the formatoptions %s", fmtos_keys)
while fmtos:
del fmtos_keys[0]
fmto = fmtos.pop(0)
# first update children
for child_fmto in get_children(fmto, [fmto.key]):
yield child_fmto
# filter out if parent is in update list
if any(key in fmtos_keys for key in fmto.parents):
continue
yield fmto | Sort the formatoption objects by their priority and dependency
Parameters
----------
fmtos: list
list of :class:`Formatoption` instances
changed: list
the list of formatoption keys that have changed
Yields
------
Formatoption
The next formatoption as it comes by the sorting
Warnings
--------
The list `fmtos` is cleared by this method! | entailment |
def _get_formatoptions(cls, include_bases=True):
"""
Iterator over formatoptions
This class method returns an iterator that contains all the
formatoptions descriptors that are in this class and that are defined
in the base classes
Notes
-----
There is absolutely no need to call this method besides the plotter
initialization, since all formatoptions are in the plotter itself.
Just type::
>>> list(plotter)
to get the formatoptions.
See Also
--------
_format_keys"""
def base_fmtos(base):
return filter(
lambda key: isinstance(getattr(cls, key), Formatoption),
getattr(base, '_get_formatoptions', empty)(False))
def empty(*args, **kwargs):
return list()
fmtos = (attr for attr, obj in six.iteritems(cls.__dict__)
if isinstance(obj, Formatoption))
if not include_bases:
return fmtos
return unique_everseen(chain(fmtos, *map(base_fmtos, cls.__mro__))) | Iterator over formatoptions
This class method returns an iterator that contains all the
formatoptions descriptors that are in this class and that are defined
in the base classes
Notes
-----
There is absolutely no need to call this method besides the plotter
initialization, since all formatoptions are in the plotter itself.
Just type::
>>> list(plotter)
to get the formatoptions.
See Also
--------
_format_keys | entailment |
def _enhance_keys(cls, keys=None, *args, **kwargs):
"""
Enhance the given keys by groups
Parameters
----------
keys: list of str or None
If None, the all formatoptions of the given class are used. Group
names from the :attr:`psyplot.plotter.groups` mapping are replaced
by the formatoptions
Other Parameters
----------------
%(check_key.parameters.kwargs)s
Returns
-------
list of str
The enhanced list of the formatoptions"""
all_keys = list(cls._get_formatoptions())
if isinstance(keys, six.string_types):
keys = [keys]
else:
keys = list(keys or sorted(all_keys))
fmto_groups = defaultdict(list)
for key in all_keys:
fmto_groups[getattr(cls, key).group].append(key)
new_i = 0
for i, key in enumerate(keys[:]):
if key in fmto_groups:
del keys[new_i]
for key2 in fmto_groups[key]:
if key2 not in keys:
keys.insert(new_i, key2)
new_i += 1
else:
valid, similar, message = check_key(
key, all_keys, False, 'formatoption keyword', *args,
**kwargs)
if not valid:
keys.remove(key)
new_i -= 1
warn(message)
new_i += 1
return keys | Enhance the given keys by groups
Parameters
----------
keys: list of str or None
If None, the all formatoptions of the given class are used. Group
names from the :attr:`psyplot.plotter.groups` mapping are replaced
by the formatoptions
Other Parameters
----------------
%(check_key.parameters.kwargs)s
Returns
-------
list of str
The enhanced list of the formatoptions | entailment |
def show_keys(cls, keys=None, indent=0, grouped=False, func=None,
include_links=False, *args, **kwargs):
"""
Classmethod to return a nice looking table with the given formatoptions
Parameters
----------
%(Plotter._enhance_keys.parameters)s
indent: int
The indentation of the table
grouped: bool, optional
If True, the formatoptions are grouped corresponding to the
:attr:`Formatoption.groupname` attribute
Other Parameters
----------------
func: function or None
The function the is used for returning (by default it is printed
via the :func:`print` function or (when using the gui) in the
help explorer). The given function must take a string as argument
include_links: bool or None, optional
Default False. If True, links (in restructured formats) are
included in the description. If None, the behaviour is determined
by the :attr:`psyplot.plotter.Plotter.include_links` attribute.
%(Plotter._enhance_keys.other_parameters)s
Returns
-------
results of `func`
None if `func` is the print function, otherwise anything else
See Also
--------
show_summaries, show_docs"""
def titled_group(groupname):
bars = str_indent + '*' * len(groupname) + '\n'
return bars + str_indent + groupname + '\n' + bars
keys = cls._enhance_keys(keys, *args, **kwargs)
str_indent = " " * indent
func = func or default_print_func
# call this function recursively when grouped is True
if grouped:
grouped_keys = DefaultOrderedDict(list)
for fmto in map(lambda key: getattr(cls, key), keys):
grouped_keys[fmto.groupname].append(fmto.key)
text = ""
for group, keys in six.iteritems(grouped_keys):
text += titled_group(group) + cls.show_keys(
keys, indent=indent, grouped=False, func=six.text_type,
include_links=include_links) + '\n\n'
return func(text.rstrip())
if not keys:
return
n = len(keys)
ncols = min([4, n]) # number of columns
# The number of cells in the table is one of the following cases:
# 1. The number of columns and equal to the number of keys
# 2. The number of keys
# 3. The number of keys plus the empty cells in the last column
ncells = n + ((ncols - (n % ncols)) if n != ncols else 0)
if include_links or (include_links is None and cls.include_links):
long_keys = list(map(lambda key: ':attr:`~%s.%s.%s`' % (
cls.__module__, cls.__name__, key), keys))
else:
long_keys = keys
maxn = max(map(len, long_keys)) # maximal lenght of the keys
# extend with empty cells
long_keys.extend([' ' * maxn] * (ncells - n))
bars = (str_indent + '+-' + ("-"*(maxn) + "-+-")*ncols)[:-1]
lines = ('| %s |\n%s' % (' | '.join(
key.ljust(maxn) for key in long_keys[i:i+ncols]), bars)
for i in range(0, n, ncols))
text = bars + "\n" + str_indent + ("\n" + str_indent).join(
lines)
if six.PY2:
text = text.encode('utf-8')
return func(text) | Classmethod to return a nice looking table with the given formatoptions
Parameters
----------
%(Plotter._enhance_keys.parameters)s
indent: int
The indentation of the table
grouped: bool, optional
If True, the formatoptions are grouped corresponding to the
:attr:`Formatoption.groupname` attribute
Other Parameters
----------------
func: function or None
The function the is used for returning (by default it is printed
via the :func:`print` function or (when using the gui) in the
help explorer). The given function must take a string as argument
include_links: bool or None, optional
Default False. If True, links (in restructured formats) are
included in the description. If None, the behaviour is determined
by the :attr:`psyplot.plotter.Plotter.include_links` attribute.
%(Plotter._enhance_keys.other_parameters)s
Returns
-------
results of `func`
None if `func` is the print function, otherwise anything else
See Also
--------
show_summaries, show_docs | entailment |
def _show_doc(cls, fmt_func, keys=None, indent=0, grouped=False,
func=None, include_links=False, *args, **kwargs):
"""
Classmethod to print the formatoptions and their documentation
This function is the basis for the :meth:`show_summaries` and
:meth:`show_docs` methods
Parameters
----------
fmt_func: function
A function that takes the key, the key as it is printed, and the
documentation of a formatoption as argument and returns what shall
be printed
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_summaries, show_docs"""
def titled_group(groupname):
bars = str_indent + '*' * len(groupname) + '\n'
return bars + str_indent + groupname + '\n' + bars
func = func or default_print_func
keys = cls._enhance_keys(keys, *args, **kwargs)
str_indent = " " * indent
if grouped:
grouped_keys = DefaultOrderedDict(list)
for fmto in map(lambda key: getattr(cls, key), keys):
grouped_keys[fmto.groupname].append(fmto.key)
text = "\n\n".join(
titled_group(group) + cls._show_doc(
fmt_func, keys, indent=indent, grouped=False,
func=str, include_links=include_links)
for group, keys in six.iteritems(grouped_keys))
return func(text.rstrip())
if include_links or (include_links is None and cls.include_links):
long_keys = list(map(lambda key: ':attr:`~%s.%s.%s`' % (
cls.__module__, cls.__name__, key), keys))
else:
long_keys = keys
text = '\n'.join(str_indent + long_key + '\n' + fmt_func(
key, long_key, getattr(cls, key).__doc__) for long_key, key in zip(
long_keys, keys))
return func(text) | Classmethod to print the formatoptions and their documentation
This function is the basis for the :meth:`show_summaries` and
:meth:`show_docs` methods
Parameters
----------
fmt_func: function
A function that takes the key, the key as it is printed, and the
documentation of a formatoption as argument and returns what shall
be printed
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_summaries, show_docs | entailment |
def show_summaries(cls, keys=None, indent=0, *args, **kwargs):
"""
Classmethod to print the summaries of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs"""
def find_summary(key, key_txt, doc):
return '\n'.join(wrapper.wrap(doc[:doc.find('\n\n')]))
str_indent = " " * indent
wrapper = TextWrapper(width=80, initial_indent=str_indent + ' ' * 4,
subsequent_indent=str_indent + ' ' * 4)
return cls._show_doc(find_summary, keys=keys, indent=indent,
*args, **kwargs) | Classmethod to print the summaries of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs | entailment |
def show_docs(cls, keys=None, indent=0, *args, **kwargs):
"""
Classmethod to print the full documentations of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs"""
def full_doc(key, key_txt, doc):
return ('=' * len(key_txt)) + '\n' + doc + '\n'
return cls._show_doc(full_doc, keys=keys, indent=indent,
*args, **kwargs) | Classmethod to print the full documentations of the formatoptions
Parameters
----------
%(Plotter.show_keys.parameters)s
Other Parameters
----------------
%(Plotter.show_keys.other_parameters)s
Returns
-------
%(Plotter.show_keys.returns)s
See Also
--------
show_keys, show_docs | entailment |
def _get_rc_strings(cls):
"""
Recursive method to get the base strings in the rcParams dictionary.
This method takes the :attr:`_rcparams_string` attribute from the given
`class` and combines it with the :attr:`_rcparams_string` attributes
from the base classes.
The returned frozenset can be used as base strings for the
:meth:`psyplot.config.rcsetup.RcParams.find_and_replace` method.
Returns
-------
list
The first entry is the :attr:`_rcparams_string` of this class,
the following the :attr:`_rcparams_string` attributes of the
base classes according to the method resolution order of this
class"""
return list(unique_everseen(chain(
*map(lambda base: getattr(base, '_rcparams_string', []),
cls.__mro__)))) | Recursive method to get the base strings in the rcParams dictionary.
This method takes the :attr:`_rcparams_string` attribute from the given
`class` and combines it with the :attr:`_rcparams_string` attributes
from the base classes.
The returned frozenset can be used as base strings for the
:meth:`psyplot.config.rcsetup.RcParams.find_and_replace` method.
Returns
-------
list
The first entry is the :attr:`_rcparams_string` of this class,
the following the :attr:`_rcparams_string` attributes of the
base classes according to the method resolution order of this
class | entailment |
def _set_rc(self):
"""Method to set the rcparams and defaultParams for this plotter"""
base_str = self._get_rc_strings()
# to make sure that the '.' is not interpreted as a regex pattern,
# we specify the pattern_base by ourselves
pattern_base = map(lambda s: s.replace('.', '\.'), base_str)
# pattern for valid keys being all formatoptions in this plotter
pattern = '(%s)(?=$)' % '|'.join(self._get_formatoptions())
self._rc = rcParams.find_and_replace(base_str, pattern=pattern,
pattern_base=pattern_base)
user_rc = SubDict(rcParams['plotter.user'], base_str, pattern=pattern,
pattern_base=pattern_base)
self._rc.update(user_rc.data)
self._defaultParams = SubDict(rcParams.defaultParams, base_str,
pattern=pattern,
pattern_base=pattern_base) | Method to set the rcparams and defaultParams for this plotter | entailment |
def update(self, fmt={}, replot=False, auto_update=False, draw=None,
force=False, todefault=False, **kwargs):
"""
Update the formatoptions and the plot
If the :attr:`data` attribute of this plotter is None, the plotter is
updated like a usual dictionary (see :meth:`dict.update`). Otherwise
the update is registered and the plot is updated if `auto_update` is
True or if the :meth:`start_update` method is called (see below).
Parameters
----------
%(Plotter._register_update.parameters)s
%(InteractiveBase.start_update.parameters)s
%(InteractiveBase.update.parameters.auto_update)s
``**kwargs``
Any other formatoption that shall be updated (additionally to those
in `fmt`)
Notes
-----
%(InteractiveBase.update.notes)s"""
if self.disabled:
return
fmt = dict(fmt)
if kwargs:
fmt.update(kwargs)
# if the data is None, update like a usual dictionary (but with
# validation)
if not self._initialized:
for key, val in six.iteritems(fmt):
self[key] = val
return
self._register_update(fmt=fmt, replot=replot, force=force,
todefault=todefault)
if not self.no_auto_update or auto_update:
self.start_update(draw=draw) | Update the formatoptions and the plot
If the :attr:`data` attribute of this plotter is None, the plotter is
updated like a usual dictionary (see :meth:`dict.update`). Otherwise
the update is registered and the plot is updated if `auto_update` is
True or if the :meth:`start_update` method is called (see below).
Parameters
----------
%(Plotter._register_update.parameters)s
%(InteractiveBase.start_update.parameters)s
%(InteractiveBase.update.parameters.auto_update)s
``**kwargs``
Any other formatoption that shall be updated (additionally to those
in `fmt`)
Notes
-----
%(InteractiveBase.update.notes)s | entailment |
def _set_sharing_keys(self, keys):
"""
Set the keys to share or unshare
Parameters
----------
keys: string or iterable of strings
The iterable may contain formatoptions that shall be shared (or
unshared), or group names of formatoptions to share all
formatoptions of that group (see the :attr:`fmt_groups` property).
If None, all formatoptions of this plotter are inserted.
Returns
-------
set
The set of formatoptions to share (or unshare)"""
if isinstance(keys, str):
keys = {keys}
keys = set(self) if keys is None else set(keys)
fmto_groups = self._fmto_groups
keys.update(chain(*(map(lambda fmto: fmto.key, fmto_groups[key])
for key in keys.intersection(fmto_groups))))
keys.difference_update(fmto_groups)
return keys | Set the keys to share or unshare
Parameters
----------
keys: string or iterable of strings
The iterable may contain formatoptions that shall be shared (or
unshared), or group names of formatoptions to share all
formatoptions of that group (see the :attr:`fmt_groups` property).
If None, all formatoptions of this plotter are inserted.
Returns
-------
set
The set of formatoptions to share (or unshare) | entailment |
def share(self, plotters, keys=None, draw=None, auto_update=False):
"""
Share the formatoptions of this plotter with others
This method shares the formatoptions of this :class:`Plotter` instance
with others to make sure that, if the formatoption of this changes,
those of the others change as well
Parameters
----------
plotters: list of :class:`Plotter` instances or a :class:`Plotter`
The plotters to share the formatoptions with
keys: string or iterable of strings
The formatoptions to share, or group names of formatoptions to
share all formatoptions of that group (see the
:attr:`fmt_groups` property). If None, all formatoptions of this
plotter are unshared.
%(InteractiveBase.start_update.parameters.draw)s
%(InteractiveBase.update.parameters.auto_update)s
See Also
--------
unshare, unshare_me"""
auto_update = auto_update or not self.no_auto_update
if isinstance(plotters, Plotter):
plotters = [plotters]
keys = self._set_sharing_keys(keys)
for plotter in plotters:
for key in keys:
fmto = self._shared.get(key, getattr(self, key))
if not getattr(plotter, key) == fmto:
plotter._shared[key] = getattr(self, key)
fmto.shared.add(getattr(plotter, key))
# now exit if we are not initialized
if self._initialized:
self.update(force=keys, auto_update=auto_update, draw=draw)
for plotter in plotters:
if not plotter._initialized:
continue
old_registered = plotter._registered_updates.copy()
plotter._registered_updates.clear()
try:
plotter.update(force=keys, auto_update=auto_update, draw=draw)
except:
raise
finally:
plotter._registered_updates.clear()
plotter._registered_updates.update(old_registered)
if draw is None:
draw = rcParams['auto_draw']
if draw:
self.draw()
if rcParams['auto_show']:
self.show() | Share the formatoptions of this plotter with others
This method shares the formatoptions of this :class:`Plotter` instance
with others to make sure that, if the formatoption of this changes,
those of the others change as well
Parameters
----------
plotters: list of :class:`Plotter` instances or a :class:`Plotter`
The plotters to share the formatoptions with
keys: string or iterable of strings
The formatoptions to share, or group names of formatoptions to
share all formatoptions of that group (see the
:attr:`fmt_groups` property). If None, all formatoptions of this
plotter are unshared.
%(InteractiveBase.start_update.parameters.draw)s
%(InteractiveBase.update.parameters.auto_update)s
See Also
--------
unshare, unshare_me | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.