INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns true if the given BoundingBox x is contained within the bounding box where at least one of the boundaries of the box has to be exclusive. | def containsbb_exclusive(self, x):
"""
Returns true if the given BoundingBox x is contained within the
bounding box, where at least one of the boundaries of the box has
to be exclusive.
"""
left, bottom, right, top = self.aarect().lbrt()
leftx, bottomx, rightx, to... |
Return ( left bottom right top ) as a tuple. | def lbrt(self):
"""Return (left,bottom,right,top) as a tuple."""
return self._left, self._bottom, self._right, self._top |
Return the centroid of the rectangle. | def centroid(self):
"""
Return the centroid of the rectangle.
"""
left, bottom, right, top = self.lbrt()
return (right + left) / 2.0, (top + bottom) / 2.0 |
Recurses DynamicMap to find DynamicMaps inputs | def get_nested_dmaps(dmap):
"""Recurses DynamicMap to find DynamicMaps inputs
Args:
dmap: DynamicMap to recurse to look for DynamicMap inputs
Returns:
List of DynamicMap instances that were found
"""
if not isinstance(dmap, DynamicMap):
return []
dmaps = [dmap]
for ... |
Recurses supplied DynamicMap to find all streams | def get_nested_streams(dmap):
"""Recurses supplied DynamicMap to find all streams
Args:
dmap: DynamicMap to recurse to look for streams
Returns:
List of streams that were found
"""
return list({s for dmap in get_nested_dmaps(dmap) for s in dmap.streams}) |
Determine whether the Callable should have memoization enabled based on the supplied streams ( typically by a DynamicMap ). Memoization is disabled if any of the streams require it it and are currently in a triggered state. | def dynamicmap_memoization(callable_obj, streams):
"""
Determine whether the Callable should have memoization enabled
based on the supplied streams (typically by a
DynamicMap). Memoization is disabled if any of the streams require
it it and are currently in a triggered state.
"""
memoization... |
Group by supplied dimension ( s ) and overlay each group | def overlay(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and overlay each group
Groups data by supplied dimension(s) overlaying the groups
along the dimension(s).
Args:
dimensions: Dimension(s) of dimensions to group by
Returns:
N... |
Group by supplied dimension ( s ) and lay out groups in grid | def grid(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups in grid
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dim... |
Group by supplied dimension ( s ) and lay out groups | def layout(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and lay out groups
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension(s) to group by
Returns:
NdLayo... |
Applies simplified option definition returning a new object | def options(self, *args, **kwargs):
"""Applies simplified option definition returning a new object
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects in the HoloMap a simple format may be
used,... |
Deprecated method to split overlays inside the HoloMap. | def split_overlays(self):
"Deprecated method to split overlays inside the HoloMap."
if util.config.future_deprecations:
self.param.warning("split_overlays is deprecated and is now "
"a private method.")
return self._split_overlays() |
Splits overlays inside the HoloMap into list of HoloMaps | def _split_overlays(self):
"Splits overlays inside the HoloMap into list of HoloMaps"
if not issubclass(self.type, CompositeOverlay):
return None, self.clone()
item_maps = OrderedDict()
for k, overlay in self.data.items():
for key, el in overlay.items():
... |
Helper for __mul__ that returns the list of keys together with the dimension labels. | def _dimension_keys(self):
"""
Helper for __mul__ that returns the list of keys together with
the dimension labels.
"""
return [tuple(zip([d.name for d in self.kdims], [k] if self.ndims == 1 else k))
for k in self.keys()] |
Implements dynamic version of overlaying operation overlaying DynamicMaps and HoloMaps where the key dimensions of one is a strict superset of the other. | def _dynamic_mul(self, dimensions, other, keys):
"""
Implements dynamic version of overlaying operation overlaying
DynamicMaps and HoloMaps where the key dimensions of one is
a strict superset of the other.
"""
# If either is a HoloMap compute Dimension values
if ... |
Collate allows reordering nested containers | def collate(self, merge_type=None, drop=[], drop_constant=False):
"""Collate allows reordering nested containers
Collation allows collapsing nested mapping types by merging
their dimensions. In simple terms in merges nested containers
into a single merged type.
In the simple ca... |
Concatenates and aggregates along supplied dimensions | def collapse(self, dimensions=None, function=None, spreadfn=None, **kwargs):
"""Concatenates and aggregates along supplied dimensions
Useful to collapse stacks of objects into a single object,
e.g. to average a stack of Images or Curves.
Args:
dimensions: Dimension(s) to co... |
Samples element values at supplied coordinates. | def sample(self, samples=[], bounds=None, **sample_values):
"""Samples element values at supplied coordinates.
Allows sampling of element with a list of coordinates matching
the key dimensions, returning a new object containing just the
selected samples. Supports multiple signatures:
... |
Applies reduction to elements along the specified dimension ( s ). | def reduce(self, dimensions=None, function=None, spread_fn=None, **reduce_map):
"""Applies reduction to elements along the specified dimension(s).
Allows reducing the values along one or more key dimension
with the supplied function. Supports two signatures:
Reducing with a list of dim... |
Clone object and apply new group and/ or label. | def relabel(self, label=None, group=None, depth=1):
"""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... |
Computes and adjoins histogram along specified dimension ( s ). | def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, individually=True, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
... |
Returns True if the callable takes no arguments | def noargs(self):
"Returns True if the callable takes no arguments"
noargs = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None)
return self.argspec == noargs |
Clones the Callable optionally with new settings | def clone(self, callable=None, **overrides):
"""Clones the Callable optionally with new settings
Args:
callable: New callable function to wrap
**overrides: Parameter overrides to apply
Returns:
Cloned Callable object
"""
old = {k: v for k, v ... |
Returns a list of key dimensions that are unbounded excluding stream parameters. If any of theses key dimensions are unbounded the DynamicMap as a whole is also unbounded. | def unbounded(self):
"""
Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of theses key dimensions are
unbounded, the DynamicMap as a whole is also unbounded.
"""
unbounded_dims = []
# Dimensioned streams do not need to be b... |
Construct an initial key for based on the lower range bounds or values on the key dimensions. | def _initial_key(self):
"""
Construct an initial key for based on the lower range bounds or
values on the key dimensions.
"""
key = []
undefined = []
stream_params = set(util.stream_parameters(self.streams))
for kdim in self.kdims:
if str(kdim)... |
Make sure the supplied key values are within the bounds specified by the corresponding dimension range and soft_range. | def _validate_key(self, key):
"""
Make sure the supplied key values are within the bounds
specified by the corresponding dimension range and soft_range.
"""
if key == () and len(self.kdims) == 0: return ()
key = util.wrap_tuple(key)
assert len(key) == len(self.kdi... |
Updates attached streams and triggers events | def event(self, **kwargs):
"""Updates attached streams and triggers events
Automatically find streams matching the supplied kwargs to
update and trigger events on them.
Args:
**kwargs: Events to update streams with
"""
if self.callback.noargs and self.stream... |
Applies custom option tree to values return by the callback. | def _style(self, retval):
"Applies custom option tree to values return by the callback."
if self.id not in Store.custom_options():
return retval
spec = StoreOptions.tree_to_dict(Store.custom_options()[self.id])
return retval.opts(spec) |
Executes the callback with the appropriate args and kwargs | def _execute_callback(self, *args):
"Executes the callback with the appropriate args and kwargs"
self._validate_key(args) # Validate input key
# Additional validation needed to ensure kwargs don't clash
kdims = [kdim.name for kdim in self.kdims]
kwarg_items = [s.contents.it... |
Applies simplified option definition returning a new object. | def options(self, *args, **kwargs):
"""Applies simplified option definition returning a new object.
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects returned by the DynamicMap a simple
format... |
Clones the object overriding data and parameters. | 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
... |
Returns a new DynamicMap if the key ( tuple form ) expresses a cross product otherwise returns None. The cache argument is a dictionary ( key: element pairs ) of all the data found in the cache for this key. | def _cross_product(self, tuple_key, cache, data_slice):
"""
Returns a new DynamicMap if the key (tuple form) expresses a
cross product, otherwise returns None. The cache argument is a
dictionary (key:element pairs) of all the data found in the
cache for this key.
Each ke... |
Slices bounded DynamicMaps by setting the soft_ranges on key dimensions and applies data slice to cached and dynamic values. | def _slice_bounded(self, tuple_key, data_slice):
"""
Slices bounded DynamicMaps by setting the soft_ranges on
key dimensions and applies data slice to cached and dynamic
values.
"""
slices = [el for el in tuple_key if isinstance(el, slice)]
if any(el.step for el i... |
Applies selection by dimension name | 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... |
Request that a key/ value pair be considered for caching. | def _cache(self, key, val):
"""
Request that a key/value pair be considered for caching.
"""
cache_size = (1 if util.dimensionless_contents(self.streams, self.kdims)
else self.cache_size)
if len(self) >= cache_size:
first_key = next(k for k in se... |
Map a function to all objects matching the specs | def map(self, map_fn, specs=None, clone=True, link_inputs=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:
... |
Clone object and apply new group and/ or label. | def relabel(self, label=None, group=None, depth=1):
"""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... |
Splits a DynamicMap into its components. Only well defined for DynamicMap with consistent number and order of layers. | def _split_overlays(self):
"""
Splits a DynamicMap into its components. Only well defined for
DynamicMap with consistent number and order of layers.
"""
if not len(self):
raise ValueError('Cannot split DynamicMap before it has been initialized')
elif not issub... |
Unpacks DynamicMap into container of DynamicMaps | def collate(self):
"""Unpacks DynamicMap into container of DynamicMaps
Collation allows unpacking DynamicMaps which return Layout,
NdLayout or GridSpace objects into a single such object
containing DynamicMaps. Assumes that the items in the layout
or grid that is returned do not... |
Groups DynamicMap by one or more dimensions | def groupby(self, dimensions=None, container_type=None, group_type=None, **kwargs):
"""Groups DynamicMap by one or more dimensions
Applies groupby operation over the specified dimensions
returning an object of type container_type (expected to be
dictionary-like) containing the groups.
... |
Groups data by supplied dimension ( s ) laying the groups along the dimension ( s ) out in a GridSpace. | def grid(self, dimensions=None, **kwargs):
"""
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
grid: GridSp... |
Groups data by supplied dimension ( s ) laying the groups along the dimension ( s ) out in a NdLayout. | def layout(self, dimensions=None, **kwargs):
"""
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a NdLayout.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
layout: NdL... |
Group by supplied dimension ( s ) and overlay each group | def overlay(self, dimensions=None, **kwargs):
"""Group by supplied dimension(s) and overlay each group
Groups data by supplied dimension(s) overlaying the groups
along the dimension(s).
Args:
dimensions: Dimension(s) of dimensions to group by
Returns:
N... |
Computes and adjoins histogram along specified dimension ( s ). | def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimens... |
Reorders key dimensions on DynamicMap | def reindex(self, kdims=[], force=False):
"""Reorders key dimensions on DynamicMap
Create a new object with a reordered set of key dimensions.
Dropping dimensions is not allowed on a DynamicMap.
Args:
kdims: List of dimensions to reindex the mapping with
force: ... |
Snaps indices into the GridSpace to the closest coordinate. | def _transform_indices(self, key):
"""Snaps indices into the GridSpace to the closest coordinate.
Args:
key: Tuple index into the GridSpace
Returns:
Transformed key snapped to closest numeric coordinates
"""
ndims = self.ndims
if all(not (isinsta... |
Returns the keys of the GridSpace | def keys(self, full_grid=False):
"""Returns the keys of the GridSpace
Args:
full_grid (bool, optional): Return full cross-product of keys
Returns:
List of keys
"""
keys = super(GridSpace, self).keys()
if self.ndims == 1 or not full_grid:
... |
The last of a GridSpace is another GridSpace constituted of the last of the individual elements. To access the elements by their X Y position either index the position directly or use the items () method. | def last(self):
"""
The last of a GridSpace is another GridSpace
constituted of the last of the individual elements. To access
the elements by their X,Y position, either index the position
directly or use the items() method.
"""
if self.type == HoloMap:
... |
Returns the 2D shape of the GridSpace as ( rows cols ). | def shape(self):
"Returns the 2D shape of the GridSpace as (rows, cols)."
keys = self.keys()
if self.ndims == 1:
return (len(keys), 1)
return len(set(k[0] for k in keys)), len(set(k[1] for k in keys)) |
Initializes hover data based on Element dimension values. | def _get_hover_data(self, data, element):
"""
Initializes hover data based on Element dimension values.
"""
if 'hover' not in self.handles or self.static_source:
return
for k, v in self.overlay_dims.items():
dim = util.dimension_sanitizer(k.name)
... |
Initializes hover data based on Element dimension values. If empty initializes with no data. | def _get_hover_data(self, data, element):
"""
Initializes hover data based on Element dimension values.
If empty initializes with no data.
"""
if 'hover' not in self.handles or self.static_source:
return
npath = len([vs for vs in data.values()][0])
fo... |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
plot_method = properties.pop('plot_method', None)
properties = mpl_to_bokeh(properties)
data = dict(properties, **mapping)
if self._has_holes:
plot_method = 'multi_... |
Computes and adjoins histogram along specified dimension ( s ). | def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, index=0, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimensio... |
Return the values along the requested dimension. | 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... |
Get a layer in the Overlay. | def get(self, identifier, default=None):
"""Get a layer in the Overlay.
Get a particular layer in the Overlay using its path string
or an integer index.
Args:
identifier: Index or path string of the item to return
default: Value to return if no item is found
... |
Deprecated method to collapse layers in the Overlay. | def collapse(self, function):
"Deprecated method to collapse layers in the Overlay."
if config.future_deprecations:
self.param.warning('Overlay.collapse is deprecated, to'
'collapse multiple elements use a HoloMap.')
elements = list(self)
types... |
Predicate that returns whether the object is displayable or not ( i. e whether the object obeys the nesting hierarchy | def displayable(obj):
"""
Predicate that returns whether the object is displayable or not
(i.e whether the object obeys the nesting hierarchy
"""
if isinstance(obj, Overlay) and any(isinstance(o, (HoloMap, GridSpace))
for o in obj):
return False
if... |
Computes the depth of a DynamicMap overlay if it can be determined otherwise return None. | def overlay_depth(obj):
"""
Computes the depth of a DynamicMap overlay if it can be determined
otherwise return None.
"""
if isinstance(obj, DynamicMap):
if isinstance(obj.last, CompositeOverlay):
return len(obj.last)
elif obj.last is None:
return None
... |
Traverses an overlayable composite container to determine which objects are associated with specific ( Nd ) Overlay layers by z - order making sure to take DynamicMap Callables into account. Returns a mapping between the zorders of each layer and a corresponding lists of objects. | def compute_overlayable_zorders(obj, path=[]):
"""
Traverses an overlayable composite container to determine which
objects are associated with specific (Nd)Overlay layers by
z-order, making sure to take DynamicMap Callables into
account. Returns a mapping between the zorders of each layer and a
... |
Traverses a DynamicMap graph and determines if any components were overlaid dynamically ( i. e. by * on a DynamicMap ). | def is_dynamic_overlay(dmap):
"""
Traverses a DynamicMap graph and determines if any components
were overlaid dynamically (i.e. by * on a DynamicMap).
"""
if not isinstance(dmap, DynamicMap):
return False
elif dmap.callback._is_overlay:
return True
else:
return any(is... |
Splits a DynamicMap into the original component layers it was constructed from by traversing the graph to search for dynamically overlaid components ( i. e. constructed by using * on a DynamicMap ). Useful for assigning subplots of an OverlayPlot the streams that are responsible for driving their updates. Allows the Ov... | def split_dmap_overlay(obj, depth=0):
"""
Splits a DynamicMap into the original component layers it was
constructed from by traversing the graph to search for dynamically
overlaid components (i.e. constructed by using * on a DynamicMap).
Useful for assigning subplots of an OverlayPlot the streams th... |
Initializes all DynamicMap objects contained by the object | def initialize_dynamic(obj):
"""
Initializes all DynamicMap objects contained by the object
"""
dmaps = obj.traverse(lambda x: x, specs=[DynamicMap])
for dmap in dmaps:
if dmap.unbounded:
# Skip initialization until plotting code
continue
if not len(dmap):
... |
Returns the current frame in a mapping given a key mapping. | def get_plot_frame(map_obj, key_map, cached=False):
"""Returns the current frame in a mapping given a key mapping.
Args:
obj: Nested Dimensioned object
key_map: Dictionary mapping between dimensions and key value
cached: Whether to allow looking up key in cache
Returns:
The... |
Extracts a single frame from a nested object. | def get_nested_plot_frame(obj, key_map, cached=False):
"""Extracts a single frame from a nested object.
Replaces any HoloMap or DynamicMap in the nested data structure,
with the item corresponding to the supplied key.
Args:
obj: Nested Dimensioned object
key_map: Dictionary mapping bet... |
Generate helpful message regarding an undisplayable object | def undisplayable_info(obj, html=False):
"Generate helpful message regarding an undisplayable object"
collate = '<tt>collate</tt>' if html else 'collate'
info = "For more information, please consult the Composing Data tutorial (http://git.io/vtIQh)"
if isinstance(obj, HoloMap):
error = "HoloMap... |
Scales point sizes according to a scaling factor base size and size_fn which will be applied before scaling. | def compute_sizes(sizes, size_fn, scaling_factor, scaling_method, base_size):
"""
Scales point sizes according to a scaling factor,
base size and size_fn, which will be applied before
scaling.
"""
if sizes.dtype.kind not in ('i', 'f'):
return None
if scaling_method == 'area':
... |
Process a padding value supplied as a tuple or number and returns padding values for x - y - and z - axis. | def get_axis_padding(padding):
"""
Process a padding value supplied as a tuple or number and returns
padding values for x-, y- and z-axis.
"""
if isinstance(padding, tuple):
if len(padding) == 2:
xpad, ypad = padding
zpad = 0
elif len(padding) == 3:
... |
If lower and high values are equal ensures they are separated by the defined span. | def get_minimum_span(low, high, span):
"""
If lower and high values are equal ensures they are separated by
the defined span.
"""
if is_number(low) and low == high:
if isinstance(low, np.datetime64):
span = span * np.timedelta64(1, 's')
low, high = low-span, high+span
... |
Computes the data soft - and hard - range along a dimension given an element and a dictionary of ranges. | def get_range(element, ranges, dimension):
"""
Computes the data, soft- and hard-range along a dimension given
an element and a dictionary of ranges.
"""
if dimension and dimension != 'categorical':
if ranges and dimension.name in ranges:
drange = ranges[dimension.name]['data']
... |
Utility to find the range for an adjoined plot given the plot the element the Element the plot is adjoined to and the dictionary of ranges. | def get_sideplot_ranges(plot, element, main, ranges):
"""
Utility to find the range for an adjoined
plot given the plot, the element, the
Element the plot is adjoined to and the
dictionary of ranges.
"""
key = plot.current_key
dims = element.dimensions()
dim = dims[0] if 'frequency' ... |
Checks whether range1 is within the range specified by range2. | def within_range(range1, range2):
"""Checks whether range1 is within the range specified by range2."""
range1 = [r if isfinite(r) else None for r in range1]
range2 = [r if isfinite(r) else None for r in range2]
return ((range1[0] is None or range2[0] is None or range1[0] >= range2[0]) and
(r... |
Returns the common mode of the dynamic maps in given composite object | def get_dynamic_mode(composite):
"Returns the common mode of the dynamic maps in given composite object"
dynmaps = composite.traverse(lambda x: x, [DynamicMap])
holomaps = composite.traverse(lambda x: x, ['HoloMap'])
dynamic_unbounded = any(m.unbounded for m in dynmaps)
if holomaps:
validate... |
Initializes any DynamicMaps in unbounded mode. | def initialize_unbounded(obj, dimensions, key):
"""
Initializes any DynamicMaps in unbounded mode.
"""
select = dict(zip([d.name for d in dimensions], key))
try:
obj.select([DynamicMap], **select)
except KeyError:
pass |
Utility to export object to files frame by frame numbered individually. Will use default backend and figure format by default. | def save_frames(obj, filename, fmt=None, backend=None, options=None):
"""
Utility to export object to files frame by frame, numbered individually.
Will use default backend and figure format by default.
"""
backend = Store.current_backend if backend is None else backend
renderer = Store.renderers... |
Given a plot subplot and dynamically generated ( Nd ) Overlay find the closest matching Element for that plot. | def dynamic_update(plot, subplot, key, overlay, items):
"""
Given a plot, subplot and dynamically generated (Nd)Overlay
find the closest matching Element for that plot.
"""
match_spec = get_overlay_spec(overlay,
wrap_tuple(key),
sub... |
Maps an array of values to RGB hex strings given a color range and colormap. | def map_colors(arr, crange, cmap, hex=True):
"""
Maps an array of values to RGB hex strings, given
a color range and colormap.
"""
if isinstance(crange, np.ndarray):
xsorted = np.argsort(crange)
ypos = np.searchsorted(crange, arr)
arr = xsorted[ypos]
else:
if isin... |
Converts a matplotlib colormap to palette of RGB hex strings. | def mplcmap_to_palette(cmap, ncolors=None, categorical=False):
"""
Converts a matplotlib colormap to palette of RGB hex strings."
"""
from matplotlib.colors import Colormap, ListedColormap
ncolors = ncolors or 256
if not isinstance(cmap, Colormap):
import matplotlib.cm as cm
# A... |
Interpolates the color gradient between to hex colors | def linear_gradient(start_hex, finish_hex, n=10):
"""
Interpolates the color gradient between to hex colors
"""
s = hex2rgb(start_hex)
f = hex2rgb(finish_hex)
gradient = [s]
for t in range(1, n):
curr_vector = [int(s[j] + (float(t)/(n-1))*(f[j]-s[j])) for j in range(3)]
gradi... |
Interpolates the color gradients between a list of hex colors. | def polylinear_gradient(colors, n):
"""
Interpolates the color gradients between a list of hex colors.
"""
n_out = int(float(n) / (len(colors)-1))
gradient = linear_gradient(colors[0], colors[1], n_out)
if len(colors) == len(gradient):
return gradient
for col in range(1, len(colors... |
List available colormaps by combining matplotlib bokeh and colorcet colormaps or palettes if available. May also be narrowed down to a particular provider or list of providers. | def _list_cmaps(provider=None, records=False):
"""
List available colormaps by combining matplotlib, bokeh, and
colorcet colormaps or palettes if available. May also be
narrowed down to a particular provider or list of providers.
"""
if provider is None:
provider = providers
elif isi... |
Maintain descriptions of colormaps that include the following information: | def register_cmaps(category, provider, source, bg, names):
"""
Maintain descriptions of colormaps that include the following information:
name - string name for the colormap
category - intended use or purpose, mostly following matplotlib
provider - package providing the colormap directly
so... |
Return colormap names matching the specified filters. | def list_cmaps(provider=None, records=False, name=None, category=None, source=None,
bg=None, reverse=None):
"""
Return colormap names matching the specified filters.
"""
# Only uses names actually imported and currently available
available = _list_cmaps(provider=provider, records=True... |
Convert valid colormap specifications to a list of colors. | def process_cmap(cmap, ncolors=None, provider=None, categorical=False):
"""
Convert valid colormap specifications to a list of colors.
"""
providers_checked="matplotlib, bokeh, or colorcet" if provider is None else provider
if isinstance(cmap, Cycle):
palette = [rgb2hex(c) if isinstance(c, ... |
Maps the supplied colors into bins defined by the supplied levels. If a clip tuple is defined the bins are clipped to the defined range otherwise the range is computed from the levels and returned. | def color_intervals(colors, levels, clip=None, N=255):
"""
Maps the supplied colors into bins defined by the supplied levels.
If a clip tuple is defined the bins are clipped to the defined
range otherwise the range is computed from the levels and returned.
Arguments
---------
colors: list
... |
Returns an axis label for one or more dimensions. | def dim_axis_label(dimensions, separator=', '):
"""
Returns an axis label for one or more dimensions.
"""
if not isinstance(dimensions, list): dimensions = [dimensions]
return separator.join([d.pprint_label for d in dimensions]) |
Attaches plot refresh to all streams on the object. | def attach_streams(plot, obj, precedence=1.1):
"""
Attaches plot refresh to all streams on the object.
"""
def append_refresh(dmap):
for stream in get_nested_streams(dmap):
if plot.refresh not in stream._subscribers:
stream.add_subscriber(plot.refresh, precedence)
... |
Traverses the object and sets the supplied attribute on the object. Supports Dimensioned and DimensionedPlot types. | def traverse_setter(obj, attribute, value):
"""
Traverses the object and sets the supplied attribute on the
object. Supports Dimensioned and DimensionedPlot types.
"""
obj.traverse(lambda x: setattr(x, attribute, value)) |
NumPy based implementation of get_min_distance | def _get_min_distance_numpy(element):
"""
NumPy based implementation of get_min_distance
"""
xys = element.array([0, 1])
with warnings.catch_warnings():
warnings.filterwarnings('ignore', r'invalid value encountered in')
xys = xys.astype('float32').view(np.complex64)
distances... |
Gets the minimum sampling distance of the x - and y - coordinates in a grid. | def get_min_distance(element):
"""
Gets the minimum sampling distance of the x- and y-coordinates
in a grid.
"""
try:
from scipy.spatial.distance import pdist
return pdist(element.array([0, 1])).min()
except:
return _get_min_distance_numpy(element) |
Computes paths for a directed path which include an arrow to indicate the directionality of each edge. | def get_directed_graph_paths(element, arrow_length):
"""
Computes paths for a directed path which include an arrow to
indicate the directionality of each edge.
"""
edgepaths = element._split_edgepaths
edges = edgepaths.split(datatype='array', dimensions=edgepaths.kdims)
arrows = []
for e... |
Convert RGB ( A ) tuple to hex. | def rgb2hex(rgb):
"""
Convert RGB(A) tuple to hex.
"""
if len(rgb) > 3:
rgb = rgb[:-1]
return "#{0:02x}{1:02x}{2:02x}".format(*(int(v*255) for v in rgb)) |
Returns the key to look up a dimension range. | def dim_range_key(eldim):
"""
Returns the key to look up a dimension range.
"""
if isinstance(eldim, dim):
dim_name = repr(eldim)
if dim_name.startswith("'") and dim_name.endswith("'"):
dim_name = dim_name[1:-1]
else:
dim_name = eldim.name
return dim_name |
Given a Dimension creates bokeh widgets to select along that dimension. For numeric data a slider widget is created which may be either discrete if a holomap is supplied or the Dimension. values are set or a continuous widget for DynamicMaps. If the slider is discrete the returned mapping defines a mapping between valu... | def create_widget(self, dim, holomap=None, editable=False):
""""
Given a Dimension creates bokeh widgets to select along that
dimension. For numeric data a slider widget is created which
may be either discrete, if a holomap is supplied or the
Dimension.values are set, or a contin... |
Creates a set of widgets representing the dimensions on the plot object used to instantiate the widgets class. | def get_widgets(self):
"""
Creates a set of widgets representing the dimensions on the
plot object used to instantiate the widgets class.
"""
widgets = OrderedDict()
mappings = {}
for dim in self.mock_obj.kdims:
holomap = None if self.plot.dynamic else... |
Handle update events on bokeh server. | def update(self):
"""
Handle update events on bokeh server.
"""
if not self._queue:
return
dim, widget_type, attr, old, new = self._queue[-1]
self._queue = []
dim_label = dim.pprint_label
label, widget = self.widgets[dim_label]
if wid... |
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:
patch = self.renderer.diff(self.plot, binary=False)
msg = serialize_json(dict(content=patch.content... |
Processes the list of tools to be supplied to the plot. | def _init_tools(self, element, callbacks=[]):
"""
Processes the list of tools to be supplied to the plot.
"""
tooltips, hover_opts = self._hover_opts(element)
tooltips = [(ttp.pprint_label, '@{%s}' % util.dimension_sanitizer(ttp.name))
if isinstance(ttp, Dimen... |
Initializes hover data based on Element dimension values. If empty initializes with no data. | def _get_hover_data(self, data, element, dimensions=None):
"""
Initializes hover data based on Element dimension values.
If empty initializes with no data.
"""
if 'hover' not in self.handles or self.static_source:
return
for d in (dimensions or element.dimens... |
Given a list of other plots return axes that are shared with another plot by matching the dimensions specs stored as tags on the dimensions. | def _merge_ranges(self, plots, xspecs, yspecs):
"""
Given a list of other plots return axes that are shared
with another plot by matching the dimensions specs stored
as tags on the dimensions.
"""
plot_ranges = {}
for plot in plots:
if plot is None:
... |
Returns the dimensions corresponding to each axis. | def _get_axis_dims(self, element):
"""Returns the dimensions corresponding to each axis.
Should return a list of dimensions or list of lists of
dimensions, which will be formatted to label the axis
and to link axes.
"""
dims = element.dimensions()[:2]
if len(dims... |
Initializes Bokeh figure to draw Element into and sets basic figure and axis attributes including axes types labels titles and plot height and width. | def _init_plot(self, key, element, plots, ranges=None):
"""
Initializes Bokeh figure to draw Element into and sets basic
figure and axis attributes including axes types, labels,
titles and plot height and width.
"""
subplots = list(self.subplots.values()) if self.subplots... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.