INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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
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.
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
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 other entries.
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.
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.
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.
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.
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.
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
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)
Applies the applicable formatter to the value.
def pprint_value(self, value): """Applies the applicable formatter to the value. Args: value: Dimension value to format Returns: Formatted dimension value """ own_type = type(value) if self.type is None else self.type formatter = (self.value_form...
Pretty print the dimension value and unit.
def pprint_value_string(self, value): """Pretty print the dimension value and unit. Args: value: Dimension value to format Returns: Formatted dimension value string with unit """ unit = '' if self.unit is None else ' ' + bytes_to_unicode(self.unit) ...
Handles tracking and cleanup of custom ids.
def id(self, opts_id): """Handles tracking and cleanup of custom ids.""" old_id = self._id self._id = opts_id if old_id is not None: cleanup_custom_options(old_id) if opts_id is not None and opts_id != old_id: if opts_id not in Store._weakrefs: ...
Clones the object overriding data and parameters.
def clone(self, data=None, shared_data=True, new_type=None, link=True, *args, **overrides): """Clones the object, overriding data and parameters. Args: data: New data replacing the existing data shared_data (bool, optional): Whether to use existing data ...
Clone object and apply new group and/ or label.
def relabel(self, label=None, group=None, depth=0): """Clone object and apply new group and/or label. Applies relabeling to children up to the supplied depth. Args: label (str, optional): New label to apply to returned object group (str, optional): New group to apply to...
Whether the spec applies to this object.
def matches(self, spec): """Whether the spec applies to this object. Args: spec: A function, spec or type to check for a match * A 'type[[.group].label]' string which is compared against the type, group and label of this object * A function ...
Traverses object returning matching items
def traverse(self, fn=None, specs=None, full_breadth=True): """Traverses object returning matching items Traverses the set of children of the object, collecting the all objects matching the defined specs. Each object can be processed with the supplied function. Args: ...
Map a function to all objects matching the specs
def map(self, map_fn, specs=None, clone=True): """Map a function to all objects matching the specs Recursively replaces elements using a map function when the specs apply, by default applies to all objects, e.g. to apply the function to all contained Curve objects: dmap.map...
Validates key dimension input
def _valid_dimensions(self, dimensions): """Validates key dimension input Returns kdims if no dimensions are specified""" if dimensions is None: dimensions = self.kdims elif not isinstance(dimensions, list): dimensions = [dimensions] valid_dimensions = [...
Lists the available dimensions on the object
def dimensions(self, selection='all', label=False): """Lists the available dimensions on the object Provides convenient access to Dimensions on nested Dimensioned objects. Dimensions can be selected by their type, i.e. 'key' or 'value' dimensions. By default 'all' dimensions are ...
Get a Dimension object by name or index.
def get_dimension(self, dimension, default=None, strict=False): """Get a Dimension object by name or index. Args: dimension: Dimension to look up by name or integer index default (optional): Value returned if Dimension not found strict (bool, optional): Raise a KeyEr...
Get the index of the requested dimension.
def get_dimension_index(self, dimension): """Get the index of the requested dimension. Args: dimension: Dimension to look up by name or by index Returns: Integer index of the requested dimension """ if isinstance(dimension, int): if (dimensio...
Get the type of the requested dimension.
def get_dimension_type(self, dim): """Get the type of the requested dimension. Type is determined by Dimension.type attribute or common type of the dimension values, otherwise None. Args: dimension: Dimension to look up by name or by index Returns: Decl...
Applies selection by dimension name
def select(self, selection_specs=None, **kwargs): """Applies selection by dimension name Applies a selection along the dimensions of the object using keyword arguments. The selection may be narrowed to certain objects using selection_specs. For container objects the selection wi...
Return the values along the requested dimension.
def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, beh...
Return the lower and upper bounds of values along dimension.
def range(self, dimension, data_range=True, dimension_range=True): """Return the lower and upper bounds of values along dimension. Args: dimension: The dimension to compute the range on. data_range (bool): Compute range from data values dimension_range (bool): Includ...
Applies simplified option definition returning a new object.
def options(self, *args, **kwargs): """Applies simplified option definition returning a new object. Applies options on an object or nested group of objects in a flat format returning a new object with the options applied. If the options are to be set directly on the object a sim...
Deprecated method to construct tree from list of objects
def from_values(cls, vals): "Deprecated method to construct tree from list of objects" if util.config.future_deprecations: param.main.param.warning("%s.from_values is deprecated, the %s " "constructor may now be used directly.") return cls(items=c...
Processes list of items assigning unique paths to each.
def _process_items(cls, vals): "Processes list of items assigning unique paths to each." if type(vals) is cls: return vals.data elif not isinstance(vals, (list, tuple)): vals = [vals] items = [] counts = defaultdict(lambda: 1) cls._unpack_paths(val...
Deduplicates assigned paths by incrementing numbering
def _deduplicate_items(cls, items): "Deduplicates assigned paths by incrementing numbering" counter = Counter([path[:i] for path, _ in items for i in range(1, len(path)+1)]) if sum(counter.values()) == len(counter): return items new_items = [] counts = defaultdict(la...
Recursively unpacks lists and ViewableTree - like objects accumulating into the supplied list of items.
def _unpack_paths(cls, objs, items, counts): """ Recursively unpacks lists and ViewableTree-like objects, accumulating into the supplied list of items. """ if type(objs) is cls: objs = objs.items() for item in objs: path, obj = item if isinstance(i...
Return the values along the requested dimension.
def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Concatenates values on all nodes with requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expa...
Deprecated method to apply new group to items.
def regroup(self, group): """Deprecated method to apply new group to items. Equivalent functionality possible using: ViewableTree(tree.relabel(group='Group').values()) """ if util.config.future_deprecations: self.param.warning('%s.regroup is deprecated, use rela...
Applies all the axis settings before the axis or figure is returned. Only plots with zorder 0 get to apply their settings.
def _finalize_axis(self, key, element=None, title=None, dimensions=None, ranges=None, xticks=None, yticks=None, zticks=None, xlabel=None, ylabel=None, zlabel=None): """ Applies all the axis settings before the axis or figure is returned. Only plots with zorder 0 get to app...
Finalizes the ticks on the axes based on the supplied ticks and Elements. Sets the axes position as well as tick positions labels and fontsize.
def _finalize_ticks(self, axis, dimensions, xticks, yticks, zticks): """ Finalizes the ticks on the axes based on the supplied ticks and Elements. Sets the axes position as well as tick positions, labels and fontsize. """ ndims = len(dimensions) if dimensions else 0 ...
Sets the labels of the axes using the supplied list of dimensions. Optionally explicit labels may be supplied to override the dimension label.
def _set_labels(self, axes, dimensions, xlabel=None, ylabel=None, zlabel=None): """ Sets the labels of the axes using the supplied list of dimensions. Optionally explicit labels may be supplied to override the dimension label. """ xlabel, ylabel, zlabel = self._get_axis_l...
Set axis formatter based on dimension formatter.
def _set_axis_formatter(self, axis, dim, formatter): """ Set axis formatter based on dimension formatter. """ if isinstance(dim, list): dim = dim[0] if formatter is not None: pass elif dim.value_format: formatter = dim.value_format elif dim...
Computes the aspect ratio of the plot
def get_aspect(self, xspan, yspan): """ Computes the aspect ratio of the plot """ if isinstance(self.aspect, (int, float)): return self.aspect elif self.aspect == 'square': return 1 elif self.aspect == 'equal': return xspan/yspan ...
Set the aspect on the axes based on the aspect setting.
def _set_aspect(self, axes, aspect): """ Set the aspect on the axes based on the aspect setting. """ if ((isinstance(aspect, util.basestring) and aspect != 'square') or self.data_aspect): data_ratio = self.data_aspect or aspect else: (x0, x1), ...
Compute extents for current view and apply as axis limits
def _set_axis_limits(self, axis, view, subplots, ranges): """ Compute extents for current view and apply as axis limits """ # Extents extents = self.get_extents(view, ranges) if not extents or self.overlaid: axis.autoscale_view(scalex=True, scaley=True) ...
Set the position and visibility of the xaxis or yaxis by supplying the axes object the axis to set i. e. x or y and an option to specify the position and visibility of the axis. The option may be None bare or positional i. e. left and right for the yaxis and top and bottom for the xaxis. May also combine positional and...
def _set_axis_position(self, axes, axis, option): """ Set the position and visibility of the xaxis or yaxis by supplying the axes object, the axis to set, i.e. 'x' or 'y' and an option to specify the position and visibility of the axis. The option may be None, 'bare' or positiona...
Allows setting the ticks for a particular axis either with a tuple of ticks a tick locator object an integer number of ticks a list of tuples containing positions and labels or a list of positions. Also supports enabling log ticking if an integer number of ticks is supplied and setting a rotation for the ticks.
def _set_axis_ticks(self, axis, ticks, log=False, rotation=0): """ Allows setting the ticks for a particular axis either with a tuple of ticks, a tick locator object, an integer number of ticks, a list of tuples containing positions and labels or a list of positions. Also support...
Set the plot ( s ) to the given frame number. Operates by manipulating the matplotlib objects held in the self. _handles dictionary.
def update_frame(self, key, ranges=None, element=None): """ Set the plot(s) to the given frame number. Operates by manipulating the matplotlib objects held in the self._handles dictionary. If n is greater than the number of available frames, update using the last availa...
Initializes the artist based on the plot method declared on the plot.
def init_artists(self, ax, plot_args, plot_kwargs): """ Initializes the artist based on the plot method declared on the plot. """ plot_method = self._plot_methods.get('batched' if self.batched else 'single') plot_fn = getattr(ax, plot_method) artist = plot_fn(*plo...
Update the elements of the plot.
def update_handles(self, key, axis, element, ranges, style): """ Update the elements of the plot. """ self.teardown_handles() plot_data, plot_kwargs, axis_kwargs = self.get_data(element, ranges, style) with abbreviated_exception(): handles = self.init_artists...
Returns valid color normalization kwargs to be passed to matplotlib plot function.
def _norm_kwargs(self, element, ranges, opts, vdim, values=None, prefix=''): """ Returns valid color normalization kwargs to be passed to matplotlib plot function. """ dim_name = dim_range_key(vdim) if values is None: if isinstance(vdim, dim): ...
Accumulate the legend handles and labels for all subplots and set up the legend
def _adjust_legend(self, overlay, axis): """ Accumulate the legend handles and labels for all subplots and set up the legend """ legend_data = [] dimensions = overlay.kdims title = ', '.join([d.name for d in dimensions]) for key, subplot in self.subplots.i...
Helper method that returns a list of elements that match the given path pattern of form { type }. { group }. { label }.
def search(cls, element, pattern): """ Helper method that returns a list of elements that match the given path pattern of form {type}.{group}.{label}. The input may be a Layout, an Overlay type or a single Element. """ if isinstance(element, Layout): ...
Returns a label if all the elements of an overlay agree on a consistent label otherwise returns the default label.
def get_overlay_label(cls, overlay, default_label=''): """ Returns a label if all the elements of an overlay agree on a consistent label, otherwise returns the default label. """ if all(el.label==overlay.get(0).label for el in overlay): return overlay.get(0).label ...
Returns the extents if all the elements of an overlay agree on a consistent extents otherwise raises an exception.
def get_overlay_bounds(cls, overlay): """ Returns the extents if all the elements of an overlay agree on a consistent extents, otherwise raises an exception. """ if all(el.bounds==overlay.get(0).bounds for el in overlay): return overlay.get(0).bounds else: ...
Applies the operation to the element executing any pre - and post - processor hooks if defined.
def _apply(self, element, key=None): """ Applies the operation to the element, executing any pre- and post-processor hooks if defined. """ kwargs = {} for hook in self._preprocess_hooks: kwargs.update(hook(self, element)) ret = self._process(element, k...
The process_element method allows a single element to be operated on given an externally supplied key.
def process_element(self, element, key, **params): """ The process_element method allows a single element to be operated on given an externally supplied key. """ self.p = param.ParamOverrides(self, params) return self._apply(element, key)
Finds all common dimension keys in the object including subsets of dimensions. If there are is no common subset of dimensions None is returned.
def uniform(obj): """ Finds all common dimension keys in the object including subsets of dimensions. If there are is no common subset of dimensions, None is returned. """ from .spaces import HoloMap dim_groups = obj.traverse(lambda x: tuple(x.kdims), (HoloMap,))...
Finds all common dimension keys in the object including subsets of dimensions. If there are is no common subset of dimensions None is returned.
def unique_dimkeys(obj, default_dim='Frame'): """ Finds all common dimension keys in the object including subsets of dimensions. If there are is no common subset of dimensions, None is returned. Returns the list of dimensions followed by the list of unique keys. """ from .ndmapping impo...
Iterates over dimension values in keys taking two sets of dimension values at a time to determine whether two consecutive dimensions have a one - to - many relationship. If they do a mapping between the first and second dimension values is returned. Returns a list of n - 1 mappings between consecutive dimensions.
def hierarchical(keys): """ Iterates over dimension values in keys, taking two sets of dimension values at a time to determine whether two consecutive dimensions have a one-to-many relationship. If they do a mapping between the first and second dimension values is returned. Returns a list of n-1...
>>> GridInterface. _infer_interval_breaks ( np. arange ( 5 )) array ( [ - 0. 5 0. 5 1. 5 2. 5 3. 5 4. 5 ] ) >>> GridInterface. _infer_interval_breaks ( [[ 0 1 ] [ 3 4 ]] axis = 1 ) array ( [[ - 0. 5 0. 5 1. 5 ] [ 2. 5 3. 5 4. 5 ]] )
def _infer_interval_breaks(cls, coord, axis=0): """ >>> GridInterface._infer_interval_breaks(np.arange(5)) array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]) >>> GridInterface._infer_interval_breaks([[0, 1], [3, 4]], axis=1) array([[-0.5, 0.5, 1.5], [ 2.5, 3.5, 4.5]])...
Returns the coordinates along a dimension. Ordered ensures coordinates are in ascending order and expanded creates ND - array matching the dimensionality of the dataset.
def coords(cls, dataset, dim, ordered=False, expanded=False, edges=False): """ Returns the coordinates along a dimension. Ordered ensures coordinates are in ascending order and expanded creates ND-array matching the dimensionality of the dataset. """ dim = dataset.get_di...
Canonicalize takes an array of values as input and reorients and transposes it to match the canonical format expected by plotting functions. In certain cases the dimensions defined via the kdims of an Element may not match the dimensions of the underlying data. A set of data_coords may be passed in to define the dimens...
def canonicalize(cls, dataset, data, data_coords=None, virtual_coords=[]): """ Canonicalize takes an array of values as input and reorients and transposes it to match the canonical format expected by plotting functions. In certain cases the dimensions defined via the kdims of an ...
Samples the gridded data into dataset of samples.
def sample(cls, dataset, samples=[]): """ Samples the gridded data into dataset of samples. """ ndims = dataset.ndims dimensions = dataset.dimensions(label='name') arrays = [dataset.data[vdim.name] for vdim in dataset.vdims] data = defaultdict(list) for s...
Update datasource with data for a new frame.
def _update_datasource(self, source, data): """ Update datasource with data for a new frame. """ if isinstance(source, ColumnDataSource): if self.handles['static_source']: source.trigger('data', source.data, data) else: source.data....
Replace edge renderer with filled renderer
def _init_filled_edges(self, renderer, properties, edge_mapping): "Replace edge renderer with filled renderer" glyph_model = Patches if self.filled else Bezier allowed_properties = glyph_model.properties() for glyph_type in ('', 'selection_', 'nonselection_', 'hover_', 'muted_'): ...
Computes the args and kwargs for the GraphRenderer
def _get_graph_properties(self, plot, element, data, mapping, ranges, style): "Computes the args and kwargs for the GraphRenderer" sources = [] properties, mappings = {}, {} for key in ('scatter_1', self.edge_glyph): gdata = data.pop(key, {}) group_style = dict(s...
Reorders renderers based on the defined draw order
def _reorder_renderers(self, plot, renderer, mapping): "Reorders renderers based on the defined draw order" renderers = dict({r: self.handles[r+'_glyph_renderer'] for r in mapping}, graph=renderer) other = [r for r in plot.renderers if r not in renderers.values()] ...
A Chord plot is always drawn on a unit circle.
def get_extents(self, element, ranges, range_type='combined'): """ A Chord plot is always drawn on a unit circle. """ xdim, ydim = element.nodes.kdims[:2] if range_type not in ('combined', 'data', 'extents'): return xdim.range[0], ydim.range[0], xdim.range[1], ydim.ra...
String sanitizer to avoid problematic characters in filenames.
def sanitizer(name, replacements=[(':','_'), ('/','_'), ('\\','_')]): """ String sanitizer to avoid problematic characters in filenames. """ for old,new in replacements: name = name.replace(old,new) return name