INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Given an object or Element class return the suitable plotting class needed to render it with the current renderer. | def plotting_class(cls, obj):
"""
Given an object or Element class, return the suitable plotting
class needed to render it with the current renderer.
"""
if isinstance(obj, AdjointLayout) or obj is AdjointLayout:
obj = Layout
if isinstance(obj, type):
... |
Returns JS and CSS and for embedding of widgets. | def html_assets(cls, core=True, extras=True, backends=None, script=False):
"""
Returns JS and CSS and for embedding of widgets.
"""
if backends is None:
backends = [cls.backend] if cls.backend else []
# Get all the widgets and find the set of required js widget files... |
Save a HoloViews object to file either using an explicitly supplied format or to the appropriate default. | def save(self_or_cls, obj, basename, fmt='auto', key={}, info={}, options=None, **kwargs):
"""
Save a HoloViews object to file, either using an explicitly
supplied format or to the appropriate default.
"""
if info or key:
raise Exception('Renderer does not support sav... |
Loads any resources required for display of plots in the Jupyter notebook | def load_nb(cls, inline=True):
"""
Loads any resources required for display of plots
in the Jupyter notebook
"""
with param.logging_level('ERROR'):
cls.notebook_context = True
cls.comm_manager = JupyterCommManager |
Deletes registered plots and calls Plot. cleanup | def _delete_plot(cls, plot_id):
"""
Deletes registered plots and calls Plot.cleanup
"""
plot = cls._plots.get(plot_id)
if plot is None:
return
plot.cleanup()
del cls._plots[plot_id] |
Return the strength of the match ( None if no match ) | def _match(cls, el, spec):
"Return the strength of the match (None if no match)"
spec_dict = dict(zip(['type', 'group', 'label'], spec.split('.')))
if not isinstance(el, Image) or spec_dict['type'] != 'Image':
raise NotImplementedError("Only Image currently supported")
sanit... |
Given a raster or input overlay generate a list of matched elements ( None if no match ) and corresponding tuple of match strength values. | def _match_overlay(self, raster, overlay_spec):
"""
Given a raster or input overlay, generate a list of matched
elements (None if no match) and corresponding tuple of match
strength values.
"""
ordering = [None]*len(overlay_spec) # Elements to overlay
strengths = ... |
Returns a Dataset template used as a wrapper around the data contained within the multi - interface dataset. | def _inner_dataset_template(cls, dataset):
"""
Returns a Dataset template used as a wrapper around the data
contained within the multi-interface dataset.
"""
from . import Dataset
vdims = dataset.vdims if getattr(dataset, 'level', None) is None else []
return Data... |
Tests if dimension is scalar in each subpath. | def isscalar(cls, dataset, dim):
"""
Tests if dimension is scalar in each subpath.
"""
if not dataset.data:
return True
ds = cls._inner_dataset_template(dataset)
isscalar = []
for d in dataset.data:
ds.data = d
isscalar.append(d... |
Applies selectiong on all the subpaths. | def select(cls, dataset, selection_mask=None, **selection):
"""
Applies selectiong on all the subpaths.
"""
if not dataset.data:
return []
ds = cls._inner_dataset_template(dataset)
data = []
for d in dataset.data:
ds.data = d
se... |
Allows selecting paths with usual NumPy slicing index. | def select_paths(cls, dataset, selection):
"""
Allows selecting paths with usual NumPy slicing index.
"""
return [s[0] for s in np.array([{0: p} for p in dataset.data])[selection]] |
Returns the shape of all subpaths making it appear like a single array of concatenated subpaths separated by NaN values. | def shape(cls, dataset):
"""
Returns the shape of all subpaths, making it appear like a
single array of concatenated subpaths separated by NaN values.
"""
if not dataset.data:
return (0, len(dataset.dimensions()))
rows, cols = 0, 0
ds = cls._inner_dat... |
Returns the length of the multi - tabular dataset making it appear like a single array of concatenated subpaths separated by NaN values. | def length(cls, dataset):
"""
Returns the length of the multi-tabular dataset making it appear
like a single array of concatenated subpaths separated by NaN
values.
"""
if not dataset.data:
return 0
length = 0
ds = cls._inner_dataset_template(d... |
Returns a single concatenated array of all subpaths separated by NaN values. If expanded keyword is False an array of arrays is returned. | def values(cls, dataset, dimension, expanded, flat):
"""
Returns a single concatenated array of all subpaths separated
by NaN values. If expanded keyword is False an array of arrays
is returned.
"""
if not dataset.data:
return np.array([])
values = []
... |
Splits a multi - interface Dataset into regular Datasets using regular tabular interfaces. | def split(cls, dataset, start, end, datatype, **kwargs):
"""
Splits a multi-interface Dataset into regular Datasets using
regular tabular interfaces.
"""
objs = []
if datatype is None:
for d in dataset.data[start: end]:
objs.append(dataset.clon... |
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... |
Convert dimension values to DataFrame. | 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... |
Convert dimension values to columnar array. | def array(self, dimensions=None):
"""Convert dimension values to columnar array.
Args:
dimensions: List of dimensions to return
Returns:
Array of columns corresponding to each dimension
"""
if dimensions is None:
dims = [d for d in self.kdims... |
Deprecated method to convert any Element to a Table. | def table(self, datatype=None):
"Deprecated method to convert any Element to a Table."
if config.future_deprecations:
self.param.warning(
"The table method is deprecated and should no "
"longer be used. Instead cast the %s to a "
"a Table direc... |
Deprecated method to convert data to dictionary | def mapping(self, kdims=None, vdims=None, **kwargs):
"Deprecated method to convert data to dictionary"
if config.future_deprecations:
self.param.warning(
"The mapping method is deprecated and should no "
"longer be used. Use another one of the common "
... |
Formatted contents of table cell. | def pprint_cell(self, row, col):
"""Formatted contents of table cell.
Args:
row (int): Integer index of table row
col (int): Integer index of table column
Returns:
Formatted table cell contents
"""
ndims = self.ndims
if col >= self.co... |
Return all constant dimensions. | def static_dimensions(self):
"""
Return all constant dimensions.
"""
dimensions = []
for dim in self.kdims:
if len(set(self.dimension_values(dim.name))) == 1:
dimensions.append(dim)
return dimensions |
Recursively descend through an Layout and NdMapping objects in order to add the supplied dimension values to all contained HoloMaps. | def _add_dimensions(self, item, dims, constant_keys):
"""
Recursively descend through an Layout and NdMapping objects
in order to add the supplied dimension values to all contained
HoloMaps.
"""
if isinstance(item, Layout):
item.fixed = False
dim_vals... |
Establish support for a kernel density estimate. | def _kde_support(bin_range, bw, gridsize, cut, clip):
"""Establish support for a kernel density estimate."""
kmin, kmax = bin_range[0] - bw * cut, bin_range[1] + bw * cut
if isfinite(clip[0]):
kmin = max(kmin, clip[0])
if isfinite(clip[1]):
kmax = min(kmax, clip[1])
return np.linspac... |
Renders the supplied object and displays it using the active GUI backend. | def show(self, obj):
"""
Renders the supplied object and displays it using the active
GUI backend.
"""
if self.interactive:
if isinstance(obj, list):
return [self.get_plot(o) for o in obj]
return self.get_plot(obj)
from .plot impor... |
Given a holoviews object and a percentage size apply heuristics to compute a suitable figure size. For instance scaling layouts and grids linearly can result in unwieldy figure sizes when there are a large number of elements. As ad hoc heuristics are used this functionality is kept separate from the plotting classes th... | def plot_options(cls, obj, percent_size):
"""
Given a holoviews object and a percentage size, apply heuristics
to compute a suitable figure size. For instance, scaling layouts
and grids linearly can result in unwieldy figure sizes when there
are a large number of elements. As ad ... |
Returns the latest plot data to update an existing plot. | def diff(self, plot):
"""
Returns the latest plot data to update an existing plot.
"""
if self.fig == 'auto':
figure_format = self.params('fig').objects[0]
else:
figure_format = self.fig
return self.html(plot, figure_format) |
Render matplotlib figure object and return the corresponding data. If as_script is True the content will be split in an HTML and a JS component. | def _figure_data(self, plot, fmt='png', bbox_inches='tight', as_script=False, **kwargs):
"""
Render matplotlib figure object and return the corresponding
data. If as_script is True, the content will be split in an
HTML and a JS component.
Similar to IPython.core.pylabtools.prin... |
Render a matplotlib animation object and return the corresponding data. | def _anim_data(self, anim, fmt):
"""
Render a matplotlib animation object and return the corresponding data.
"""
(writer, _, anim_kwargs, extra_args) = ANIMATION_OPTS[fmt]
if extra_args != []:
anim_kwargs = dict(anim_kwargs, extra_args=extra_args)
if self.fps... |
Compute the tight bounding box for each figure once reducing number of required canvas draw calls from N * 2 to N + 1 as a function of the number of frames. | def _compute_bbox(self, fig, kw):
"""
Compute the tight bounding box for each figure once, reducing
number of required canvas draw calls from N*2 to N+1 as a
function of the number of frames.
Tight bounding box computing code here mirrors:
matplotlib.backend_bases.Figure... |
Initialize matplotlib backend | def load_nb(cls, inline=True):
"""
Initialize matplotlib backend
"""
import matplotlib.pyplot as plt
backend = plt.get_backend()
if backend not in ['agg', 'module://ipykernel.pylab.backend_inline']:
plt.switch_backend('agg') |
Cleans up unused custom trees if all objects referencing the custom id have been garbage collected or tree is otherwise unreferenced. | def cleanup_custom_options(id, weakref=None):
"""
Cleans up unused custom trees if all objects referencing the
custom id have been garbage collected or tree is otherwise
unreferenced.
"""
try:
if Store._options_context:
return
weakrefs = Store._weakrefs.get(id, [])
... |
Context manager to temporarily set the skip_invalid and warn_on_skip class parameters on Options. | def options_policy(skip_invalid, warn_on_skip):
"""
Context manager to temporarily set the skip_invalid and warn_on_skip
class parameters on Options.
"""
settings = (Options.skip_invalid, Options.warn_on_skip)
(Options.skip_invalid, Options.warn_on_skip) = (skip_invalid, warn_on_skip)
yield
... |
Return a fuzzy match message based on the OptionError | def format_options_error(self):
"""
Return a fuzzy match message based on the OptionError
"""
allowed_keywords = self.allowed_keywords
target = allowed_keywords.target
matches = allowed_keywords.fuzzy_match(self.invalid_keyword)
if not matches:
matches... |
Print the traceback of the exception wrapped by the AbbreviatedException. | def print_traceback(self):
"""
Print the traceback of the exception wrapped by the AbbreviatedException.
"""
traceback.print_exception(self.etype, self.value, self.traceback) |
Return a new Options object that is filtered by the specified list of keys. Mutating self. kwargs to filter is unsafe due to the option expansion that occurs on initialization. | def filtered(self, allowed):
"""
Return a new Options object that is filtered by the specified
list of keys. Mutating self.kwargs to filter is unsafe due to
the option expansion that occurs on initialization.
"""
kws = {k:v for k,v in self.kwargs.items() if k in allowed}
... |
Truncates all contained Palette objects to a maximum number of samples and returns a new Options object containing the truncated or resampled Palettes. | def max_cycles(self, num):
"""
Truncates all contained Palette objects to a maximum number
of samples and returns a new Options object containing the
truncated or resampled Palettes.
"""
kwargs = {kw: (arg[num] if isinstance(arg, Palette) else arg)
for k... |
Returns True if the options cycle otherwise False | def cyclic(self):
"Returns True if the options cycle, otherwise False"
return any(isinstance(val, Cycle) for val in self.kwargs.values()) |
Computes a merged Options object for the given group name from the existing Options on the node and the new Options which are passed in. | def _merge_options(self, identifier, group_name, options):
"""
Computes a merged Options object for the given group
name from the existing Options on the node and the
new Options which are passed in.
"""
if group_name not in self.groups:
raise KeyError("Group ... |
Find the closest node or path to an the arbitrary path that is supplied down the tree from the given node. The mode argument may be either node or path which determines the return type. | def find(self, path, mode='node'):
"""
Find the closest node or path to an the arbitrary path that is
supplied down the tree from the given node. The mode argument
may be either 'node' or 'path' which determines the return
type.
"""
path = path.split('.') if isins... |
This method is designed to be called from the root of the tree. Given any LabelledData object this method will return the most appropriate Options object including inheritance. | def closest(self, obj, group, defaults=True):
"""
This method is designed to be called from the root of the
tree. Given any LabelledData object, this method will return
the most appropriate Options object, including inheritance.
In addition, closest supports custom options by ch... |
Using inheritance up to the root get the complete Options object for the given node and the specified group. | def options(self, group, target=None, defaults=True):
"""
Using inheritance up to the root, get the complete Options
object for the given node and the specified group.
"""
if target is None:
target = self.path
if self.groups.get(group, None) is None:
... |
Returns the single strongest matching compositor operation given an overlay. If no matches are found None is returned. | def strongest_match(cls, overlay, mode, backend=None):
"""
Returns the single strongest matching compositor operation
given an overlay. If no matches are found, None is returned.
The best match is defined as the compositor operation with the
highest match value as returned by th... |
Finds any applicable compositor and applies it. | def collapse_element(cls, overlay, ranges=None, mode='data', backend=None):
"""
Finds any applicable compositor and applies it.
"""
from .element import Element
from .overlay import Overlay, CompositeOverlay
unpack = False
if not isinstance(overlay, CompositeOverl... |
Given a map of Overlays apply all applicable compositors. | def collapse(cls, holomap, ranges=None, mode='data'):
"""
Given a map of Overlays, apply all applicable compositors.
"""
# No potential compositors
if cls.definitions == []:
return holomap
# Apply compositors
clone = holomap.clone(shared_data=False)
... |
Applies compositor operations to any HoloViews element or container using the map method. | def map(cls, obj, mode='data', backend=None):
"""
Applies compositor operations to any HoloViews element or container
using the map method.
"""
from .overlay import CompositeOverlay
element_compositors = [c for c in cls.definitions if len(c._pattern_spec) == 1]
ov... |
Find the match strength for a list of overlay items that must be exactly the same length as the pattern specification. | def _slice_match_level(self, overlay_items):
"""
Find the match strength for a list of overlay items that must
be exactly the same length as the pattern specification.
"""
level = 0
for spec, el in zip(self._pattern_spec, overlay_items):
if spec[0] != type(el)... |
Given an overlay return the match level and applicable slice of the overall overlay. The level an integer if there is a match or None if there is no match. | def match_level(self, overlay):
"""
Given an overlay, return the match level and applicable slice
of the overall overlay. The level an integer if there is a
match or None if there is no match.
The level integer is the number of matching components. Higher
values indicate... |
Apply the compositor on the input with the given input ranges. | def apply(self, value, input_ranges, backend=None):
"""
Apply the compositor on the input with the given input ranges.
"""
from .overlay import CompositeOverlay
if backend is None: backend = Store.current_backend
kwargs = {k: v for k, v in self.kwargs.items() if k != 'out... |
Use this method to set the backend to run the switch hooks | def set_current_backend(cls, backend):
"Use this method to set the backend to run the switch hooks"
for hook in cls._backend_switch_hooks:
hook(backend)
cls.current_backend = backend |
Equivalent to pickle. load except that the HoloViews trees is restored appropriately. | def load(cls, filename):
"""
Equivalent to pickle.load except that the HoloViews trees is
restored appropriately.
"""
cls.load_counter_offset = StoreOptions.id_offset()
val = pickle.load(filename)
cls.load_counter_offset = None
return val |
Equivalent to pickle. loads except that the HoloViews trees is restored appropriately. | def loads(cls, pickle_string):
"""
Equivalent to pickle.loads except that the HoloViews trees is
restored appropriately.
"""
cls.load_counter_offset = StoreOptions.id_offset()
val = pickle.loads(pickle_string)
cls.load_counter_offset = None
return val |
Equivalent to pickle. dump except that the HoloViews option tree is saved appropriately. | def dump(cls, obj, file, protocol=0):
"""
Equivalent to pickle.dump except that the HoloViews option
tree is saved appropriately.
"""
cls.save_option_state = True
pickle.dump(obj, file, protocol=protocol)
cls.save_option_state = False |
Equivalent to pickle. dumps except that the HoloViews option tree is saved appropriately. | def dumps(cls, obj, protocol=0):
"""
Equivalent to pickle.dumps except that the HoloViews option
tree is saved appropriately.
"""
cls.save_option_state = True
val = pickle.dumps(obj, protocol=protocol)
cls.save_option_state = False
return val |
Show information about a particular object or component class including the applicable style and plot options. Returns None if the object is not parameterized. | def info(cls, obj, ansi=True, backend='matplotlib', visualization=True,
recursive=False, pattern=None, elements=[]):
"""
Show information about a particular object or component class
including the applicable style and plot options. Returns None if
the object is not parameter... |
Given an object lookup the corresponding customized option tree if a single custom tree is applicable. | def lookup(cls, backend, obj):
"""
Given an object, lookup the corresponding customized option
tree if a single custom tree is applicable.
"""
ids = set([el for el in obj.traverse(lambda x: x.id) if el is not None])
if len(ids) == 0:
raise Exception("Object do... |
Transfers options for all backends from one object to another. Drops any options defined in the supplied drop list. | def transfer_options(cls, obj, new_obj, backend=None):
"""
Transfers options for all backends from one object to another.
Drops any options defined in the supplied drop list.
"""
backend = cls.current_backend if backend is None else backend
type_name = type(new_obj).__nam... |
Given a component such as an Element ( e. g. Image Curve ) or a container ( e. g Layout ) specify new style options to be accepted by the corresponding plotting class. | def add_style_opts(cls, component, new_options, backend=None):
"""
Given a component such as an Element (e.g. Image, Curve) or a
container (e.g Layout) specify new style options to be
accepted by the corresponding plotting class.
Note: This is supplied for advanced users who kno... |
Register the supplied dictionary of associations between elements and plotting classes to the specified backend. | def register(cls, associations, backend, style_aliases={}):
"""
Register the supplied dictionary of associations between
elements and plotting classes to the specified backend.
"""
if backend not in cls.registry:
cls.registry[backend] = {}
cls.registry[backend... |
Specify a display hook that will be applied to objects of type objtype. The group specifies the set to which the display hook belongs allowing the Store to compute the precedence within each group. | def set_display_hook(cls, group, objtype, hook):
"""
Specify a display hook that will be applied to objects of type
objtype. The group specifies the set to which the display hook
belongs, allowing the Store to compute the precedence within
each group.
"""
cls._dis... |
Using any display hooks that have been registered render the object to a dictionary of MIME types and metadata information. | def render(cls, obj):
"""
Using any display hooks that have been registered, render the
object to a dictionary of MIME types and metadata information.
"""
class_hierarchy = inspect.getmro(type(obj))
hooks = []
for _, type_hooks in cls._display_hooks.items():
... |
Stop collecting OptionErrors recorded with the record_skipped_option method and return them | def stop_recording_skipped(cls):
"""
Stop collecting OptionErrors recorded with the
record_skipped_option method and return them
"""
if cls._errors_recorded is None:
raise Exception('Cannot stop recording before it is started')
recorded = cls._errors_recorded[... |
Given an OptionTree convert it into the equivalent dictionary format. | def tree_to_dict(cls, tree):
"""
Given an OptionTree, convert it into the equivalent dictionary format.
"""
specs = {}
for k in tree.keys():
spec_key = '.'.join(k)
specs[spec_key] = {}
for grp in tree[k].groups:
kwargs = tree[k]... |
Recursively propagate an id through an object for components matching the applied_keys. This method can only be called if there is a tree with a matching id in Store. custom_options | def propagate_ids(cls, obj, match_id, new_id, applied_keys, backend=None):
"""
Recursively propagate an id through an object for components
matching the applied_keys. This method can only be called if
there is a tree with a matching id in Store.custom_options
"""
applied ... |
Given an list of ids as captured with capture_ids restore the ids. Note the structure of an object must not change between the calls to capture_ids and restore_ids. | def restore_ids(cls, obj, ids):
"""
Given an list of ids as captured with capture_ids, restore the
ids. Note the structure of an object must not change between
the calls to capture_ids and restore_ids.
"""
ids = iter(ids)
obj.traverse(lambda o: setattr(o, 'id', ne... |
Apply the given option specs to the supplied options tree. | def apply_customizations(cls, spec, options):
"""
Apply the given option specs to the supplied options tree.
"""
for key in sorted(spec.keys()):
if isinstance(spec[key], (list, tuple)):
customization = {v.key:v for v in spec[key]}
else:
... |
Given a specification validated it against the options tree for the specified backends by raising OptionError for invalid options. If backends is None validates against all the currently loaded backend. | def validate_spec(cls, spec, backends=None):
"""
Given a specification, validated it against the options tree for
the specified backends by raising OptionError for invalid
options. If backends is None, validates against all the
currently loaded backend.
Only useful when ... |
Returns an options validation error message if there are any invalid keywords. Otherwise returns None. | def validation_error_message(cls, spec, backends=None):
"""
Returns an options validation error message if there are any
invalid keywords. Otherwise returns None.
"""
try:
cls.validate_spec(spec, backends=backends)
except OptionError as e:
return e... |
Expands compositor definition keys into { type }. { group } keys. For instance a compositor operation returning a group string Image of element type RGB expands to RGB. Image. | def expand_compositor_keys(cls, spec):
"""
Expands compositor definition keys into {type}.{group}
keys. For instance a compositor operation returning a group
string 'Image' of element type RGB expands to 'RGB.Image'.
"""
expanded_spec={}
applied_keys = []
... |
Returns the appropriate set of customized subtree clones for an object suitable for merging with Store. custom_options ( i. e with the ids appropriately offset ). Note if an object has no integer ids a new OptionTree is built. | def create_custom_trees(cls, obj, options=None):
"""
Returns the appropriate set of customized subtree clones for
an object, suitable for merging with Store.custom_options (i.e
with the ids appropriately offset). Note if an object has no
integer ids a new OptionTree is built.
... |
Given a full options dictionary and options groups specified as a keywords return the full set of merged options: | def merge_options(cls, groups, options=None,**kwargs):
"""
Given a full options dictionary and options groups specified
as a keywords, return the full set of merged options:
>>> options={'Curve':{'style':dict(color='b')}}
>>> style={'Curve':{'linewidth':10 }}
>>> merged ... |
Method to capture and restore option state. When called without any state supplied the current state is returned. Then if this state is supplied back in a later call using the same object the original state is restored. | def state(cls, obj, state=None):
"""
Method to capture and restore option state. When called
without any state supplied, the current state is
returned. Then if this state is supplied back in a later call
using the same object, the original state is restored.
"""
i... |
Context - manager for temporarily setting options on an object ( if options is None no options will be set ). Once the context manager exits both the object and the Store will be left in exactly the same state they were in before the context manager was used. | def options(cls, obj, options=None, **kwargs):
"""
Context-manager for temporarily setting options on an object
(if options is None, no options will be set) . Once the
context manager exits, both the object and the Store will be
left in exactly the same state they were in before ... |
Compute an appropriate offset for future id values given the set of ids currently defined across backends. | def id_offset(cls):
"""
Compute an appropriate offset for future id values given the set
of ids currently defined across backends.
"""
max_ids = []
for backend in Store.renderers.keys():
store_ids = Store.custom_options(backend=backend).keys()
max_... |
Given the id_mapping from previous ids to new ids and the new custom tree dictionary update the current backend with the supplied trees and update the keys in the remaining backends to stay linked with the current object. | def update_backends(cls, id_mapping, custom_trees, backend=None):
"""
Given the id_mapping from previous ids to new ids and the new
custom tree dictionary, update the current backend with the
supplied trees and update the keys in the remaining backends to
stay linked with the cur... |
Pure Python function for customize HoloViews objects in terms of their style plot and normalization options. | def set_options(cls, obj, options=None, backend=None, **kwargs):
"""
Pure Python function for customize HoloViews objects in terms of
their style, plot and normalization options.
The options specification is a dictionary containing the target
for customization as a {type}.{group... |
Checks if supplied object is a valid color spec. | def is_color(color):
"""
Checks if supplied object is a valid color spec.
"""
if not isinstance(color, basestring):
return False
elif RGB_HEX_REGEX.match(color):
return True
elif color in COLOR_ALIASES:
return True
elif color in cnames:
return True
return ... |
Validates a style and associated value. | def validate(style, value, vectorized=True):
"""
Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
vectorized: bool
Whether validator should allow vectorized... |
Filters styles which are specific to a particular artist e. g. for a GraphPlot this will filter options specific to the nodes and edges. | def filter_styles(style, group, other_groups, blacklist=[]):
"""
Filters styles which are specific to a particular artist, e.g.
for a GraphPlot this will filter options specific to the nodes and
edges.
Arguments
---------
style: dict
Dictionary of styles and values
group: str
... |
Wraps formatting function or string in appropriate matplotlib formatter type. | def wrap_formatter(formatter):
"""
Wraps formatting function or string in
appropriate matplotlib formatter type.
"""
if isinstance(formatter, ticker.Formatter):
return formatter
elif callable(formatter):
args = [arg for arg in _getargspec(formatter).args
if arg !=... |
Tests whether two axes overlap vertically | def axis_overlap(ax1, ax2):
"""
Tests whether two axes overlap vertically
"""
b1, t1 = ax1.get_position().intervaly
b2, t2 = ax2.get_position().intervaly
return t1 > b2 and b1 < t2 |
Recursively iterate over lists of axes merging them by their vertical overlap leaving a list of rows. | def resolve_rows(rows):
"""
Recursively iterate over lists of axes merging
them by their vertical overlap leaving a list
of rows.
"""
merged_rows = []
for row in rows:
overlap = False
for mrow in merged_rows:
if any(axis_overlap(ax1, ax2) for ax1 in row
... |
Calculate heights and widths of axes and adjust the size of the figure to match the aspect. | def fix_aspect(fig, nrows, ncols, title=None, extra_artists=[],
vspace=0.2, hspace=0.2):
"""
Calculate heights and widths of axes and adjust
the size of the figure to match the aspect.
"""
fig.canvas.draw()
w, h = fig.get_size_inches()
# Compute maximum height and width of ea... |
Compute a tight bounding box around all the artists in the figure. | def get_tight_bbox(fig, bbox_extra_artists=[], pad=None):
"""
Compute a tight bounding box around all the artists in the figure.
"""
renderer = fig.canvas.get_renderer()
bbox_inches = fig.get_tightbbox(renderer)
bbox_artists = bbox_extra_artists[:]
bbox_artists += fig.get_default_bbox_extra_... |
Return the array data from any Raster or Image type | def get_raster_array(image):
"""
Return the array data from any Raster or Image type
"""
if isinstance(image, RGB):
rgb = image.rgb
data = np.dstack([np.flipud(rgb.dimension_values(d, flat=False))
for d in rgb.vdims])
else:
data = image.dimension_val... |
Produces matplotlib Path codes for exterior and interior rings of a polygon geometry. | def ring_coding(array):
"""
Produces matplotlib Path codes for exterior and interior rings
of a polygon geometry.
"""
# The codes will be all "LINETO" commands, except for "MOVETO"s at the
# beginning of each subpath
n = len(array)
codes = np.ones(n, dtype=Path.code_type) * Path.LINETO
... |
Converts Polygons into list of lists of matplotlib. patches. PathPatch objects including any specified holes. Each list represents one ( multi - ) polygon. | def polygons_to_path_patches(element):
"""
Converts Polygons into list of lists of matplotlib.patches.PathPatch
objects including any specified holes. Each list represents one
(multi-)polygon.
"""
paths = element.split(datatype='array', dimensions=element.kdims)
has_holes = isinstance(elemen... |
Returns potential Link or Stream sources. | def link_sources(self):
"Returns potential Link or Stream sources."
if isinstance(self, GenericOverlayPlot):
zorders = []
elif self.batched:
zorders = list(range(self.zorder, self.zorder+len(self.hmap.last)))
else:
zorders = [self.zorder]
if i... |
Initializes any callbacks for streams which have defined the plotted object as a source. | def _construct_callbacks(self):
"""
Initializes any callbacks for streams which have defined
the plotted object as a source.
"""
cb_classes = set()
registry = list(Stream.registry.items())
callbacks = Stream._callbacks['bokeh']
for source in self.link_sour... |
Pushes updated plot data via the Comm. | def push(self):
"""
Pushes updated plot data via the Comm.
"""
if self.renderer.mode == 'server':
return
if self.comm is None:
raise Exception('Renderer does not have a comm.')
if self._root and 'embedded' in self._root.tags:
# Allows ... |
Sets the root model on all subplots. | def set_root(self, root):
"""
Sets the root model on all subplots.
"""
if root is None:
return
for plot in self.traverse(lambda x: x):
plot._root = root |
Initializes a data source to be passed into the bokeh glyph. | def _init_datasource(self, data):
"""
Initializes a data source to be passed into the bokeh glyph.
"""
data = self._postprocess_data(data)
return ColumnDataSource(data=data) |
Applies necessary type transformation to the data before it is set on a ColumnDataSource. | def _postprocess_data(self, data):
"""
Applies necessary type transformation to the data before
it is set on a ColumnDataSource.
"""
new_data = {}
for k, values in data.items():
values = decode_bytes(values) # Bytes need decoding to strings
# Cert... |
Update datasource with data for a new frame. | def _update_datasource(self, source, data):
"""
Update datasource with data for a new frame.
"""
if not self.document:
return
data = self._postprocess_data(data)
empty = all(len(v) == 0 for v in data.values())
if (self.streaming and self.streaming[0].... |
Iterates over all subplots and updates existing CustomJS callbacks with models that were replaced when compositing subplots into a CompositePlot and sets the plot id to match the root level bokeh model. | def _update_callbacks(self, plot):
"""
Iterates over all subplots and updates existing CustomJS
callbacks with models that were replaced when compositing
subplots into a CompositePlot and sets the plot id to match
the root level bokeh model.
"""
subplots = self.tr... |
Cleans up references to the plot after the plot has been deleted. Traverses through all plots cleaning up Callbacks and Stream subscribers. | def cleanup(self):
"""
Cleans up references to the plot after the plot has been
deleted. Traverses through all plots cleaning up Callbacks and
Stream subscribers.
"""
plots = self.traverse(lambda x: x, [BokehPlot])
for plot in plots:
if not isinstance(... |
Converts integer fontsizes to a string specifying fontsize in pt. | def _fontsize(self, key, label='fontsize', common=True):
"""
Converts integer fontsizes to a string specifying
fontsize in pt.
"""
size = super(BokehPlot, self)._fontsize(key, label, common)
return {k: v if isinstance(v, basestring) else '%spt' % v
for k, ... |
Syncs data sources between Elements which draw data from the same object. | def sync_sources(self):
"""
Syncs data sources between Elements, which draw data
from the same object.
"""
get_sources = lambda x: (id(x.current_frame.data), x)
filter_fn = lambda x: (x.shared_datasource and x.current_frame is not None and
n... |
Should perform any linking required to update titles when dimensioned streams change. | def _link_dimensioned_streams(self):
"""
Should perform any linking required to update titles when dimensioned
streams change.
"""
streams = [s for s in self.streams if any(k in self.dimensions for k in s.contents)]
for s in streams:
s.add_subscriber(self._str... |
Update the internal state of the Plot to represent the given key tuple ( where integers represent frames ). Returns this state. | def update_frame(self, key, ranges=None):
"""
Update the internal state of the Plot to represent the given
key tuple (where integers represent frames). Returns this
state.
"""
ranges = self.compute_ranges(self.layout, key, ranges)
for coord in self.layout.keys(ful... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.