INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Applies the applicable formatter to the value.
Args:
value: Dimension value to format
Returns:
Formatted dimension value | def pprint_value(self, value):
"""Applies the applicable formatter to the value.
Args:
value: Dimension value to format
Returns:
Formatted dimension value
"""
own_type = type(value) if self.type is None else self.type
formatter = (self.value_form... |
Pretty print the dimension value and unit.
Args:
value: Dimension value to format
Returns:
Formatted dimension value string with unit | def pprint_value_string(self, value):
"""Pretty print the dimension value and unit.
Args:
value: Dimension value to format
Returns:
Formatted dimension value string with unit
"""
unit = '' if self.unit is None else ' ' + bytes_to_unicode(self.unit)
... |
Handles tracking and cleanup of custom ids. | def id(self, opts_id):
"""Handles tracking and cleanup of custom ids."""
old_id = self._id
self._id = opts_id
if old_id is not None:
cleanup_custom_options(old_id)
if opts_id is not None and opts_id != old_id:
if opts_id not in Store._weakrefs:
... |
Clones the object, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
link (bool, optional): Whether clone should be linked
... | def clone(self, data=None, shared_data=True, new_type=None, link=True,
*args, **overrides):
"""Clones the object, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
... |
Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to returned object
depth (int, optional): Depth to wh... | def relabel(self, label=None, group=None, depth=0):
"""Clone object and apply new group and/or label.
Applies relabeling to children up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to... |
Whether the spec applies to this object.
Args:
spec: A function, spec or type to check for a match
* A 'type[[.group].label]' string which is compared
against the type, group and label of this object
* A function which is given the object and return... | def matches(self, spec):
"""Whether the spec applies to this object.
Args:
spec: A function, spec or type to check for a match
* A 'type[[.group].label]' string which is compared
against the type, group and label of this object
* A function ... |
Traverses object returning matching items
Traverses the set of children of the object, collecting the
all objects matching the defined specs. Each object can be
processed with the supplied function.
Args:
fn (function, optional): Function applied to matched objects
... | def traverse(self, fn=None, specs=None, full_breadth=True):
"""Traverses object returning matching items
Traverses the set of children of the object, collecting the
all objects matching the defined specs. Each object can be
processed with the supplied function.
Args:
... |
Map a function to all objects matching the specs
Recursively replaces elements using a map function when the
specs apply, by default applies to all objects, e.g. to apply
the function to all contained Curve objects:
dmap.map(fn, hv.Curve)
Args:
map_fn: Function... | def map(self, map_fn, specs=None, clone=True):
"""Map a function to all objects matching the specs
Recursively replaces elements using a map function when the
specs apply, by default applies to all objects, e.g. to apply
the function to all contained Curve objects:
dmap.map... |
Validates key dimension input
Returns kdims if no dimensions are specified | def _valid_dimensions(self, dimensions):
"""Validates key dimension input
Returns kdims if no dimensions are specified"""
if dimensions is None:
dimensions = self.kdims
elif not isinstance(dimensions, list):
dimensions = [dimensions]
valid_dimensions = [... |
Lists the available dimensions on the object
Provides convenient access to Dimensions on nested Dimensioned
objects. Dimensions can be selected by their type, i.e. 'key'
or 'value' dimensions. By default 'all' dimensions are
returned.
Args:
selection: Type of dimens... | def dimensions(self, selection='all', label=False):
"""Lists the available dimensions on the object
Provides convenient access to Dimensions on nested Dimensioned
objects. Dimensions can be selected by their type, i.e. 'key'
or 'value' dimensions. By default 'all' dimensions are
... |
Get the index of the requested dimension.
Args:
dimension: Dimension to look up by name or by index
Returns:
Integer index of the requested dimension | def get_dimension_index(self, dimension):
"""Get the index of the requested dimension.
Args:
dimension: Dimension to look up by name or by index
Returns:
Integer index of the requested dimension
"""
if isinstance(dimension, int):
if (dimensio... |
Get a Dimension object by name or index.
Args:
dimension: Dimension to look up by name or integer index
default (optional): Value returned if Dimension not found
strict (bool, optional): Raise a KeyError if not found
Returns:
Dimension object for the req... | def get_dimension(self, dimension, default=None, strict=False):
"""Get a Dimension object by name or index.
Args:
dimension: Dimension to look up by name or integer index
default (optional): Value returned if Dimension not found
strict (bool, optional): Raise a KeyEr... |
Get the type of the requested dimension.
Type is determined by Dimension.type attribute or common
type of the dimension values, otherwise None.
Args:
dimension: Dimension to look up by name or by index
Returns:
Declared type of values along the dimension | def get_dimension_type(self, dim):
"""Get the type of the requested dimension.
Type is determined by Dimension.type attribute or common
type of the dimension values, otherwise None.
Args:
dimension: Dimension to look up by name or by index
Returns:
Decl... |
Applies selection by dimension name
Applies a selection along the dimensions of the object using
keyword arguments. The selection may be narrowed to certain
objects using selection_specs. For container objects the
selection will be applied to all children as well.
Selections ma... | def select(self, selection_specs=None, **kwargs):
"""Applies selection by dimension name
Applies a selection along the dimensions of the object using
keyword arguments. The selection may be narrowed to certain
objects using selection_specs. For container objects the
selection wi... |
Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior depends
on the type of data:
* Colum... | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, beh... |
Return the lower and upper bounds of values along dimension.
Args:
dimension: The dimension to compute the range on.
data_range (bool): Compute range from data values
dimension_range (bool): Include Dimension ranges
Whether to include Dimension range and soft... | def range(self, dimension, data_range=True, dimension_range=True):
"""Return the lower and upper bounds of values along dimension.
Args:
dimension: The dimension to compute the range on.
data_range (bool): Compute range from data values
dimension_range (bool): Includ... |
Applies simplified option definition returning a new object.
Applies options on an object or nested group of objects in a
flat format returning a new object with the options
applied. If the options are to be set directly on the object a
simple format may be used, e.g.:
obj.... | def options(self, *args, **kwargs):
"""Applies simplified option definition returning a new object.
Applies options on an object or nested group of objects in a
flat format returning a new object with the options
applied. If the options are to be set directly on the object a
sim... |
Deprecated method to construct tree from list of objects | def from_values(cls, vals):
"Deprecated method to construct tree from list of objects"
if util.config.future_deprecations:
param.main.param.warning("%s.from_values is deprecated, the %s "
"constructor may now be used directly.")
return cls(items=c... |
Processes list of items assigning unique paths to each. | def _process_items(cls, vals):
"Processes list of items assigning unique paths to each."
if type(vals) is cls:
return vals.data
elif not isinstance(vals, (list, tuple)):
vals = [vals]
items = []
counts = defaultdict(lambda: 1)
cls._unpack_paths(val... |
Deduplicates assigned paths by incrementing numbering | def _deduplicate_items(cls, items):
"Deduplicates assigned paths by incrementing numbering"
counter = Counter([path[:i] for path, _ in items for i in range(1, len(path)+1)])
if sum(counter.values()) == len(counter):
return items
new_items = []
counts = defaultdict(la... |
Recursively unpacks lists and ViewableTree-like objects, accumulating
into the supplied list of items. | def _unpack_paths(cls, objs, items, counts):
"""
Recursively unpacks lists and ViewableTree-like objects, accumulating
into the supplied list of items.
"""
if type(objs) is cls:
objs = objs.items()
for item in objs:
path, obj = item if isinstance(i... |
Return the values along the requested dimension.
Concatenates values on all nodes with requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior de... | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Concatenates values on all nodes with requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expa... |
Deprecated method to apply new group to items.
Equivalent functionality possible using:
ViewableTree(tree.relabel(group='Group').values()) | def regroup(self, group):
"""Deprecated method to apply new group to items.
Equivalent functionality possible using:
ViewableTree(tree.relabel(group='Group').values())
"""
if util.config.future_deprecations:
self.param.warning('%s.regroup is deprecated, use rela... |
Applies all the axis settings before the axis or figure is returned.
Only plots with zorder 0 get to apply their settings.
When the number of the frame is supplied as n, this method looks
up and computes the appropriate title, axis labels and axis bounds. | def _finalize_axis(self, key, element=None, title=None, dimensions=None, ranges=None, xticks=None,
yticks=None, zticks=None, xlabel=None, ylabel=None, zlabel=None):
"""
Applies all the axis settings before the axis or figure is returned.
Only plots with zorder 0 get to app... |
Finalizes the ticks on the axes based on the supplied ticks
and Elements. Sets the axes position as well as tick positions,
labels and fontsize. | def _finalize_ticks(self, axis, dimensions, xticks, yticks, zticks):
"""
Finalizes the ticks on the axes based on the supplied ticks
and Elements. Sets the axes position as well as tick positions,
labels and fontsize.
"""
ndims = len(dimensions) if dimensions else 0
... |
Sets the labels of the axes using the supplied list of dimensions.
Optionally explicit labels may be supplied to override the dimension
label. | def _set_labels(self, axes, dimensions, xlabel=None, ylabel=None, zlabel=None):
"""
Sets the labels of the axes using the supplied list of dimensions.
Optionally explicit labels may be supplied to override the dimension
label.
"""
xlabel, ylabel, zlabel = self._get_axis_l... |
Set axis formatter based on dimension formatter. | def _set_axis_formatter(self, axis, dim, formatter):
"""
Set axis formatter based on dimension formatter.
"""
if isinstance(dim, list): dim = dim[0]
if formatter is not None:
pass
elif dim.value_format:
formatter = dim.value_format
elif dim... |
Computes the aspect ratio of the plot | def get_aspect(self, xspan, yspan):
"""
Computes the aspect ratio of the plot
"""
if isinstance(self.aspect, (int, float)):
return self.aspect
elif self.aspect == 'square':
return 1
elif self.aspect == 'equal':
return xspan/yspan
... |
Set the aspect on the axes based on the aspect setting. | def _set_aspect(self, axes, aspect):
"""
Set the aspect on the axes based on the aspect setting.
"""
if ((isinstance(aspect, util.basestring) and aspect != 'square') or
self.data_aspect):
data_ratio = self.data_aspect or aspect
else:
(x0, x1), ... |
Compute extents for current view and apply as axis limits | def _set_axis_limits(self, axis, view, subplots, ranges):
"""
Compute extents for current view and apply as axis limits
"""
# Extents
extents = self.get_extents(view, ranges)
if not extents or self.overlaid:
axis.autoscale_view(scalex=True, scaley=True)
... |
Set the position and visibility of the xaxis or yaxis by
supplying the axes object, the axis to set, i.e. 'x' or 'y'
and an option to specify the position and visibility of the axis.
The option may be None, 'bare' or positional, i.e. 'left' and
'right' for the yaxis and 'top' and 'bottom... | def _set_axis_position(self, axes, axis, option):
"""
Set the position and visibility of the xaxis or yaxis by
supplying the axes object, the axis to set, i.e. 'x' or 'y'
and an option to specify the position and visibility of the axis.
The option may be None, 'bare' or positiona... |
Allows setting the ticks for a particular axis either with
a tuple of ticks, a tick locator object, an integer number
of ticks, a list of tuples containing positions and labels
or a list of positions. Also supports enabling log ticking
if an integer number of ticks is supplied and settin... | def _set_axis_ticks(self, axis, ticks, log=False, rotation=0):
"""
Allows setting the ticks for a particular axis either with
a tuple of ticks, a tick locator object, an integer number
of ticks, a list of tuples containing positions and labels
or a list of positions. Also support... |
Set the plot(s) to the given frame number. Operates by
manipulating the matplotlib objects held in the self._handles
dictionary.
If n is greater than the number of available frames, update
using the last available frame. | def update_frame(self, key, ranges=None, element=None):
"""
Set the plot(s) to the given frame number. Operates by
manipulating the matplotlib objects held in the self._handles
dictionary.
If n is greater than the number of available frames, update
using the last availa... |
Initializes the artist based on the plot method declared on
the plot. | def init_artists(self, ax, plot_args, plot_kwargs):
"""
Initializes the artist based on the plot method declared on
the plot.
"""
plot_method = self._plot_methods.get('batched' if self.batched else 'single')
plot_fn = getattr(ax, plot_method)
artist = plot_fn(*plo... |
Update the elements of the plot. | def update_handles(self, key, axis, element, ranges, style):
"""
Update the elements of the plot.
"""
self.teardown_handles()
plot_data, plot_kwargs, axis_kwargs = self.get_data(element, ranges, style)
with abbreviated_exception():
handles = self.init_artists... |
Returns valid color normalization kwargs
to be passed to matplotlib plot function. | def _norm_kwargs(self, element, ranges, opts, vdim, values=None, prefix=''):
"""
Returns valid color normalization kwargs
to be passed to matplotlib plot function.
"""
dim_name = dim_range_key(vdim)
if values is None:
if isinstance(vdim, dim):
... |
Accumulate the legend handles and labels for all subplots
and set up the legend | def _adjust_legend(self, overlay, axis):
"""
Accumulate the legend handles and labels for all subplots
and set up the legend
"""
legend_data = []
dimensions = overlay.kdims
title = ', '.join([d.name for d in dimensions])
for key, subplot in self.subplots.i... |
Helper method that returns a list of elements that match the
given path pattern of form {type}.{group}.{label}.
The input may be a Layout, an Overlay type or a single
Element. | def search(cls, element, pattern):
"""
Helper method that returns a list of elements that match the
given path pattern of form {type}.{group}.{label}.
The input may be a Layout, an Overlay type or a single
Element.
"""
if isinstance(element, Layout):
... |
Returns a label if all the elements of an overlay agree on a
consistent label, otherwise returns the default label. | def get_overlay_label(cls, overlay, default_label=''):
"""
Returns a label if all the elements of an overlay agree on a
consistent label, otherwise returns the default label.
"""
if all(el.label==overlay.get(0).label for el in overlay):
return overlay.get(0).label
... |
Returns the extents if all the elements of an overlay agree on
a consistent extents, otherwise raises an exception. | def get_overlay_bounds(cls, overlay):
"""
Returns the extents if all the elements of an overlay agree on
a consistent extents, otherwise raises an exception.
"""
if all(el.bounds==overlay.get(0).bounds for el in overlay):
return overlay.get(0).bounds
else:
... |
Applies the operation to the element, executing any pre- and
post-processor hooks if defined. | def _apply(self, element, key=None):
"""
Applies the operation to the element, executing any pre- and
post-processor hooks if defined.
"""
kwargs = {}
for hook in self._preprocess_hooks:
kwargs.update(hook(self, element))
ret = self._process(element, k... |
The process_element method allows a single element to be
operated on given an externally supplied key. | def process_element(self, element, key, **params):
"""
The process_element method allows a single element to be
operated on given an externally supplied key.
"""
self.p = param.ParamOverrides(self, params)
return self._apply(element, key) |
Finds all common dimension keys in the object including subsets of
dimensions. If there are is no common subset of dimensions, None
is returned. | def uniform(obj):
"""
Finds all common dimension keys in the object including subsets of
dimensions. If there are is no common subset of dimensions, None
is returned.
"""
from .spaces import HoloMap
dim_groups = obj.traverse(lambda x: tuple(x.kdims),
(HoloMap,))... |
Finds all common dimension keys in the object including subsets of
dimensions. If there are is no common subset of dimensions, None
is returned.
Returns the list of dimensions followed by the list of unique
keys. | def unique_dimkeys(obj, default_dim='Frame'):
"""
Finds all common dimension keys in the object including subsets of
dimensions. If there are is no common subset of dimensions, None
is returned.
Returns the list of dimensions followed by the list of unique
keys.
"""
from .ndmapping impo... |
Iterates over dimension values in keys, taking two sets
of dimension values at a time to determine whether two
consecutive dimensions have a one-to-many relationship.
If they do a mapping between the first and second dimension
values is returned. Returns a list of n-1 mappings, between
consecutive d... | def hierarchical(keys):
"""
Iterates over dimension values in keys, taking two sets
of dimension values at a time to determine whether two
consecutive dimensions have a one-to-many relationship.
If they do a mapping between the first and second dimension
values is returned. Returns a list of n-1... |
Returns the coordinates along a dimension. Ordered ensures
coordinates are in ascending order and expanded creates
ND-array matching the dimensionality of the dataset. | def coords(cls, dataset, dim, ordered=False, expanded=False, edges=False):
"""
Returns the coordinates along a dimension. Ordered ensures
coordinates are in ascending order and expanded creates
ND-array matching the dimensionality of the dataset.
"""
dim = dataset.get_di... |
>>> GridInterface._infer_interval_breaks(np.arange(5))
array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5])
>>> GridInterface._infer_interval_breaks([[0, 1], [3, 4]], axis=1)
array([[-0.5, 0.5, 1.5],
[ 2.5, 3.5, 4.5]]) | def _infer_interval_breaks(cls, coord, axis=0):
"""
>>> GridInterface._infer_interval_breaks(np.arange(5))
array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5])
>>> GridInterface._infer_interval_breaks([[0, 1], [3, 4]], axis=1)
array([[-0.5, 0.5, 1.5],
[ 2.5, 3.5, 4.5]])... |
Samples the gridded data into dataset of samples. | def sample(cls, dataset, samples=[]):
"""
Samples the gridded data into dataset of samples.
"""
ndims = dataset.ndims
dimensions = dataset.dimensions(label='name')
arrays = [dataset.data[vdim.name] for vdim in dataset.vdims]
data = defaultdict(list)
for s... |
Canonicalize takes an array of values as input and reorients
and transposes it to match the canonical format expected by
plotting functions. In certain cases the dimensions defined
via the kdims of an Element may not match the dimensions of
the underlying data. A set of data_coords may b... | def canonicalize(cls, dataset, data, data_coords=None, virtual_coords=[]):
"""
Canonicalize takes an array of values as input and reorients
and transposes it to match the canonical format expected by
plotting functions. In certain cases the dimensions defined
via the kdims of an ... |
Update datasource with data for a new frame. | def _update_datasource(self, source, data):
"""
Update datasource with data for a new frame.
"""
if isinstance(source, ColumnDataSource):
if self.handles['static_source']:
source.trigger('data', source.data, data)
else:
source.data.... |
Replace edge renderer with filled renderer | def _init_filled_edges(self, renderer, properties, edge_mapping):
"Replace edge renderer with filled renderer"
glyph_model = Patches if self.filled else Bezier
allowed_properties = glyph_model.properties()
for glyph_type in ('', 'selection_', 'nonselection_', 'hover_', 'muted_'):
... |
Computes the args and kwargs for the GraphRenderer | def _get_graph_properties(self, plot, element, data, mapping, ranges, style):
"Computes the args and kwargs for the GraphRenderer"
sources = []
properties, mappings = {}, {}
for key in ('scatter_1', self.edge_glyph):
gdata = data.pop(key, {})
group_style = dict(s... |
Reorders renderers based on the defined draw order | def _reorder_renderers(self, plot, renderer, mapping):
"Reorders renderers based on the defined draw order"
renderers = dict({r: self.handles[r+'_glyph_renderer']
for r in mapping}, graph=renderer)
other = [r for r in plot.renderers if r not in renderers.values()]
... |
A Chord plot is always drawn on a unit circle. | def get_extents(self, element, ranges, range_type='combined'):
"""
A Chord plot is always drawn on a unit circle.
"""
xdim, ydim = element.nodes.kdims[:2]
if range_type not in ('combined', 'data', 'extents'):
return xdim.range[0], ydim.range[0], xdim.range[1], ydim.ra... |
String sanitizer to avoid problematic characters in filenames. | def sanitizer(name, replacements=[(':','_'), ('/','_'), ('\\','_')]):
"""
String sanitizer to avoid problematic characters in filenames.
"""
for old,new in replacements:
name = name.replace(old,new)
return name |
Simple name_generator designed for HoloViews objects.
Objects are labeled with {group}-{label} for each nested
object, based on a depth-first search. Adjacent objects with
identical representations yield only a single copy of the
representation, to avoid long names for the common case of
a contain... | def simple_name_generator(obj):
"""
Simple name_generator designed for HoloViews objects.
Objects are labeled with {group}-{label} for each nested
object, based on a depth-first search. Adjacent objects with
identical representations yield only a single copy of the
representation, to avoid lon... |
Classmethod that applies conditional encoding based on
mime-type. Given an entry as returned by __call__ return the
data in the appropriate encoding. | def encode(cls, entry):
"""
Classmethod that applies conditional encoding based on
mime-type. Given an entry as returned by __call__ return the
data in the appropriate encoding.
"""
(data, info) = entry
if info['mime_type'] in cls.utf8_mime_types:
retu... |
Add the file extension if not already present | def _filename(self_or_cls, filename):
"Add the file extension if not already present"
if not filename.endswith(self_or_cls.file_ext):
return '%s.%s' % (filename, self_or_cls.file_ext)
else:
return filename |
Returns a merged metadata info dictionary from the supplied
function and additional dictionaries | def _merge_metadata(self_or_cls, obj, fn, *dicts):
"""
Returns a merged metadata info dictionary from the supplied
function and additional dictionaries
"""
merged = dict([(k,v) for d in dicts for (k,v) in d.items()])
return dict(merged, **fn(obj)) if fn else merged |
Given a list or NdMapping type containing file paths return a
Layout of Collators, which can be called to load a given set
of files using the current Importer.
If supplied as a list each file is expected to disambiguate
itself with contained metadata. If an NdMapping type is
sup... | def collect(self_or_cls, files, drop=[], metadata=True):
"""
Given a list or NdMapping type containing file paths return a
Layout of Collators, which can be called to load a given set
of files using the current Importer.
If supplied as a list each file is expected to disambiguat... |
Returns the format fields otherwise raise exception | def parse_fields(cls, formatter):
"Returns the format fields otherwise raise exception"
if formatter is None: return []
try:
parse = list(string.Formatter().parse(formatter))
return set(f for f in list(zip(*parse))[1] if f is not None)
except:
raise S... |
If a filename is supplied, it will be used. Otherwise, a
filename will be generated from the supplied object. Note that
if the explicit filename uses the {timestamp} field, it will
be formatted upon export.
The data to be archived is either supplied explicitly as
'data' or autom... | def add(self, obj=None, filename=None, data=None, info={}, **kwargs):
"""
If a filename is supplied, it will be used. Otherwise, a
filename will be generated from the supplied object. Note that
if the explicit filename uses the {timestamp} field, it will
be formatted upon export.... |
Find a unique basename for a new file/key where existing is
either a list of (basename, ext) pairs or an absolute path to
a directory.
By default, uniqueness is enforced depending on the state of
the unique_name parameter (for export names). If force is
True, this parameter is i... | def _unique_name(self, basename, ext, existing, force=False):
"""
Find a unique basename for a new file/key where existing is
either a list of (basename, ext) pairs or an absolute path to
a directory.
By default, uniqueness is enforced depending on the state of
the uniqu... |
Export the archive, directory or file. | def export(self, timestamp=None, info={}):
"""
Export the archive, directory or file.
"""
tval = tuple(time.localtime()) if timestamp is None else timestamp
tstamp = time.strftime(self.timestamp_format, tval)
info = dict(info, timestamp=tstamp)
export_name = self... |
Print the current (unexported) contents of the archive | def contents(self, maxlen=70):
"Print the current (unexported) contents of the archive"
lines = []
if len(self._files) == 0:
print("Empty %s" % self.__class__.__name__)
return
fnames = [self._truncate_name(maxlen=maxlen, *k) for k in self._files]
max_len ... |
Return a list of filename entries currently in the archive | def listing(self):
"Return a list of filename entries currently in the archive"
return ['.'.join([f,ext]) if ext else f for (f,ext) in self._files.keys()] |
A helper utility to display a progress bar when iterating over a
collection of a fixed length or a generator (with a declared
length).
If enum=True, then equivalent to enumerate with a progress bar. | def progress(iterator, enum=False, length=None):
"""
A helper utility to display a progress bar when iterating over a
collection of a fixed length or a generator (with a declared
length).
If enum=True, then equivalent to enumerate with a progress bar.
"""
progress = ProgressBar()
length... |
Returns the figure in html format on the
first call and | def _plot_figure(self, idx, fig_format='json'):
"""
Returns the figure in html format on the
first call and
"""
self.plot.update(idx)
if self.embed:
return self.renderer.diff(self.plot) |
Calculate the true density along x, and adjust the top and
bottom bounds so that the density along y will be equal.
Returns (adjusted_bounds, true_density) | def __equalize_densities(self,nominal_bounds,nominal_density):
"""
Calculate the true density along x, and adjust the top and
bottom bounds so that the density along y will be equal.
Returns (adjusted_bounds, true_density)
"""
left,bottom,right,top = nominal_bounds.lbrt(... |
Convert a point (x,y) in Sheet coordinates to continuous
matrix coordinates.
Returns (float_row,float_col), where float_row corresponds to
y, and float_col to x.
Valid for scalar or array x and y.
Note about Bounds For a Sheet with
BoundingBox(points=((-0.5,-0.5),(0.5,... | def sheet2matrix(self,x,y):
"""
Convert a point (x,y) in Sheet coordinates to continuous
matrix coordinates.
Returns (float_row,float_col), where float_row corresponds to
y, and float_col to x.
Valid for scalar or array x and y.
Note about Bounds For a Sheet wi... |
Convert a point (x,y) in sheet coordinates to the integer row
and column index of the matrix cell in which that point falls,
given a bounds and density. Returns (row,column).
Note that if coordinates along the right or bottom boundary
are passed into this function, the returned matrix ... | def sheet2matrixidx(self,x,y):
"""
Convert a point (x,y) in sheet coordinates to the integer row
and column index of the matrix cell in which that point falls,
given a bounds and density. Returns (row,column).
Note that if coordinates along the right or bottom boundary
... |
Convert a floating-point location (float_row,float_col) in
matrix coordinates to its corresponding location (x,y) in
sheet coordinates.
Valid for scalar or array float_row and float_col.
Inverse of sheet2matrix(). | def matrix2sheet(self,float_row,float_col):
"""
Convert a floating-point location (float_row,float_col) in
matrix coordinates to its corresponding location (x,y) in
sheet coordinates.
Valid for scalar or array float_row and float_col.
Inverse of sheet2matrix().
... |
Return (x,y) where x and y are the floating point coordinates
of the *center* of the given matrix cell (row,col). If the
matrix cell represents a 0.2 by 0.2 region, then the center
location returned would be 0.1,0.1.
NOTE: This is NOT the strict mathematical inverse of
sheet2mat... | def matrixidx2sheet(self,row,col):
"""
Return (x,y) where x and y are the floating point coordinates
of the *center* of the given matrix cell (row,col). If the
matrix cell represents a 0.2 by 0.2 region, then the center
location returned would be 0.1,0.1.
NOTE: This is N... |
Given arbitrary sheet coordinates, return the sheet coordinates
of the center of the closest unit. | def closest_cell_center(self,x,y):
"""
Given arbitrary sheet coordinates, return the sheet coordinates
of the center of the closest unit.
"""
return self.matrixidx2sheet(*self.sheet2matrixidx(x,y)) |
Return x,y where x is a vector of sheet coordinates
representing the x-center of each matrix cell, and y
represents the corresponding y-center of the cell. | def sheetcoordinates_of_matrixidx(self):
"""
Return x,y where x is a vector of sheet coordinates
representing the x-center of each matrix cell, and y
represents the corresponding y-center of the cell.
"""
rows,cols = self.shape
return self.matrixidx2sheet(np.arang... |
Gets the matrix indices of a slice within an array of size
sheetshape from a sliceshape, positioned at coord. | def findinputslice(coord, sliceshape, sheetshape):
"""
Gets the matrix indices of a slice within an array of size
sheetshape from a sliceshape, positioned at coord.
"""
center_row, center_col = coord
n_rows, n_cols = sliceshape
sheet_rows, sheet_cols = sheetshape
... |
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge of the sheet). | def positionlesscrop(self,x,y,sheet_coord_system):
"""
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge of the sheet).
"""
... |
Offset the bounds_template to this cf's location and store the
result in the 'bounds' attribute.
Also stores the input_sheet_slice for access by C. | def positionedcrop(self,x,y,sheet_coord_system):
"""
Offset the bounds_template to this cf's location and store the
result in the 'bounds' attribute.
Also stores the input_sheet_slice for access by C.
"""
cf_row,cf_col = sheet_coord_system.sheet2matrixidx(x,y)
bo... |
Crop the slice to the SheetCoordinateSystem's bounds. | def crop_to_sheet(self,sheet_coord_system):
"Crop the slice to the SheetCoordinateSystem's bounds."
maxrow,maxcol = sheet_coord_system.shape
self[0] = max(0,self[0])
self[1] = min(maxrow,self[1])
self[2] = max(0,self[2])
self[3] = min(maxcol,self[3]) |
Create the 'odd' Slice that best approximates the specified
sheet-coordinate bounds.
The supplied bounds are translated to have a center at the
center of one of the sheet's units (we arbitrarily use the
center unit), and then these bounds are converted to a slice
in such a way t... | def _createoddslicespec(bounds,scs,min_matrix_radius):
"""
Create the 'odd' Slice that best approximates the specified
sheet-coordinate bounds.
The supplied bounds are translated to have a center at the
center of one of the sheet's units (we arbitrarily use the
center un... |
Convert an iterable boundsspec (supplying l,b,r,t of a
BoundingRegion) into a Slice specification.
Includes all units whose centers are within the specified
sheet-coordinate bounds specified by boundsspec.
Exact inverse of _slicespec2boundsspec(). | def _boundsspec2slicespec(boundsspec,scs):
"""
Convert an iterable boundsspec (supplying l,b,r,t of a
BoundingRegion) into a Slice specification.
Includes all units whose centers are within the specified
sheet-coordinate bounds specified by boundsspec.
Exact inverse of ... |
Convert an iterable slicespec (supplying r1,r2,c1,c2 of a
Slice) into a BoundingRegion specification.
Exact inverse of _boundsspec2slicespec(). | def _slicespec2boundsspec(slicespec,scs):
"""
Convert an iterable slicespec (supplying r1,r2,c1,c2 of a
Slice) into a BoundingRegion specification.
Exact inverse of _boundsspec2slicespec().
"""
r1,r2,c1,c2 = slicespec
left,bottom = scs.matrix2sheet(r2,c1)
... |
A Chord plot is always drawn on a unit circle. | def get_extents(self, element, ranges, range_type='combined'):
"""
A Chord plot is always drawn on a unit circle.
"""
if range_type == 'extents':
return element.nodes.extents
xdim, ydim = element.nodes.kdims[:2]
xpad = .05 if self.label_index is None else 0.25... |
Given a dataset object and data in the appropriate format for
the interface, return a simple scalar. | def unpack_scalar(cls, dataset, data):
"""
Given a dataset object and data in the appropriate format for
the interface, return a simple scalar.
"""
if len(data) != 1 or len(data.columns) > 1:
return data
return data.iat[0,0] |
Returns the data of a Dataset as a dataframe avoiding copying
if it already a dataframe type. | def as_dframe(cls, dataset):
"""
Returns the data of a Dataset as a dataframe avoiding copying
if it already a dataframe type.
"""
if issubclass(dataset.interface, PandasInterface):
return dataset.data
else:
return dataset.dframe() |
Escapes a list of values to a string, converting to
unicode for safety. | def escape_vals(vals, escape_numerics=True):
"""
Escapes a list of values to a string, converting to
unicode for safety.
"""
# Ints formatted as floats to disambiguate with counter mode
ints, floats = "%.1f", "%.10f"
escaped = []
for v in vals:
if isinstance(v, np.timedelta64):
... |
Saves frames data into a json file at the
specified json_path, named with the widget uuid. | def save_json(self, frames):
"""
Saves frames data into a json file at the
specified json_path, named with the widget uuid.
"""
if self.json_save_path is None: return
path = os.path.join(self.json_save_path, '%s.json' % self.id)
if not os.path.isdir(self.json_save... |
Helper utility to access the active renderer for a given extension. | def renderer(name):
"""
Helper utility to access the active renderer for a given extension.
"""
try:
if name not in Store.renderers:
extension(name)
return Store.renderers[name]
except ImportError:
msg = ('Could not find a {name!r} renderer, available renderers ar... |
Saves the supplied object to file.
The available output formats depend on the backend being used. By
default and if the filename is a string the output format will be
inferred from the file extension. Otherwise an explicit format
will need to be specified. For ambiguous file extensions such as
html... | def save(obj, filename, fmt='auto', backend=None, **kwargs):
"""
Saves the supplied object to file.
The available output formats depend on the backend being used. By
default and if the filename is a string the output format will be
inferred from the file extension. Otherwise an explicit format
... |
Renders the HoloViews object to the corresponding object in the
specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default
backend. The resulting object can then be used with other objects
in the specified backend. For instance, if you want to make a
... | def render(obj, backend=None, **kwargs):
"""
Renders the HoloViews object to the corresponding object in the
specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default
backend. The resulting object can then be used with other objects
in the spec... |
Format option group kwargs into canonical options format | def _group_kwargs_to_options(cls, obj, kwargs):
"Format option group kwargs into canonical options format"
groups = Options._option_groups
if set(kwargs.keys()) - set(groups):
raise Exception("Keyword options %s must be one of %s" % (groups,
','.join(repr... |
Apply the groups to a single specified backend | def _apply_groups_to_backend(cls, obj, options, backend, clone):
"Apply the groups to a single specified backend"
obj_handle = obj
if options is None:
if clone:
obj_handle = obj.map(lambda x: x.clone(id=None))
else:
obj.map(lambda x: setatt... |
Group options by backend and filter out output group appropriately | def _grouped_backends(cls, options, backend):
"Group options by backend and filter out output group appropriately"
if options is None:
return [(backend or Store.current_backend, options)]
dfltdict = defaultdict(dict)
for spec, groups in options.items():
if 'outpu... |
Applies nested options definition grouped by type.
Applies options on an object or nested group of objects,
returning a new object with the options applied. This method
accepts the separate option namespaces explicitly (i.e 'plot',
'style' and 'norm').
If the options are to be ... | def apply_groups(cls, obj, options=None, backend=None, clone=True, **kwargs):
"""Applies nested options definition grouped by type.
Applies options on an object or nested group of objects,
returning a new object with the options applied. This method
accepts the separate option namespace... |
Deprecated, not expected to be used by any current code | def _cellmagic(cls, options, obj, strict=False):
"Deprecated, not expected to be used by any current code"
options, failure = cls._process_magic(options, strict)
if failure: return obj
if not isinstance(obj, Dimensioned):
return obj
else:
return StoreOptio... |
Deprecated, not expected to be used by any current code | def _linemagic(cls, options, strict=False, backend=None):
"Deprecated, not expected to be used by any current code"
backends = None if backend is None else [backend]
options, failure = cls._process_magic(options, strict, backends=backends)
if failure: return
with options_policy(s... |
Set default options for a session.
Set default options for a session. whether in a Python script or
a Jupyter notebook.
Args:
*options: Option objects used to specify the defaults.
backend: The plotting extension the options apply to | def defaults(cls, *options, **kwargs):
"""Set default options for a session.
Set default options for a session. whether in a Python script or
a Jupyter notebook.
Args:
*options: Option objects used to specify the defaults.
backend: The plotting extension the opti... |
Given a list of flat Option objects which may or may not have
'backend' in their kwargs, return a list of grouped backend | def _expand_by_backend(cls, options, backend):
"""
Given a list of flat Option objects which may or may not have
'backend' in their kwargs, return a list of grouped backend
"""
groups = defaultdict(list)
used_fallback = False
for obj in options:
if 'ba... |
Validates and expands a dictionaries of options indexed by
type[.group][.label] keys into separate style, plot, norm and
output options.
opts._expand_options({'Image': dict(cmap='viridis', show_title=False)})
returns
{'Image': {'plot': dict(show_title=False), 'style': ... | def _expand_options(cls, options, backend=None):
"""
Validates and expands a dictionaries of options indexed by
type[.group][.label] keys into separate style, plot, norm and
output options.
opts._expand_options({'Image': dict(cmap='viridis', show_title=False)})
retu... |
Generates an error message for an invalid option suggesting
similar options through fuzzy matching. | def _options_error(cls, opt, objtype, backend, valid_options):
"""
Generates an error message for an invalid option suggesting
similar options through fuzzy matching.
"""
current_backend = Store.current_backend
loaded_backends = Store.loaded_backends()
kws = Keywo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.