INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Takes the output of group_select selecting subgroups iteratively,
avoiding duplicating select operations. | def iterative_select(obj, dimensions, selects, depth=None):
"""
Takes the output of group_select selecting subgroups iteratively,
avoiding duplicating select operations.
"""
ndims = len(dimensions)
depth = depth if depth is not None else ndims
items = []
if isinstance(selects, dict):
... |
Find a file given folder and filename. If the filename can be
resolved directly returns otherwise walks the supplied folder. | def find_file(folder, filename):
"""
Find a file given folder and filename. If the filename can be
resolved directly returns otherwise walks the supplied folder.
"""
matches = []
if os.path.isabs(filename) and os.path.isfile(filename):
return filename
for root, _, filenames in os.wal... |
Checks whether the supplied data is of DataFrame type. | def is_dataframe(data):
"""
Checks whether the supplied data is of DataFrame type.
"""
dd = None
if 'dask' in sys.modules and 'pandas' in sys.modules:
import dask.dataframe as dd
return((pd is not None and isinstance(data, pd.DataFrame)) or
(dd is not None and isinstance(data, ... |
Checks whether the supplied data is of Series type. | def is_series(data):
"""
Checks whether the supplied data is of Series type.
"""
dd = None
if 'dask' in sys.modules:
import dask.dataframe as dd
return((pd is not None and isinstance(data, pd.Series)) or
(dd is not None and isinstance(data, dd.Series))) |
Whether the object is a method on a parameterized object.
Args:
obj: Object to check
has_deps (boolean, optional): Check for dependencies
Whether to also check whether the method has been annotated
with param.depends
Returns:
A boolean value indicating whether the obje... | def is_param_method(obj, has_deps=False):
"""Whether the object is a method on a parameterized object.
Args:
obj: Object to check
has_deps (boolean, optional): Check for dependencies
Whether to also check whether the method has been annotated
with param.depends
Returns:
... |
Temporarily set parameters on Parameterized object to
constant=False. | def disable_constant(parameterized):
"""
Temporarily set parameters on Parameterized object to
constant=False.
"""
params = parameterized.params().values()
constants = [p.constant for p in params]
for p in params:
p.constant = False
try:
yield
except:
raise
... |
Function to get the first non-auxiliary object
label attribute from an NdMapping. | def get_ndmapping_label(ndmapping, attr):
"""
Function to get the first non-auxiliary object
label attribute from an NdMapping.
"""
label = None
els = itervalues(ndmapping.data)
while label is None:
try:
el = next(els)
except StopIteration:
return None... |
Return a complete dictionary mapping between stream parameter names
to their applicable renames, excluding parameters listed in
exclude_params.
If reverse is True, the mapping is from the renamed strings to the
original stream parameter names. | def stream_name_mapping(stream, exclude_params=['name'], reverse=False):
"""
Return a complete dictionary mapping between stream parameter names
to their applicable renames, excluding parameters listed in
exclude_params.
If reverse is True, the mapping is from the renamed strings to the
origina... |
Given a stream and a kwargs dictionary of parameter values, map to
the corresponding dictionary where the keys are substituted with the
appropriately renamed string.
If reverse, the output will be a dictionary using the original
parameter names given a dictionary using the renamed equivalents. | def rename_stream_kwargs(stream, kwargs, reverse=False):
"""
Given a stream and a kwargs dictionary of parameter values, map to
the corresponding dictionary where the keys are substituted with the
appropriately renamed string.
If reverse, the output will be a dictionary using the original
param... |
Given a list of streams, return a flat list of parameter name,
excluding those listed in the exclude list.
If no_duplicates is enabled, a KeyError will be raised if there are
parameter name clashes across the streams. | def stream_parameters(streams, no_duplicates=True, exclude=['name']):
"""
Given a list of streams, return a flat list of parameter name,
excluding those listed in the exclude list.
If no_duplicates is enabled, a KeyError will be raised if there are
parameter name clashes across the streams.
"""... |
Return a list of stream parameters that have not been associated
with any of the key dimensions. | def dimensionless_contents(streams, kdims, no_duplicates=True):
"""
Return a list of stream parameters that have not been associated
with any of the key dimensions.
"""
names = stream_parameters(streams, no_duplicates)
return [name for name in names if name not in kdims] |
Return a list of dimensions that have not been associated with
any streams. | def unbound_dimensions(streams, kdims, no_duplicates=True):
"""
Return a list of dimensions that have not been associated with
any streams.
"""
params = stream_parameters(streams, no_duplicates)
return [d for d in kdims if d not in params] |
Fills in tuple keys with dimensioned stream values as appropriate. | def wrap_tuple_streams(unwrapped, kdims, streams):
"""
Fills in tuple keys with dimensioned stream values as appropriate.
"""
param_groups = [(s.contents.keys(), s) for s in streams]
pairs = [(name,s) for (group, s) in param_groups for name in group]
substituted = []
for pos,el in enumerate... |
Drop any dimensioned streams from the keys and kdims. | def drop_streams(streams, kdims, keys):
"""
Drop any dimensioned streams from the keys and kdims.
"""
stream_params = stream_parameters(streams)
inds, dims = zip(*[(ind, kdim) for ind, kdim in enumerate(kdims)
if kdim not in stream_params])
get = operator.itemgetter(*inds)... |
Get value iterator from dictionary for Python 2 and 3 | def itervalues(obj):
"Get value iterator from dictionary for Python 2 and 3"
return iter(obj.values()) if sys.version_info.major == 3 else obj.itervalues() |
Get key iterator from dictionary for Python 2 and 3 | def iterkeys(obj):
"Get key iterator from dictionary for Python 2 and 3"
return iter(obj.keys()) if sys.version_info.major == 3 else obj.iterkeys() |
Gets a path from an Labelled object or from a tuple of an existing
path and a labelled object. The path strings are sanitized and
capitalized. | def get_path(item):
"""
Gets a path from an Labelled object or from a tuple of an existing
path and a labelled object. The path strings are sanitized and
capitalized.
"""
sanitizers = [group_sanitizer, label_sanitizer]
if isinstance(item, tuple):
path, item = item
if item.lab... |
Given a path, a list of existing paths and counts for each of the
existing paths. | def make_path_unique(path, counts, new):
"""
Given a path, a list of existing paths and counts for each of the
existing paths.
"""
added = False
while any(path == c[:i] for c in counts for i in range(1, len(c)+1)):
count = counts[path]
counts[path] += 1
if (not new and le... |
Efficient cartesian product of a list of 1D arrays returning the
expanded array views for each dimensions. By default arrays are
flattened, which may be controlled with the flat flag. The array
views can be turned into regular arrays with the copy flag. | def cartesian_product(arrays, flat=True, copy=False):
"""
Efficient cartesian product of a list of 1D arrays returning the
expanded array views for each dimensions. By default arrays are
flattened, which may be controlled with the flat flag. The array
views can be turned into regular arrays with the... |
Allows efficiently indexing into a cartesian product without
expanding it. The values should be defined as a list of iterables
making up the cartesian product and a linear index, returning
the cross product of the values at the supplied index. | def cross_index(values, index):
"""
Allows efficiently indexing into a cartesian product without
expanding it. The values should be defined as a list of iterables
making up the cartesian product and a linear index, returning
the cross product of the values at the supplied index.
"""
lengths ... |
Returns the indices of the lexicographical sorting
order of the supplied arrays. | def arglexsort(arrays):
"""
Returns the indices of the lexicographical sorting
order of the supplied arrays.
"""
dtypes = ','.join(array.dtype.str for array in arrays)
recarray = np.empty(len(arrays[0]), dtype=dtypes)
for i, array in enumerate(arrays):
recarray['f%s' % i] = array
... |
Given a DynamicMap return all streams that have any dimensioned
parameters i.e parameters also listed in the key dimensions. | def dimensioned_streams(dmap):
"""
Given a DynamicMap return all streams that have any dimensioned
parameters i.e parameters also listed in the key dimensions.
"""
dimensioned = []
for stream in dmap.streams:
stream_params = stream_parameters([stream])
if set([str(k) for k in dma... |
Expand the coordinates along a dimension of the gridded
dataset into an ND-array matching the dimensionality of
the dataset. | def expand_grid_coords(dataset, dim):
"""
Expand the coordinates along a dimension of the gridded
dataset into an ND-array matching the dimensionality of
the dataset.
"""
arrays = [dataset.interface.coords(dataset, d.name, True)
for d in dataset.kdims]
idx = dataset.get_dimensi... |
Safely converts NumPy datetime64 to a datetime object. | def dt64_to_dt(dt64):
"""
Safely converts NumPy datetime64 to a datetime object.
"""
ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')
return dt.datetime.utcfromtimestamp(ts) |
Computes a bounding range and density from a number of samples
assumed to be evenly spaced. Density is rounded to machine precision
using significant digits reported by sys.float_info.dig. | def bound_range(vals, density, time_unit='us'):
"""
Computes a bounding range and density from a number of samples
assumed to be evenly spaced. Density is rounded to machine precision
using significant digits reported by sys.float_info.dig.
"""
if not len(vals):
return(np.nan, np.nan, de... |
Validates regular sampling of a 1D array ensuring that the difference
in sampling steps is at most rtol times the smallest sampling step.
Returns a boolean indicating whether the sampling is regular. | def validate_regular_sampling(values, rtol=10e-6):
"""
Validates regular sampling of a 1D array ensuring that the difference
in sampling steps is at most rtol times the smallest sampling step.
Returns a boolean indicating whether the sampling is regular.
"""
diffs = np.diff(values)
return (l... |
Computes a grid density given the edges and number of samples.
Handles datetime grids correctly by computing timedeltas and
computing a density for the given time_unit. | def compute_density(start, end, length, time_unit='us'):
"""
Computes a grid density given the edges and number of samples.
Handles datetime grids correctly by computing timedeltas and
computing a density for the given time_unit.
"""
if isinstance(start, int): start = float(start)
if isinsta... |
Computes a date range given a start date, end date and the number
of samples. | def date_range(start, end, length, time_unit='us'):
"""
Computes a date range given a start date, end date and the number
of samples.
"""
step = (1./compute_density(start, end, length, time_unit))
if pd and isinstance(start, pd.Timestamp):
start = start.to_datetime64()
step = np.time... |
Converts a datetime type to an integer with the supplied time unit. | def dt_to_int(value, time_unit='us'):
"""
Converts a datetime type to an integer with the supplied time unit.
"""
if pd:
if isinstance(value, pd.Period):
value = value.to_timestamp()
if isinstance(value, pd.Timestamp):
try:
value = value.to_datetim... |
Converts cftime to timestamp since epoch in milliseconds
Non-standard calendars (e.g. Julian or no leap calendars)
are converted to standard Gregorian calendar. This can cause
extra space to be added for dates that don't exist in the original
calendar. In order to handle these dates correctly a custom ... | def cftime_to_timestamp(date, time_unit='us'):
"""Converts cftime to timestamp since epoch in milliseconds
Non-standard calendars (e.g. Julian or no leap calendars)
are converted to standard Gregorian calendar. This can cause
extra space to be added for dates that don't exist in the original
calend... |
Given a set of values returns the indices of each of those values
in the source array. | def search_indices(values, source):
"""
Given a set of values returns the indices of each of those values
in the source array.
"""
orig_indices = source.argsort()
return orig_indices[np.searchsorted(source[orig_indices], values)] |
Computes edges as midpoints of the bin centers. The first and
last boundaries are equidistant from the first and last midpoints
respectively. | def compute_edges(edges):
"""
Computes edges as midpoints of the bin centers. The first and
last boundaries are equidistant from the first and last midpoints
respectively.
"""
edges = np.asarray(edges)
if edges.dtype.kind == 'i':
edges = edges.astype('f')
midpoints = (edges[:-1]... |
Converts a MIME bundle into HTML. | def mimebundle_to_html(bundle):
"""
Converts a MIME bundle into HTML.
"""
if isinstance(bundle, tuple):
data, metadata = bundle
else:
data = bundle
html = data.get('text/html', '')
if 'application/javascript' in data:
js = data['application/javascript']
html +... |
Converts a NumPy scalar to a regular python type. | def numpy_scalar_to_python(scalar):
"""
Converts a NumPy scalar to a regular python type.
"""
scalar_type = type(scalar)
if np.issubclass_(scalar_type, np.float_):
return float(scalar)
elif np.issubclass_(scalar_type, np.int_):
return int(scalar)
return scalar |
Recursively iterates over type, group, label and overlay key,
finding the closest matching spec. | def closest_match(match, specs, depth=0):
"""
Recursively iterates over type, group, label and overlay key,
finding the closest matching spec.
"""
new_specs = []
match_lengths = []
for i, spec in specs:
if spec[0] == match[0]:
new_specs.append((i, spec[1:]))
else:... |
Conveniently add new aliases as keyword arguments. For instance
you can add a new alias with add_aliases(short='Longer string') | def add_aliases(self_or_cls, **kwargs):
"""
Conveniently add new aliases as keyword arguments. For instance
you can add a new alias with add_aliases(short='Longer string')
"""
self_or_cls.aliases.update({v:k for k,v in kwargs.items()}) |
Remove a list of aliases. | def remove_aliases(self_or_cls, aliases):
"""
Remove a list of aliases.
"""
for k,v in self_or_cls.aliases.items():
if v in aliases:
self_or_cls.aliases.pop(k) |
Whether or not the identifier will be prefixed.
Strings that require the prefix are generally not recommended. | def prefixed(self, identifier, version):
"""
Whether or not the identifier will be prefixed.
Strings that require the prefix are generally not recommended.
"""
invalid_starting = ['Mn', 'Mc', 'Nd', 'Pc']
if identifier.startswith('_'): return True
return((identifi... |
Remove diacritics and accents from the input leaving other
unicode characters alone. | def remove_diacritics(self_or_cls, identifier):
"""
Remove diacritics and accents from the input leaving other
unicode characters alone."""
chars = ''
for c in identifier:
replacement = unicodedata.normalize('NFKD', c).encode('ASCII', 'ignore')
if replacem... |
Given a unicode character c, return the shortened unicode name
(as a list of tokens) by applying the eliminations,
substitutions and transforms. | def shortened_character_name(self_or_cls, c, eliminations=[], substitutions={}, transforms=[]):
"""
Given a unicode character c, return the shortened unicode name
(as a list of tokens) by applying the eliminations,
substitutions and transforms.
"""
name = unicodedata.name... |
Strip underscores to make sure the number is correct after join | def _process_underscores(self, tokens):
"Strip underscores to make sure the number is correct after join"
groups = [[str(''.join(el))] if b else list(el)
for (b,el) in itertools.groupby(tokens, lambda k: k=='_')]
flattened = [el for group in groups for el in group]
proc... |
Accumulate blocks of hex and separate blocks by underscores | def sanitize(self, name, valid_fn):
"Accumulate blocks of hex and separate blocks by underscores"
invalid = {'\a':'a','\b':'b', '\v':'v','\f':'f','\r':'r'}
for cc in filter(lambda el: el in name, invalid.keys()):
raise Exception("Please use a raw string or escape control code '\%s'"
... |
The set of samples available along a particular dimension. | def values(cls, dataset, dim, expanded=True, flat=True, compute=True):
"""
The set of samples available along a particular dimension.
"""
dim_idx = dataset.get_dimension_index(dim)
if dim_idx in [0, 1]:
l, b, r, t = dataset.bounds.lbrt()
dim2, dim1 = datas... |
Slice the underlying numpy array in sheet coordinates. | def select(cls, dataset, selection_mask=None, **selection):
"""
Slice the underlying numpy array in sheet coordinates.
"""
selection = {k: slice(*sel) if isinstance(sel, tuple) else sel
for k, sel in selection.items()}
coords = tuple(selection[kd.name] if kd.... |
Sample the Raster along one or both of its dimensions,
returning a reduced dimensionality type, which is either
a ItemTable, Curve or Scatter. If two dimension samples
and a new_xaxis is provided the sample will be the value
of the sampled unit indexed by the value in the new_xaxis
... | def sample(cls, dataset, samples=[]):
"""
Sample the Raster along one or both of its dimensions,
returning a reduced dimensionality type, which is either
a ItemTable, Curve or Scatter. If two dimension samples
and a new_xaxis is provided the sample will be the value
of th... |
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 np.isscalar(data) or len(data) != 1:
return data
key = list(data.keys())[0]
if len(data[key]) == 1 a... |
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations. | def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
i = 0
c = complex(x,y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
... |
Return the lower and upper bounds of values along dimension.
Range of the y-dimension includes the symmetric or assymetric
error.
Args:
dimension: The dimension to compute the range on.
data_range (bool): Compute range from data values
dimension_range (bool)... | def range(self, dim, data_range=True, dimension_range=True):
"""Return the lower and upper bounds of values along dimension.
Range of the y-dimension includes the symmetric or assymetric
error.
Args:
dimension: The dimension to compute the range on.
data_range (... |
Property to access the Histogram values provided for backward compatibility | def values(self):
"Property to access the Histogram values provided for backward compatibility"
if util.config.future_deprecations:
self.param.warning('Histogram.values is deprecated in favor of '
'common dimension_values method.')
return self.dimension... |
Property to access the Histogram edges provided for backward compatibility | def edges(self):
"Property to access the Histogram edges provided for backward compatibility"
if util.config.future_deprecations:
self.param.warning('Histogram.edges is deprecated in favor of '
'common dimension_values method.')
return self.interface.co... |
Stacks an (Nd)Overlay of Area or Curve Elements by offsetting
their baselines. To stack a HoloMap or DynamicMap use the map
method. | def stack(cls, areas):
"""
Stacks an (Nd)Overlay of Area or Curve Elements by offsetting
their baselines. To stack a HoloMap or DynamicMap use the map
method.
"""
if not len(areas):
return areas
baseline = np.zeros(len(areas.values()[0]))
stack... |
Cleans up references to the plot on the attached Stream
subscribers. | def cleanup(self):
"""
Cleans up references to the plot on the attached Stream
subscribers.
"""
plots = self.traverse(lambda x: x, [Plot])
for plot in plots:
if not isinstance(plot, (GenericCompositePlot, GenericElementPlot, GenericOverlayPlot)):
... |
Matches a specification against the current Plot. | def matches(self, spec):
"""
Matches a specification against the current Plot.
"""
if callable(spec) and not isinstance(spec, type): return spec(self)
elif isinstance(spec, type): return isinstance(self, spec)
else:
raise ValueError("Matching specs have to be ... |
Traverses any nested DimensionedPlot returning a list
of all plots that match the specs. The specs should
be supplied as a list of either Plot types or callables,
which should return a boolean given the plot class. | def traverse(self, fn=None, specs=None, full_breadth=True):
"""
Traverses any nested DimensionedPlot returning a list
of all plots that match the specs. The specs should
be supplied as a list of either Plot types or callables,
which should return a boolean given the plot class.
... |
Returns the formatted dimension group strings
for a particular frame. | def _frame_title(self, key, group_size=2, separator='\n'):
"""
Returns the formatted dimension group strings
for a particular frame.
"""
if self.layout_dimensions is not None:
dimensions, key = zip(*self.layout_dimensions.items())
elif not self.dynamic and (no... |
Given an object, a specific key, and the normalization options,
this method will find the specified normalization options on
the appropriate OptionTree, group the elements according to
the selected normalization option (i.e. either per frame or
over the whole animation) and finally compu... | def compute_ranges(self, obj, key, ranges):
"""
Given an object, a specific key, and the normalization options,
this method will find the specified normalization options on
the appropriate OptionTree, group the elements according to
the selected normalization option (i.e. either ... |
Gets the normalization options for a LabelledData object by
traversing the object to find elements and their ids.
The id is then used to select the appropriate OptionsTree,
accumulating the normalization options into a dictionary.
Returns a dictionary of normalization options for each
... | def _get_norm_opts(self, obj):
"""
Gets the normalization options for a LabelledData object by
traversing the object to find elements and their ids.
The id is then used to select the appropriate OptionsTree,
accumulating the normalization options into a dictionary.
Return... |
Traverses the supplied object getting all options in opts for
the specified opt_type and specs. Also takes into account the
plotting class defaults for plot options. If a keyfn is
supplied the returned options will be grouped by the returned
keys. | def _traverse_options(cls, obj, opt_type, opts, specs=None, keyfn=None, defaults=True):
"""
Traverses the supplied object getting all options in opts for
the specified opt_type and specs. Also takes into account the
plotting class defaults for plot options. If a keyfn is
supplied... |
Uses traversal to find the appropriate projection
for a nested object. Respects projections set on
Overlays before considering Element based settings,
before finally looking up the default projection on
the plot type. If more than one non-None projection
type is found an exceptio... | def _get_projection(cls, obj):
"""
Uses traversal to find the appropriate projection
for a nested object. Respects projections set on
Overlays before considering Element based settings,
before finally looking up the default projection on
the plot type. If more than one no... |
Refreshes the plot by rerendering it and then pushing
the updated data if the plot has an associated Comm. | def refresh(self, **kwargs):
"""
Refreshes the plot by rerendering it and then pushing
the updated data if the plot has an associated Comm.
"""
traverse_setter(self, '_force', True)
key = self.current_key if self.current_key else self.keys[0]
dim_streams = [stream... |
Triggers update to a plot on a refresh event | def _trigger_refresh(self, key):
"Triggers update to a plot on a refresh event"
# Update if not top-level, batched or an ElementPlot
if not self.top_level or isinstance(self, GenericElementPlot):
self.update(key) |
Pushes updated plot data via the Comm. | def push(self):
"""
Pushes updated plot data via the Comm.
"""
if self.comm is None:
raise Exception('Renderer does not have a comm.')
diff = self.renderer.diff(self)
self.comm.send(diff) |
Initializes comm and attaches streams. | def init_comm(self):
"""
Initializes comm and attaches streams.
"""
if self.comm:
return self.comm
comm = None
if self.dynamic or self.renderer.widget_mode == 'live':
comm = self.renderer.comm_manager.get_server_comm()
return comm |
Computes the z-order of element in the NdOverlay
taking into account possible batching of elements. | def get_zorder(self, overlay, key, el):
"""
Computes the z-order of element in the NdOverlay
taking into account possible batching of elements.
"""
spec = util.get_overlay_spec(overlay, key, el)
return self.ordering.index(spec) |
Executes finalize hooks | def _execute_hooks(self, element):
"""
Executes finalize hooks
"""
if self.hooks and self.finalize_hooks:
self.param.warning(
"Supply either hooks or finalize_hooks not both, "
"using hooks and ignoring finalize_hooks.")
hooks = self.ho... |
Computes padding along the axes taking into account the plot aspect. | def get_padding(self, extents):
"""
Computes padding along the axes taking into account the plot aspect.
"""
(x0, y0, z0, x1, y1, z1) = extents
padding = 0 if self.overlaid else self.padding
xpad, ypad, zpad = get_axis_padding(padding)
if not self.overlaid and not... |
Gets the extents for the axes from the current Element. The globally
computed ranges can optionally override the extents.
The extents are computed by combining the data ranges, extents
and dimension ranges. Each of these can be obtained individually
by setting the range_type to one of:
... | def get_extents(self, element, ranges, range_type='combined', xdim=None, ydim=None, zdim=None):
"""
Gets the extents for the axes from the current Element. The globally
computed ranges can optionally override the extents.
The extents are computed by combining the data ranges, extents
... |
Given a HoloMap compute the appropriate (mapwise or framewise)
ranges in order to apply the Compositor collapse operations in
display mode (data collapse should already have happened). | def _apply_compositor(self, holomap, ranges=None, keys=None, dimensions=None):
"""
Given a HoloMap compute the appropriate (mapwise or framewise)
ranges in order to apply the Compositor collapse operations in
display mode (data collapse should already have happened).
"""
... |
Handles the creation of new subplots when a DynamicMap returns
a changing set of elements in an Overlay. | def _create_dynamic_subplots(self, key, items, ranges, **init_kwargs):
"""
Handles the creation of new subplots when a DynamicMap returns
a changing set of elements in an Overlay.
"""
length = self.style_grouping
group_fn = lambda x: (x.type.__name__, x.last.group, x.last... |
Updates existing subplots when the subplot has been assigned
to plot an element that is not an exact match to the object
it was initially assigned. | def _update_subplot(self, subplot, spec):
"""
Updates existing subplots when the subplot has been assigned
to plot an element that is not an exact match to the object
it was initially assigned.
"""
# See if the precise spec has already been assigned a cyclic
# in... |
Iterates over all subplots and collects the extents of each. | def _get_subplot_extents(self, overlay, ranges, range_type):
"""
Iterates over all subplots and collects the extents of each.
"""
if range_type == 'combined':
extents = {'extents': [], 'soft': [], 'hard': [], 'data': []}
else:
extents = {range_type: []}
... |
Creates a clone of the Layout with the nth-frame for each
Element. | def _get_frame(self, key):
"""
Creates a clone of the Layout with the nth-frame for each
Element.
"""
cached = self.current_key is None
layout_frame = self.layout.clone(shared_data=False)
if key == self.current_key and not self._force:
return self.curr... |
Strip out any leading/training commas from the token | def _strip_commas(cls, kw):
"Strip out any leading/training commas from the token"
kw = kw[:-1] if kw[-1]==',' else kw
return kw[1:] if kw[0]==',' else kw |
Collect the tokens from a (potentially) nested parse result. | def collect_tokens(cls, parseresult, mode):
"""
Collect the tokens from a (potentially) nested parse result.
"""
inner = '(%s)' if mode=='parens' else '[%s]'
if parseresult is None: return []
tokens = []
for token in parseresult.asList():
# If value is... |
Helper function to return dictionary given the parse results
from a pyparsing.nestedExpr object (containing keywords).
The ns is a dynamic namespace (typically the IPython Notebook
namespace) used to update the class-level namespace. | def todict(cls, parseresult, mode='parens', ns={}):
"""
Helper function to return dictionary given the parse results
from a pyparsing.nestedExpr object (containing keywords).
The ns is a dynamic namespace (typically the IPython Notebook
namespace) used to update the class-level ... |
Given a normalization parse group (i.e. the contents of the
braces), validate the option list and compute the appropriate
integer value for the normalization plotting option. | def process_normalization(cls, parse_group):
"""
Given a normalization parse group (i.e. the contents of the
braces), validate the option list and compute the appropriate
integer value for the normalization plotting option.
"""
if ('norm_options' not in parse_group): retu... |
Given a parsed options specification as a list of groups, combine
groups without options with the first subsequent group which has
options.
A line of the form
'A B C [opts] D E [opts_2]'
results in
[({A, B, C}, [opts]), ({D, E}, [opts_2])] | def _group_paths_without_options(cls, line_parse_result):
"""
Given a parsed options specification as a list of groups, combine
groups without options with the first subsequent group which has
options.
A line of the form
'A B C [opts] D E [opts_2]'
results in
... |
Convert any potentially deprecated paths and issue appropriate warnings | def apply_deprecations(cls, path):
"Convert any potentially deprecated paths and issue appropriate warnings"
split = path.split('.')
msg = 'Element {old} deprecated. Use {new} instead.'
for old, new in cls.deprecations:
if split[0] == old:
parsewarning.warning... |
Parse an options specification, returning a dictionary with
path keys and {'plot':<options>, 'style':<options>} values. | def parse(cls, line, ns={}):
"""
Parse an options specification, returning a dictionary with
path keys and {'plot':<options>, 'style':<options>} values.
"""
parses = [p for p in cls.opts_spec.scanString(line)]
if len(parses) != 1:
raise SyntaxError("Invalid s... |
Similar to parse but returns a list of Options objects instead
of the dictionary format. | def parse_options(cls, line, ns={}):
"""
Similar to parse but returns a list of Options objects instead
of the dictionary format.
"""
parsed = cls.parse(line, ns=ns)
options_list = []
for spec in sorted(parsed.keys()):
options = parsed[spec]
... |
Parse compositor specifications, returning a list Compositors | def parse(cls, line, ns={}):
"""
Parse compositor specifications, returning a list Compositors
"""
definitions = []
parses = [p for p in cls.compositor_spec.scanString(line)]
if len(parses) != 1:
raise SyntaxError("Invalid specification syntax.")
else... |
Method to get the appropriate normalization range dictionary
given a key and element. | def get_ranges(self, element, key):
"""
Method to get the appropriate normalization range dictionary
given a key and element.
"""
keys = self.p['keys']
ranges = self.p['ranges']
if ranges == {}:
return {d.name: element.range(d.name, self.data_range)
... |
Applies a aggregate function to all ViewableElements.
See :py:meth:`Dimensioned.opts` and :py:meth:`Apply.__call__`
for more information. | def aggregate(self, dimensions=None, function=None, spreadfn=None, **kwargs):
"""Applies a aggregate function to all ViewableElements.
See :py:meth:`Dimensioned.opts` and :py:meth:`Apply.__call__`
for more information.
"""
kwargs['_method_args'] = (dimensions, function, spreadfn... |
Applies a reduce function to all ViewableElement objects.
See :py:meth:`Dimensioned.opts` and :py:meth:`Apply.__call__`
for more information. | def reduce(self, dimensions=[], function=None, spreadfn=None, **kwargs):
"""Applies a reduce function to all ViewableElement objects.
See :py:meth:`Dimensioned.opts` and :py:meth:`Apply.__call__`
for more information.
"""
kwargs['_method_args'] = (dimensions, function, spreadfn)... |
Replaces dimensions in list with dictionary of overrides.
Args:
dimensions: List of dimensions
overrides: Dictionary of dimension specs indexed by name
Returns:
list: List of dimensions with replacements applied | def replace_dimensions(cls, dimensions, overrides):
"""Replaces dimensions in list with dictionary of overrides.
Args:
dimensions: List of dimensions
overrides: Dictionary of dimension specs indexed by name
Returns:
list: List of dimensions with replacements... |
Returns a filtered version of the DynamicMap cache leaving only
keys consistently with the newly specified values | def _filter_cache(self, dmap, kdims):
"""
Returns a filtered version of the DynamicMap cache leaving only
keys consistently with the newly specified values
"""
filtered = []
for key, value in dmap.data.items():
if not any(kd.values and v not in kd.values for k... |
Returns the corresponding Options object.
Args:
group: The options group. Flattens across groups if None.
backend: Current backend if None otherwise chosen backend.
Returns:
Options object associated with the object containing the
applied option keywords... | def get(self, group=None, backend=None):
"""Returns the corresponding Options object.
Args:
group: The options group. Flattens across groups if None.
backend: Current backend if None otherwise chosen backend.
Returns:
Options object associated with the objec... |
Prints a repr of the object including any applied options.
Args:
show_defaults: Whether to include default options | def info(self, show_defaults=False):
"""Prints a repr of the object including any applied options.
Args:
show_defaults: Whether to include default options
"""
pprinter = PrettyPrinter(show_options=True, show_defaults=show_defaults)
print(pprinter.pprint(self._obj)) |
Given a list of Dataset objects, cast them to the specified
datatype (by default the format matching the current interface)
with the given cast_type (if specified). | def cast(cls, datasets, datatype=None, cast_type=None):
"""
Given a list of Dataset objects, cast them to the specified
datatype (by default the format matching the current interface)
with the given cast_type (if specified).
"""
datatype = datatype or cls.datatype
... |
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected. | def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
... |
Given a Dataset object and selection to be applied returns
boolean to indicate whether a scalar value has been indexed. | def indexed(cls, dataset, selection):
"""
Given a Dataset object and selection to be applied returns
boolean to indicate whether a scalar value has been indexed.
"""
selected = list(selection.keys())
all_scalar = all((not isinstance(sel, (tuple, slice, set, list))
... |
Utility function to concatenate an NdMapping of Dataset objects. | def concatenate(cls, datasets, datatype=None, new_type=None):
"""
Utility function to concatenate an NdMapping of Dataset objects.
"""
from . import Dataset, default_datatype
new_type = new_type or Dataset
if isinstance(datasets, NdMapping):
dimensions = datas... |
Make adjustments to plot extents by computing
stacked bar heights, adjusting the bar baseline
and forcing the x-axis to be categorical. | def get_extents(self, element, ranges, range_type='combined'):
"""
Make adjustments to plot extents by computing
stacked bar heights, adjusting the bar baseline
and forcing the x-axis to be categorical.
"""
if self.batched:
overlay = self.current_frame
... |
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.data_vars) == 1 and
len(data[dataset.vdims[0].name].shape) == 0):
return data[dataset.vdims[0].... |
Applies optional checks to individual data elements before
they are inserted ensuring that they are of a certain
type. Subclassed may implement further element restrictions. | def _item_check(self, dim_vals, data):
"""
Applies optional checks to individual data elements before
they are inserted ensuring that they are of a certain
type. Subclassed may implement further element restrictions.
"""
if not self._check_items:
return
... |
Adds item to the data, applying dimension types and ensuring
key conforms to Dimension type and values. | def _add_item(self, dim_vals, data, sort=True, update=True):
"""
Adds item to the data, applying dimension types and ensuring
key conforms to Dimension type and values.
"""
sort = sort and self.sort
if not isinstance(dim_vals, tuple):
dim_vals = (dim_vals,)
... |
If a type is specified by the corresponding key dimension,
this method applies the type to the supplied key. | def _apply_key_type(self, keys):
"""
If a type is specified by the corresponding key dimension,
this method applies the type to the supplied key.
"""
typed_key = ()
for dim, key in zip(self.kdims, keys):
key_type = dim.type
if key_type is None:
... |
Partitions key into key and deep dimension groups. If only key
indices are supplied, the data is indexed with an empty tuple.
Keys with indices than there are dimensions will be padded. | def _split_index(self, key):
"""
Partitions key into key and deep dimension groups. If only key
indices are supplied, the data is indexed with an empty tuple.
Keys with indices than there are dimensions will be padded.
"""
if not isinstance(key, tuple):
key = ... |
Returns slice of data element if the item is deep
indexable. Warns if attempting to slice an object that has not
been declared deep indexable. | def _dataslice(self, data, indices):
"""
Returns slice of data element if the item is deep
indexable. Warns if attempting to slice an object that has not
been declared deep indexable.
"""
if self._deep_indexable and isinstance(data, Dimensioned) and indices:
r... |
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, *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
new_type (optional): Type to cast objec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.