INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Groups object 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.
Args:
dimensions: Dimension(s) to group by
container_type: Type to ... | def groupby(self, dimensions, container_type=None, group_type=None, **kwargs):
"""Groups object 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.
A... |
Adds a dimension and its values to the object
Requires the dimension name or object, the desired position in
the key dimensions and a key value scalar or sequence of the
same length as the existing keys.
Args:
dimension: Dimension or dimension spec to add
dim_po... | def add_dimension(self, dimension, dim_pos, dim_val, vdim=False, **kwargs):
"""Adds a dimension and its values to the object
Requires the dimension name or object, the desired position in
the key dimensions and a key value scalar or sequence of the
same length as the existing keys.
... |
Drops dimension(s) from keys
Args:
dimensions: Dimension(s) to drop
Returns:
Clone of object with with dropped dimension(s) | def drop_dimension(self, dimensions):
"""Drops dimension(s) from keys
Args:
dimensions: Dimension(s) to drop
Returns:
Clone of object with with dropped dimension(s)
"""
dimensions = [dimensions] if np.isscalar(dimensions) else dimensions
dims = [... |
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... |
Reindexes object dropping static or supplied kdims
Creates a new object with a reordered or reduced set of key
dimensions. By default drops all non-varying key dimensions.
Reducing the number of key dimensions will discard information
from the keys. All data values are accessible in th... | def reindex(self, kdims=[], force=False):
"""Reindexes object dropping static or supplied kdims
Creates a new object with a reordered or reduced set of key
dimensions. By default drops all non-varying key dimensions.
Reducing the number of key dimensions will discard information
... |
Prints information about the Dimensioned object, including the
number and type of objects contained within it and information
about its dimensions. | def info(self):
"""
Prints information about the Dimensioned object, including the
number and type of objects contained within it and information
about its dimensions.
"""
if (len(self.values()) > 0):
info_str = self.__class__.__name__ +\
... |
Merges other item with this object
Args:
other: Object containing items to merge into this object
Must be a dictionary or NdMapping type | def update(self, other):
"""Merges other item with this object
Args:
other: Object containing items to merge into this object
Must be a dictionary or NdMapping type
"""
if isinstance(other, NdMapping):
dims = [d for d in other.kdims if d not in se... |
Returns the keys of all the elements. | def keys(self):
" Returns the keys of all the elements."
if self.ndims == 1:
return [k[0] for k in self.data.keys()]
else:
return list(self.data.keys()) |
Returns all elements as a list in (key,value) format. | def items(self):
"Returns all elements as a list in (key,value) format."
return list(zip(list(self.keys()), list(self.values()))) |
Standard pop semantics for all mapping types | def pop(self, key, default=None):
"Standard pop semantics for all mapping types"
if not isinstance(key, tuple): key = (key,)
return self.data.pop(key, default) |
Deprecated method to convert an MultiDimensionalMapping of
Elements to a Table. | def table(self, datatype=None, **kwargs):
"""
Deprecated method to convert an MultiDimensionalMapping of
Elements to a Table.
"""
if config.future_deprecations:
self.param.warning("The table method is deprecated and should no "
"longer b... |
Deprecated method to convert a MultiDimensionalMapping to
a pandas DataFrame. Conversion to a dataframe now only
supported by specific subclasses such as UniformNdMapping
types. | def dframe(self):
"""
Deprecated method to convert a MultiDimensionalMapping to
a pandas DataFrame. Conversion to a dataframe now only
supported by specific subclasses such as UniformNdMapping
types.
"""
self.param.warning("The MultiDimensionalMapping.dframe metho... |
Expands slices containing steps into a list. | def _expand_slice(self, indices):
"""
Expands slices containing steps into a list.
"""
keys = list(self.data.keys())
expanded = []
for idx, ind in enumerate(indices):
if isinstance(ind, slice) and ind.step is not None:
dim_ind = slice(ind.start... |
Generates filter conditions used for slicing the data structure. | def _generate_conditions(self, map_slice):
"""
Generates filter conditions used for slicing the data structure.
"""
conditions = []
for dim, dim_slice in zip(self.kdims, map_slice):
if isinstance(dim_slice, slice):
start, stop = dim_slice.start, dim_sl... |
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
... |
Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
multi_index: Convert key dimensions to (multi-)index
Return... | def dframe(self, dimensions=None, multi_index=False):
"""Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
mul... |
Group inherited from items | def group(self):
"Group inherited from items"
if self._group:
return self._group
group = get_ndmapping_label(self, 'group') if len(self) else None
if group is None:
return type(self).__name__
return group |
Label inherited from items | def label(self):
"Label inherited from items"
if self._label:
return self._label
else:
if len(self):
label = get_ndmapping_label(self, 'label')
return '' if label is None else label
else:
return '' |
The type of elements stored in the mapping. | def type(self):
"The type of elements stored in the mapping."
if self._type is None and len(self):
self._type = self.values()[0].__class__
return self._type |
Snaps coordinate(s) to closest coordinate in Dataset
Args:
coords: List of coordinates expressed as tuples
**kwargs: Coordinates defined as keyword pairs
Returns:
List of tuples of the snapped coordinates
Raises:
NotImplementedError: Raised if s... | def closest(self, coords=[], **kwargs):
"""Snaps coordinate(s) to closest coordinate in Dataset
Args:
coords: List of coordinates expressed as tuples
**kwargs: Coordinates defined as keyword pairs
Returns:
List of tuples of the snapped coordinates
R... |
Sorts the data by the values along the supplied dimensions.
Args:
by: Dimension(s) to sort by
reverse (bool, optional): Reverse sort order
Returns:
Sorted Dataset | def sort(self, by=None, reverse=False):
"""
Sorts the data by the values along the supplied dimensions.
Args:
by: Dimension(s) to sort by
reverse (bool, optional): Reverse sort order
Returns:
Sorted Dataset
"""
if by is None:
... |
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, dim, 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): Include Dime... |
Adds a dimension and its values to the Dataset
Requires the dimension name or object, the desired position in
the key dimensions and a key value scalar or array of values,
matching the length o shape of the Dataset.
Args:
dimension: Dimension or dimension spec to add
... | def add_dimension(self, dimension, dim_pos, dim_val, vdim=False, **kwargs):
"""Adds a dimension and its values to the Dataset
Requires the dimension name or object, the desired position in
the key dimensions and a key value scalar or array of values,
matching the length o shape of the D... |
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, **selection):
"""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... |
Reindexes Dataset dropping static or supplied kdims
Creates a new object with a reordered or reduced set of key
dimensions. By default drops all non-varying key dimensions.x
Args:
kdims (optional): New list of key dimensionsx
vdims (optional): New list of value dimensio... | def reindex(self, kdims=None, vdims=None):
"""Reindexes Dataset dropping static or supplied kdims
Creates a new object with a reordered or reduced set of key
dimensions. By default drops all non-varying key dimensions.x
Args:
kdims (optional): New list of key dimensionsx
... |
Samples 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:
Sampling with a list of coordinates, e.g.:
ds.sample([(0, 0... | def sample(self, samples=[], bounds=None, closest=True, **kwargs):
"""Samples 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 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 dimensions, e.g.:
ds.reduce(['x'], np.mean)
Defining a reduction using keywords, e.g... | def reduce(self, dimensions=[], function=None, spreadfn=None, **reductions):
"""Applies reduction 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 dimensions, e.g.:
... |
Aggregates data on the supplied dimensions.
Aggregates over the supplied key dimensions with the defined
function.
Args:
dimensions: Dimension(s) to aggregate on
Default to all key dimensions
function: Aggregation function to apply, e.g. numpy.mean
... | def aggregate(self, dimensions=None, function=None, spreadfn=None, **kwargs):
"""Aggregates data on the supplied dimensions.
Aggregates over the supplied key dimensions with the defined
function.
Args:
dimensions: Dimension(s) to aggregate on
Default to all ... |
Groups object 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.
Args:
dimensions: Dimension(s) to group by
container_type: Type to ... | def groupby(self, dimensions=[], container_type=HoloMap, group_type=None,
dynamic=False, **kwargs):
"""Groups object by one or more dimensions
Applies groupby operation over the specified dimensions
returning an object of type container_type (expected to be
dictionary-li... |
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... |
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... |
Convert dimension values to a dictionary.
Returns a dictionary of column arrays along each dimension
of the element.
Args:
dimensions: Dimensions to return as columns
Returns:
Dictionary of arrays for each dimension | def columns(self, dimensions=None):
"""Convert dimension values to a dictionary.
Returns a dictionary of column arrays along each dimension
of the element.
Args:
dimensions: Dimensions to return as columns
Returns:
Dictionary of arrays for each dimensio... |
Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
multi_index: Convert key dimensions to (multi-)index
Return... | def dframe(self, dimensions=None, multi_index=False):
"""Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
mul... |
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
*args: Additional arguments to pass to constructor
... | def clone(self, data=None, shared_data=True, new_type=None, *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): Typ... |
Context manager that temporarily overrides the pyplot rcParams. | def _rc_context(rcparams):
"""
Context manager that temporarily overrides the pyplot rcParams.
"""
deprecated = ['text.latex.unicode', 'examples.directory']
old_rcparams = {k: mpl.rcParams[k] for k in mpl.rcParams.keys()
if mpl_version < '3.0' or k not in deprecated}
mpl.rcPa... |
Decorator for MPLPlot methods applying the matplotlib rc params
in the plots fig_rcparams while when method is called. | def mpl_rc_context(f):
"""
Decorator for MPLPlot methods applying the matplotlib rc params
in the plots fig_rcparams while when method is called.
"""
def wrapper(self, *args, **kwargs):
with _rc_context(self.fig_rcparams):
return f(self, *args, **kwargs)
return wrapper |
Return an axis which may need to be initialized from
a new figure. | def _init_axis(self, fig, axis):
"""
Return an axis which may need to be initialized from
a new figure.
"""
if not fig and self._create_fig:
fig = plt.figure()
l, b, r, t = self.fig_bounds
inches = self.fig_inches
fig.subplots_adjus... |
General method to finalize the axis and plot. | def _finalize_axis(self, key):
"""
General method to finalize the axis and plot.
"""
if 'title' in self.handles:
self.handles['title'].set_visible(self.show_title)
self.drawn = True
if self.subplot:
return self.handles['axis']
else:
... |
Method to return a matplotlib animation. The start and stop
frames may be specified as well as the fps. | def anim(self, start=0, stop=None, fps=30):
"""
Method to return a matplotlib animation. The start and stop
frames may be specified as well as the fps.
"""
figure = self.state or self.initialize_plot()
anim = animation.FuncAnimation(figure, self.update_frame,
... |
Plot all the views contained in the AdjointLayout Object using axes
appropriate to the layout configuration. All the axes are
supplied by LayoutPlot - the purpose of the call is to
invoke subplots with correct options and styles and hide any
empty axes as necessary. | def initialize_plot(self, ranges=None):
"""
Plot all the views contained in the AdjointLayout Object using axes
appropriate to the layout configuration. All the axes are
supplied by LayoutPlot - the purpose of the call is to
invoke subplots with correct options and styles and hid... |
Make adjustments to the positions of subplots (if available)
relative to the main plot axes as required.
This method is called by LayoutPlot after an initial pass
used to position all the Layouts together. This method allows
LayoutPlots to make final adjustments to the axis positions. | def adjust_positions(self, redraw=True):
"""
Make adjustments to the positions of subplots (if available)
relative to the main plot axes as required.
This method is called by LayoutPlot after an initial pass
used to position all the Layouts together. This method allows
L... |
Computes the tallest and widest cell for each row and column
by examining the Layouts in the GridSpace. The GridSpec is then
instantiated and the LayoutPlots are configured with the
appropriate embedded layout_types. The first element of the
returned tuple is a dictionary of all the Layo... | def _compute_gridspec(self, layout):
"""
Computes the tallest and widest cell for each row and column
by examining the Layouts in the GridSpace. The GridSpec is then
instantiated and the LayoutPlots are configured with the
appropriate embedded layout_types. The first element of t... |
Situate the current AdjointLayoutPlot in a LayoutPlot. The
LayoutPlot specifies a layout_type into which the AdjointLayoutPlot
must be embedded. This enclosing layout is guaranteed to have
enough cells to display all the views.
Based on this enforced layout format, a starting index
... | def grid_situate(self, current_idx, layout_type, subgrid_width):
"""
Situate the current AdjointLayoutPlot in a LayoutPlot. The
LayoutPlot specifies a layout_type into which the AdjointLayoutPlot
must be embedded. This enclosing layout is guaranteed to have
enough cells to displa... |
Plot all the views contained in the AdjointLayout Object using axes
appropriate to the layout configuration. All the axes are
supplied by LayoutPlot - the purpose of the call is to
invoke subplots with correct options and styles and hide any
empty axes as necessary. | def _create_subplots(self, layout, positions, layout_dimensions, ranges, axes={}, num=1, create=True):
"""
Plot all the views contained in the AdjointLayout Object using axes
appropriate to the layout configuration. All the axes are
supplied by LayoutPlot - the purpose of the call is to
... |
Temporarily declares the streams as being in a triggered state.
Needed by DynamicMap to determine whether to memoize on a Callable,
i.e. if a stream has memoization disabled and is in triggered state
Callable should disable lookup in the memoization cache. This is
done by the dynamicmap_memoization cont... | def triggering_streams(streams):
"""
Temporarily declares the streams as being in a triggered state.
Needed by DynamicMap to determine whether to memoize on a Callable,
i.e. if a stream has memoization disabled and is in triggered state
Callable should disable lookup in the memoization cache. This i... |
Utility to quickly and easily declare Stream classes. Designed
for interactive use such as notebooks and shouldn't replace
parameterized class definitions in source code that is imported.
Takes a stream class name and a set of keywords where each
keyword becomes a parameter. If the valu... | def define(cls, name, **kwargs):
"""
Utility to quickly and easily declare Stream classes. Designed
for interactive use such as notebooks and shouldn't replace
parameterized class definitions in source code that is imported.
Takes a stream class name and a set of keywords where ... |
Given a list of streams, collect all the stream parameters into
a dictionary and pass it to the union set of subscribers.
Passing multiple streams at once to trigger can be useful when a
subscriber may be set multiple times across streams but only
needs to be called once. | def trigger(cls, streams):
"""
Given a list of streams, collect all the stream parameters into
a dictionary and pass it to the union set of subscribers.
Passing multiple streams at once to trigger can be useful when a
subscriber may be set multiple times across streams but only
... |
Processes a list of streams promoting Parameterized objects and
methods to Param based streams. | def _process_streams(cls, streams):
"""
Processes a list of streams promoting Parameterized objects and
methods to Param based streams.
"""
parameterizeds = defaultdict(set)
valid, invalid = [], []
for s in streams:
if isinstance(s, Stream):
... |
Property returning the subscriber list | def subscribers(self):
"""Property returning the subscriber list"""
return [s for p, s in sorted(self._subscribers, key=lambda x: x[0])] |
Clear all subscribers registered to this stream.
The default policy of 'all' clears all subscribers. If policy is
set to 'user', only subscribers defined by the user are cleared
(precedence between zero and one). A policy of 'internal' clears
subscribers with precedence greater than uni... | def clear(self, policy='all'):
"""
Clear all subscribers registered to this stream.
The default policy of 'all' clears all subscribers. If policy is
set to 'user', only subscribers defined by the user are cleared
(precedence between zero and one). A policy of 'internal' clears
... |
Resets stream parameters to their defaults. | def reset(self):
"""
Resets stream parameters to their defaults.
"""
with util.disable_constant(self):
for k, p in self.params().items():
if k != 'name':
setattr(self, k, p.default) |
Register a callable subscriber to this stream which will be
invoked either when event is called or when this stream is
passed to the trigger classmethod.
Precedence allows the subscriber ordering to be
controlled. Users should only add subscribers with precedence
between zero an... | def add_subscriber(self, subscriber, precedence=0):
"""
Register a callable subscriber to this stream which will be
invoked either when event is called or when this stream is
passed to the trigger classmethod.
Precedence allows the subscriber ordering to be
controlled. U... |
The rename method allows stream parameters to be allocated to
new names to avoid clashes with other stream parameters of the
same name. Returns a new clone of the stream instance with the
specified name mapping. | def rename(self, **mapping):
"""
The rename method allows stream parameters to be allocated to
new names to avoid clashes with other stream parameters of the
same name. Returns a new clone of the stream instance with the
specified name mapping.
"""
params = {k: v ... |
Sets the stream parameters which are expected to be declared
constant. | def _set_stream_parameters(self, **kwargs):
"""
Sets the stream parameters which are expected to be declared
constant.
"""
with util.disable_constant(self):
self.param.set_param(**kwargs) |
The update method updates the stream parameters (without any
renaming applied) in response to some event. If the stream has a
custom transform method, this is applied to transform the
parameter values accordingly.
To update and trigger, use the event method. | def update(self, **kwargs):
"""
The update method updates the stream parameters (without any
renaming applied) in response to some event. If the stream has a
custom transform method, this is applied to transform the
parameter values accordingly.
To update and trigger, us... |
Verify consistency of dataframes that pass through this stream | def verify(self, x):
""" Verify consistency of dataframes that pass through this stream """
if type(x) != type(self.data):
raise TypeError("Input expected to be of type %s, got %s." %
(type(self.data).__name__, type(x).__name__))
elif isinstance(x, np.ndar... |
Clears the data in the stream | def clear(self):
"Clears the data in the stream"
if isinstance(self.data, np.ndarray):
data = self.data[:, :0]
elif util.pd and isinstance(self.data, util.pd.DataFrame):
data = self.data.iloc[:0]
elif isinstance(self.data, dict):
data = {k: v[:0] for k... |
Concatenate and slice the accepted data types to the defined
length. | def _concat(self, data):
"""
Concatenate and slice the accepted data types to the defined
length.
"""
if isinstance(data, np.ndarray):
data_length = len(data)
if data_length < self.length:
prev_chunk = self.data[-(self.length-data_length):]... |
Overrides update to concatenate streamed data up to defined length. | def update(self, **kwargs):
"""
Overrides update to concatenate streamed data up to defined length.
"""
data = kwargs.get('data')
if data is not None:
if (util.pd and isinstance(data, util.pd.DataFrame) and
list(data.columns) != list(self.data.columns)... |
Returns Params streams given a dictionary of parameters
Args:
params (dict): Dictionary of parameters
Returns:
List of Params streams | def from_params(cls, params):
"""Returns Params streams given a dictionary of parameters
Args:
params (dict): Dictionary of parameters
Returns:
List of Params streams
"""
key_fn = lambda x: id(x[1].owner)
streams = []
for _, group in grou... |
Bypasses selection on data and sets extents based on selection. | def select(self, selection_specs=None, **kwargs):
"""
Bypasses selection on data and sets extents based on selection.
"""
return super(Element2D, self).select(selection_specs, **kwargs) |
The split method allows splitting a Path type into a list of
subpaths of the same type. A start and/or end may be supplied
to select a subset of paths. | def split(self, start=None, end=None, datatype=None, **kwargs):
"""
The split method allows splitting a Path type into a list of
subpaths of the same type. A start and/or end may be supplied
to select a subset of paths.
"""
if not self.interface.multi:
if data... |
Returns a clone of the object with matching parameter values
containing the specified args and kwargs. | def clone(self, *args, **overrides):
"""
Returns a clone of the object with matching parameter values
containing the specified args and kwargs.
"""
link = overrides.pop('link', True)
settings = dict(self.get_param_values(), **overrides)
if 'id' not in settings:
... |
Converts bokehJS timestamp to datetime64. | def convert_timestamp(timestamp):
"""
Converts bokehJS timestamp to datetime64.
"""
datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)
return np.datetime64(datetime.replace(tzinfo=None)) |
Decodes an array, list or tuple of bytestrings to avoid python 3
bokeh serialization errors | def decode_bytes(array):
"""
Decodes an array, list or tuple of bytestrings to avoid python 3
bokeh serialization errors
"""
if (sys.version_info.major == 2 or not len(array) or
(isinstance(array, np.ndarray) and array.dtype.kind != 'O')):
return array
decoded = [v.decode('utf-8'... |
Pads Nones in a list of lists of plots with empty plots. | def layout_padding(plots, renderer):
"""
Pads Nones in a list of lists of plots with empty plots.
"""
widths, heights = defaultdict(int), defaultdict(int)
for r, row in enumerate(plots):
for c, p in enumerate(row):
if p is not None:
width, height = renderer.get_si... |
Computes the size of bokeh models that make up a layout such as
figures, rows, columns, widgetboxes and Plot. | def compute_plot_size(plot):
"""
Computes the size of bokeh models that make up a layout such as
figures, rows, columns, widgetboxes and Plot.
"""
if isinstance(plot, GridBox):
ndmapping = NdMapping({(x, y): fig for fig, y, x in plot.children}, kdims=['x', 'y'])
cols = ndmapping.grou... |
Utility to compute the aspect, plot width/height and sizing_mode
behavior.
Args:
width (int): Plot width
height (int): Plot height
frame_width (int): Plot frame width
frame_height (int): Plot frame height
explicit_width (list): List of user supplied widths
explicit_height (l... | def compute_layout_properties(
width, height, frame_width, frame_height, explicit_width,
explicit_height, aspect, data_aspect, responsive, size_multiplier,
logger=None):
"""
Utility to compute the aspect, plot width/height and sizing_mode
behavior.
Args:
width (int): Plot ... |
Context manager for silencing bokeh validation warnings. | def silence_warnings(*warnings):
"""
Context manager for silencing bokeh validation warnings.
"""
for warning in warnings:
silence(warning)
try:
yield
finally:
for warning in warnings:
silence(warning, False) |
Convert a fontsize to a pixel value | def font_size_to_pixels(size):
"""
Convert a fontsize to a pixel value
"""
if size is None or not isinstance(size, basestring):
return
conversions = {'em': 16, 'pt': 16/12.}
val = re.findall('\d+', size)
unit = re.findall('[a-z]+', size)
if (val and not unit) or (val and unit[0] ... |
Vectorized HSV to RGB conversion, adapted from:
http://stackoverflow.com/questions/24852345/hsv-to-rgb-color-conversion | def hsv_to_rgb(hsv):
"""
Vectorized HSV to RGB conversion, adapted from:
http://stackoverflow.com/questions/24852345/hsv-to-rgb-color-conversion
"""
h, s, v = (hsv[..., i] for i in range(3))
shape = h.shape
i = np.int_(h*6.)
f = h*6.-i
q = f
t = 1.-f
i = np.ravel(i)
f = ... |
Computes the width of a model and sets up appropriate padding
for Tabs and DataTable types. | def pad_width(model, table_padding=0.85, tabs_padding=1.2):
"""
Computes the width of a model and sets up appropriate padding
for Tabs and DataTable types.
"""
if isinstance(model, Row):
vals = [pad_width(child) for child in model.children]
width = np.max([v for v in vals if v is not... |
Accepts a grid of bokeh plots in form of a list of lists and
wraps any DataTable or Tabs in a WidgetBox with appropriate
padding. Required to avoid overlap in gridplot. | def pad_plots(plots):
"""
Accepts a grid of bokeh plots in form of a list of lists and
wraps any DataTable or Tabs in a WidgetBox with appropriate
padding. Required to avoid overlap in gridplot.
"""
widths = []
for row in plots:
row_widths = []
for p in row:
width... |
Filters out toolboxes out of a list of plots to be able to compose
them into a larger plot. | def filter_toolboxes(plots):
"""
Filters out toolboxes out of a list of plots to be able to compose
them into a larger plot.
"""
if isinstance(plots, list):
plots = [filter_toolboxes(plot) for plot in plots]
elif hasattr(plots, 'children'):
plots.children = [filter_toolboxes(chil... |
Uses flexx.pyscript to compile a python tick formatter to JS code | def py2js_tickformatter(formatter, msg=''):
"""
Uses flexx.pyscript to compile a python tick formatter to JS code
"""
try:
from flexx.pyscript import py2js
except ImportError:
param.main.param.warning(
msg+'Ensure Flexx is installed ("conda install -c bokeh flexx" '
... |
Computes a title for bokeh tabs from the key in the overlay, the
element and the containing (Nd)Overlay. | def get_tab_title(key, frame, overlay):
"""
Computes a title for bokeh tabs from the key in the overlay, the
element and the containing (Nd)Overlay.
"""
if isinstance(overlay, Overlay):
if frame is not None:
title = []
if frame.label:
title.append(fram... |
Iterates over the data and mapping for a ColumnDataSource and
replaces columns with repeating values with a scalar. This is
purely and optimization for scalar types. | def filter_batched_data(data, mapping):
"""
Iterates over the data and mapping for a ColumnDataSource and
replaces columns with repeating values with a scalar. This is
purely and optimization for scalar types.
"""
for k, v in list(mapping.items()):
if isinstance(v, dict) and 'field' in v... |
Determine if the CDS.data requires a full replacement or simply
needs to be updated. A replacement is required if untouched
columns are not the same length as the columns being updated. | def cds_column_replace(source, data):
"""
Determine if the CDS.data requires a full replacement or simply
needs to be updated. A replacement is required if untouched
columns are not the same length as the columns being updated.
"""
current_length = [len(v) for v in source.data.values() if isinst... |
Context manager to temporary override the hold policy. | def hold_policy(document, policy, server=False):
"""
Context manager to temporary override the hold policy.
"""
old_policy = document._hold
document._hold = policy
try:
yield
finally:
if server and not old_policy:
document.unhold()
else:
docume... |
Recursively updates attributes on a model including other
models. If the type of the new model matches the old model
properties are simply updated, otherwise the model is replaced. | def recursive_model_update(model, props):
"""
Recursively updates attributes on a model including other
models. If the type of the new model matches the old model
properties are simply updated, otherwise the model is replaced.
"""
updates = {}
valid_properties = model.properties_with_values(... |
Context manager to ensures data sources shared between multiple
plots are cleared and updated appropriately avoiding warnings and
allowing empty frames on subplots. Expects a list of
shared_sources and a mapping of the columns expected columns for
each source in the plots handles. | def update_shared_sources(f):
"""
Context manager to ensures data sources shared between multiple
plots are cleared and updated appropriately avoiding warnings and
allowing empty frames on subplots. Expects a list of
shared_sources and a mapping of the columns expected columns for
each source in... |
Uses a Dimension instance to convert an array of values to categorical
(i.e. string) values and applies escaping for colons, which bokeh
treats as a categorical suffix. | def categorize_array(array, dim):
"""
Uses a Dimension instance to convert an array of values to categorical
(i.e. string) values and applies escaping for colons, which bokeh
treats as a categorical suffix.
"""
return np.array([dim.pprint_value(x) for x in array]) |
Attaches plot refresh to all streams on the object. | def attach_periodic(plot):
"""
Attaches plot refresh to all streams on the object.
"""
def append_refresh(dmap):
for dmap in get_nested_dmaps(dmap):
dmap.periodic._periodic_util = periodic(plot.document)
return plot.hmap.traverse(append_refresh, [DynamicMap]) |
Converts support date types to milliseconds since epoch
Attempts highest precision conversion of different datetime
formats to milliseconds since the epoch (1970-01-01 00:00:00).
If datetime is a cftime with a non-standard calendar the
caveats described in hv.core.util.cftime_to_timestamp apply.
A... | def date_to_integer(date):
"""Converts support date types to milliseconds since epoch
Attempts highest precision conversion of different datetime
formats to milliseconds since the epoch (1970-01-01 00:00:00).
If datetime is a cftime with a non-standard calendar the
caveats described in hv.core.util... |
Orders a set of glyph handles using regular sort and an explicit
sort order. The explicit draw order must take the form of a list
of glyph names while the keys should be glyph names with a custom
suffix. The draw order may only match subset of the keys and any
matched items will take precedence over oth... | def glyph_order(keys, draw_order=[]):
"""
Orders a set of glyph handles using regular sort and an explicit
sort order. The explicit draw order must take the form of a list
of glyph names while the keys should be glyph names with a custom
suffix. The draw order may only match subset of the keys and a... |
Generates line paths for a quadmesh given 2D arrays of X and Y
coordinates. | def colormesh(X, Y):
"""
Generates line paths for a quadmesh given 2D arrays of X and Y
coordinates.
"""
X1 = X[0:-1, 0:-1].ravel()
Y1 = Y[0:-1, 0:-1].ravel()
X2 = X[1:, 0:-1].ravel()
Y2 = Y[1:, 0:-1].ravel()
X3 = X[1:, 1:].ravel()
Y3 = Y[1:, 1:].ravel()
X4 = X[0:-1, 1:].rave... |
Expands polygon data which contains holes to a bokeh multi_polygons
representation. Multi-polygons split by nans are expanded and the
correct list of holes is assigned to each sub-polygon. | def multi_polygons_data(element):
"""
Expands polygon data which contains holes to a bokeh multi_polygons
representation. Multi-polygons split by nans are expanded and the
correct list of holes is assigned to each sub-polygon.
"""
paths = element.split(datatype='array', dimensions=element.kdims)... |
Matches dimension specs used to link axes.
Axis dimension specs consists of a list of tuples corresponding
to each dimension, each tuple spec has the form (name, label, unit).
The name and label must match exactly while the unit only has to
match if both specs define one. | def match_dim_specs(specs1, specs2):
"""Matches dimension specs used to link axes.
Axis dimension specs consists of a list of tuples corresponding
to each dimension, each tuple spec has the form (name, label, unit).
The name and label must match exactly while the unit only has to
match if both spec... |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
ret = super(SideHistogramPlot, self)._init_glyph(plot, mapping, properties)
if not 'field' in mapping.get('fill_color', {}):
return ret
dim = mapping['fill_color']['field']... |
Returns a Bokeh glyph object. | def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties.pop('legend', None)
for prop in ['color', 'alpha']:
if prop not in properties:
continue
pval = properties.pop(prop)
line_prop = '... |
Splits area plots at nans and returns x- and y-coordinates for
each area separated by nans. | def _split_area(self, xs, lower, upper):
"""
Splits area plots at nans and returns x- and y-coordinates for
each area separated by nans.
"""
xnan = np.array([np.datetime64('nat') if xs.dtype.kind == 'M' else np.nan])
ynan = np.array([np.datetime64('nat') if lower.dtype.ki... |
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
... |
Get factors for categorical axes. | def _get_factors(self, element):
"""
Get factors for categorical axes.
"""
gdim = None
sdim = None
if element.ndims == 1:
pass
elif not (self.stacked or self.stack_index):
gdim = element.get_dimension(1)
else:
sdim = ele... |
Iterates over a x- and y-values in a stack layer
and appropriately offsets the layer on top of the
previous layer. | def get_stack(self, xvals, yvals, baselines, sign='positive'):
"""
Iterates over a x- and y-values in a stack layer
and appropriately offsets the layer on top of the
previous layer.
"""
bottoms, tops = [], []
for x, y in zip(xvals, yvals):
baseline = b... |
Called from __setstate__ in LabelledData in order to load
old pickles with outdated parameter names.
Warning: We want to keep pickle hacking to a minimum! | def param_aliases(d):
"""
Called from __setstate__ in LabelledData in order to load
old pickles with outdated parameter names.
Warning: We want to keep pickle hacking to a minimum!
"""
for old, new in ALIASES.items():
old_param = '_%s_param_value' % old
new_param = '_%s_param_va... |
Convert the input to a Dimension.
Args:
dimension: tuple, dict or string type to convert to Dimension
Returns:
A Dimension object constructed from the dimension spec. No
copy is performed if the input is already a Dimension. | def asdim(dimension):
"""Convert the input to a Dimension.
Args:
dimension: tuple, dict or string type to convert to Dimension
Returns:
A Dimension object constructed from the dimension spec. No
copy is performed if the input is already a Dimension.
"""
if isinstance(dimens... |
Return the Dimension.name for a dimension-like object.
Args:
dimension: Dimension or dimension string, tuple or dict
Returns:
The name of the Dimension or what would be the name if the
input as converted to a Dimension. | def dimension_name(dimension):
"""Return the Dimension.name for a dimension-like object.
Args:
dimension: Dimension or dimension string, tuple or dict
Returns:
The name of the Dimension or what would be the name if the
input as converted to a Dimension.
"""
if isinstance(di... |
Converts kdims and vdims to Dimension objects.
Args:
kdims: List or single key dimension(s) specified as strings,
tuples dicts or Dimension objects.
vdims: List or single value dimension(s) specified as strings,
tuples dicts or Dimension objects.
Returns:
Dictio... | def process_dimensions(kdims, vdims):
"""Converts kdims and vdims to Dimension objects.
Args:
kdims: List or single key dimension(s) specified as strings,
tuples dicts or Dimension objects.
vdims: List or single value dimension(s) specified as strings,
tuples dicts or Di... |
Clones the Dimension with new parameters
Derive a new Dimension that inherits existing parameters
except for the supplied, explicit overrides
Args:
spec (tuple, optional): Dimension tuple specification
**overrides: Dimension parameter overrides
Returns:
... | def clone(self, spec=None, **overrides):
"""Clones the Dimension with new parameters
Derive a new Dimension that inherits existing parameters
except for the supplied, explicit overrides
Args:
spec (tuple, optional): Dimension tuple specification
**overrides: Dim... |
The pretty-printed label string for the Dimension | def pprint_label(self):
"The pretty-printed label string for the Dimension"
unit = ('' if self.unit is None
else type(self.unit)(self.unit_format).format(unit=self.unit))
return bytes_to_unicode(self.label) + bytes_to_unicode(unit) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.