INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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. The level integer is the number of matching components. Higher values indicate a stronger 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. Note: This is supplied for advanced users who know which additional style keywords are appropriate for the correspon...
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. Only useful when invalid keywords generate exceptions instead of skipping ...
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. The id_mapping return value is a list mapping the ids that ...
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: >>> options={'Curve':{'style':dict(color='b')}} >>> style={'Curve':{'linewidth':10 }} >>> merged = StoreOptions.merge_options(['style'], options, style=style) >>> s...
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. See holoviews.core.o...
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. The options specification is a dictionary containing the target for customization as a {type}.{group}.{label} keys. An example of such a key is 'Image' which would customize all...
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. 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 setting Returns ------- valid: boolean or N...
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. Arguments --------- style: dict Dictionary of styles and values group: str Group within the styles to filter for other_groups: list ...
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 ...
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
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 !=...
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...
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, num=0): """ 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 subplot...
Computes an empty grid to position the plots on by expanding any AdjointLayouts into multiple rows and columns.
def _compute_grid(self): """ Computes an empty grid to position the plots on by expanding any AdjointLayouts into multiple rows and columns. """ widths = [] for c in range(self.cols): c_widths = [] for r in range(self.rows): subplot...
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 r, c in self.coords: ...
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, plots=[]): """ 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 styl...
Given a HoloViews Viewable return a corresponding plot instance. Allows supplying a document attach the plot to, useful when combining the bokeh model with another plot.
def get_plot(self_or_cls, obj, doc=None, renderer=None, **kwargs): """ Given a HoloViews Viewable return a corresponding plot instance. Allows supplying a document attach the plot to, useful when combining the bokeh model with another plot. """ if doc is None: ...
Creates a bokeh app from a HoloViews object or plot. By default simply attaches the plot to bokeh's curdoc and returns the Document, if show option is supplied creates an Application instance and displays it either in a browser window or inline if notebook extension has been loaded. Usi...
def app(self_or_cls, plot, show=False, new_window=False, websocket_origin=None, port=0): """ Creates a bokeh app from a HoloViews object or plot. By default simply attaches the plot to bokeh's curdoc and returns the Document, if show option is supplied creates an Application inst...
Get a bokeh Document with the plot attached. May supply an existing doc, otherwise bokeh.io.curdoc() is used to attach the plot to the global document instance.
def server_doc(self_or_cls, obj, doc=None): """ Get a bokeh Document with the plot attached. May supply an existing doc, otherwise bokeh.io.curdoc() is used to attach the plot to the global document instance. """ if not isinstance(obj, (Plot, BokehServerWidgets)): ...
Given a plot instance, an output format and an optional bokeh document, 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='html', doc=None, as_script=False, **kwargs): """ Given a plot instance, an output format and an optional bokeh document, return the corresponding data. If as_script is True, the content will be split in an HTML and a JS component. """ mod...
Returns a json diff required to update an existing plot with the latest plot data.
def diff(self, plot, binary=True): """ Returns a json diff required to update an existing plot with the latest plot data. """ events = list(plot.document._held_events) if not events: return None msg = Protocol("1.0").create("PATCH-DOC", events, use_buf...
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 se...
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 ...
Return the display size associated with a plot before rendering to any particular format. Used to generate appropriate HTML display. Returns a tuple of (width, height) in pixels.
def get_size(self_or_cls, plot): """ Return the display size associated with a plot before rendering to any particular format. Used to generate appropriate HTML display. Returns a tuple of (width, height) in pixels. """ if isinstance(plot, Plot): plot...
Loads the bokeh notebook resources.
def load_nb(cls, inline=True): """ Loads the bokeh notebook resources. """ LOAD_MIME_TYPE = bokeh.io.notebook.LOAD_MIME_TYPE bokeh.io.notebook.LOAD_MIME_TYPE = MIME_TYPES['jlab-hv-load'] load_notebook(hide_banner=True, resources=INLINE if inline else CDN) bokeh.io...
Update the old_opts option dictionary with the options defined in new_opts. Instead of a shallow update as would be performed by calling old_opts.update(new_opts), this updates the dictionaries of all option types separately. Given two dictionaries old_opts = {'a': {'x': 'old', 'y': 'old'}} ...
def merge_option_dicts(old_opts, new_opts): """ Update the old_opts option dictionary with the options defined in new_opts. Instead of a shallow update as would be performed by calling old_opts.update(new_opts), this updates the dictionaries of all option types separately. Given two dictionarie...
Given a collection of Option objects or partial option dictionaries, merge everything to a single dictionary.
def merge_options_to_dict(options): """ Given a collection of Option objects or partial option dictionaries, merge everything to a single dictionary. """ merged_options = {} for obj in options: if isinstance(obj,dict): new_opts = obj else: new_opts = {obj....
Utility to help with the deprecation of the old .opts method signature Returns whether opts.apply_groups should be used (as a bool) and the corresponding options.
def deprecated_opts_signature(args, kwargs): """ Utility to help with the deprecation of the old .opts method signature Returns whether opts.apply_groups should be used (as a bool) and the corresponding options. """ from .options import Options groups = set(Options._option_groups) opts ...
Given an object, return a hash using HashableJSON. This hash is not architecture, Python version or platform independent.
def deephash(obj): """ Given an object, return a hash using HashableJSON. This hash is not architecture, Python version or platform independent. """ try: return hash(json.dumps(obj, cls=HashableJSON, sort_keys=True)) except: return None
Predicate that returns True for custom attributes added to AttrTrees that are not methods, properties or internal attributes. These custom attributes start with a capitalized character when applicable (not applicable to underscore or certain unicode characters)
def tree_attribute(identifier): """ Predicate that returns True for custom attributes added to AttrTrees that are not methods, properties or internal attributes. These custom attributes start with a capitalized character when applicable (not applicable to underscore or certain unicode characters) ...
Returns an ArgSpec object for functions, staticmethods, instance methods, classmethods and partials. Note that the args list for instance and class methods are those as seen by the user. In other words, the first argument which is conventionally called 'self' or 'cls' is omitted in these cases.
def argspec(callable_obj): """ Returns an ArgSpec object for functions, staticmethods, instance methods, classmethods and partials. Note that the args list for instance and class methods are those as seen by the user. In other words, the first argument which is conventionally called 'self' or '...
Utility used by DynamicMap to ensure the supplied callback has an appropriate signature. If validation succeeds, returns a list of strings to be zipped with the positional arguments i.e kdim values. The zipped values can then be merged with the stream values to pass everything to the Callable as ke...
def validate_dynamic_argspec(callback, kdims, streams): """ Utility used by DynamicMap to ensure the supplied callback has an appropriate signature. If validation succeeds, returns a list of strings to be zipped with the positional arguments i.e kdim values. The zipped values can then be merged...
Attempt to return a meaningful name identifying a callable or generator
def callable_name(callable_obj): """ Attempt to return a meaningful name identifying a callable or generator """ try: if (isinstance(callable_obj, type) and issubclass(callable_obj, param.ParameterizedFunction)): return callable_obj.__name__ elif (isinstance(calla...
Helper function to pad a __getitem__ key with the right number of empty slices (i.e :) when the key contains an Ellipsis (...). If the vdim_selection flag is true, check if the end of the key contains strings or Dimension objects in obj. If so, extra padding will not be applied for the value dimensions...
def process_ellipses(obj, key, vdim_selection=False): """ Helper function to pad a __getitem__ key with the right number of empty slices (i.e :) when the key contains an Ellipsis (...). If the vdim_selection flag is true, check if the end of the key contains strings or Dimension objects in obj. If ...
Turns a string such as 'capital delta' into the shortened, capitalized version, in this case simply 'Delta'. Used as a transform in sanitize_identifier.
def capitalize_unicode_name(s): """ Turns a string such as 'capital delta' into the shortened, capitalized version, in this case simply 'Delta'. Used as a transform in sanitize_identifier. """ index = s.find('capital') if index == -1: return s tail = s[index:].replace('capital', '').stri...
Converts arraylike objects to NumPy ndarray types. Errors if object is not arraylike and strict option is enabled.
def asarray(arraylike, strict=True): """ Converts arraylike objects to NumPy ndarray types. Errors if object is not arraylike and strict option is enabled. """ if isinstance(arraylike, np.ndarray): return arraylike elif isinstance(arraylike, list): return np.asarray(arraylike, dt...
Checks if the value is a NaT. Should only be called on datetimelike objects.
def isnat(val): """ Checks if the value is a NaT. Should only be called on datetimelike objects. """ if (isinstance(val, (np.datetime64, np.timedelta64)) or (isinstance(val, np.ndarray) and val.dtype.kind == 'M')): if numpy_version >= '1.13': return np.isnat(val) else...
Helper function to determine if scalar or array value is finite extending np.isfinite with support for None, string, datetime types.
def isfinite(val): """ Helper function to determine if scalar or array value is finite extending np.isfinite with support for None, string, datetime types. """ if not np.isscalar(val): val = asarray(val, strict=False) if val is None: return False elif isinstance(val, np.ndar...
Whether the array or scalar is recognized datetime type.
def isdatetime(value): """ Whether the array or scalar is recognized datetime type. """ if isinstance(value, np.ndarray): return (value.dtype.kind == "M" or (value.dtype.kind == "O" and len(value) and isinstance(value[0], datetime_types))) else: retur...
Takes (a1, a2) and (b1, b2) as input and returns (np.nanmin(a1, b1), np.nanmax(a2, b2)). Used to calculate min and max values of a number of items.
def find_minmax(lims, olims): """ Takes (a1, a2) and (b1, b2) as input and returns (np.nanmin(a1, b1), np.nanmax(a2, b2)). Used to calculate min and max values of a number of items. """ try: limzip = zip(list(lims), list(olims), [np.nanmin, np.nanmax]) limits = tuple([float(fn([l...
Safely finds either the numerical min and max of a set of values, falling back to the first and the last value in the sorted list of values.
def find_range(values, soft_range=[]): """ Safely finds either the numerical min and max of a set of values, falling back to the first and the last value in the sorted list of values. """ try: values = np.array(values) values = np.squeeze(values) if len(values.shape) > 1 else val...
Computes the maximal lower and upper bounds from a list bounds. Args: ranges (list of tuples): A list of range tuples combined (boolean, optional): Whether to combine bounds Whether range should be computed on lower and upper bound independently or both at once Returns: ...
def max_range(ranges, combined=True): """ Computes the maximal lower and upper bounds from a list bounds. Args: ranges (list of tuples): A list of range tuples combined (boolean, optional): Whether to combine bounds Whether range should be computed on lower and upper bound ...
Pads the range by a fraction of the interval
def range_pad(lower, upper, padding=None, log=False): """ Pads the range by a fraction of the interval """ if padding is not None and not isinstance(padding, tuple): padding = (padding, padding) if is_number(lower) and is_number(upper) and padding is not None: if not isinstance(lower...
Computes the range along a dimension by combining the data range with the Dimension soft_range and range.
def dimension_range(lower, upper, hard_range, soft_range, padding=None, log=False): """ Computes the range along a dimension by combining the data range with the Dimension soft_range and range. """ lower, upper = range_pad(lower, upper, padding, log) lower = max_range([(lower, None), (soft_range...
Computes the maximal extent in 2D and 3D space from list of 4-tuples or 6-tuples. If zrange is enabled all extents are converted to 6-tuples to compute x-, y- and z-limits.
def max_extents(extents, zrange=False): """ Computes the maximal extent in 2D and 3D space from list of 4-tuples or 6-tuples. If zrange is enabled all extents are converted to 6-tuples to compute x-, y- and z-limits. """ if zrange: num = 6 inds = [(0, 3), (1, 4), (2, 5)] ...
Generates alphanumeric labels of form A-Z, AA-ZZ etc.
def int_to_alpha(n, upper=True): "Generates alphanumeric labels of form A-Z, AA-ZZ etc." casenum = 65 if upper else 97 label = '' count= 0 if n == 0: return str(chr(n + casenum)) while n >= 0: mod, div = n % 26, n for _ in range(count): div //= 26 div %= 26 ...
Returns an iterator containing all non-duplicate elements in the input sequence.
def unique_iterator(seq): """ Returns an iterator containing all non-duplicate elements in the input sequence. """ seen = set() for item in seq: if item not in seen: seen.add(item) yield item
Returns an array of unique values in the input order. Args: arr (np.ndarray or list): The array to compute unique values on Returns: A new array of unique values
def unique_array(arr): """ Returns an array of unique values in the input order. Args: arr (np.ndarray or list): The array to compute unique values on Returns: A new array of unique values """ if not len(arr): return np.asarray(arr) elif pd: if isinstance(arr,...
Matches the group.label specification of the supplied element against the supplied specification dictionary returning the value of the best match.
def match_spec(element, specification): """ Matches the group.label specification of the supplied element against the supplied specification dictionary returning the value of the best match. """ match_tuple = () match = specification.get((), {}) for spec in [type(element).__name__, ...
Merges lists of fully or partially overlapping dimensions by merging their values. >>> from holoviews import Dimension >>> dim_list = [[Dimension('A', values=[1, 2, 3]), Dimension('B')], ... [Dimension('A', values=[2, 3, 4])]] >>> dimensions = merge_dimensions(dim_list) >>> dimensio...
def merge_dimensions(dimensions_list): """ Merges lists of fully or partially overlapping dimensions by merging their values. >>> from holoviews import Dimension >>> dim_list = [[Dimension('A', values=[1, 2, 3]), Dimension('B')], ... [Dimension('A', values=[2, 3, 4])]] >>> dimen...
Sorts data by key using usual Python tuple sorting semantics or sorts in categorical order for any categorical Dimensions.
def dimension_sort(odict, kdims, vdims, key_index): """ Sorts data by key using usual Python tuple sorting semantics or sorts in categorical order for any categorical Dimensions. """ sortkws = {} ndims = len(kdims) dimensions = kdims+vdims indexes = [(dimensions[i], int(i not in range(nd...
Stackless topological sorting. graph = { 3: [1], 5: [3], 4: [2], 6: [4], } sort_topologically(graph) [[1, 2], [3, 4], [5, 6]]
def sort_topologically(graph): """ Stackless topological sorting. graph = { 3: [1], 5: [3], 4: [2], 6: [4], } sort_topologically(graph) [[1, 2], [3, 4], [5, 6]] """ levels_by_name = {} names_by_level = defaultdict(list) def add_level_to_name(nam...
Return True if the directed graph g has a cycle. The directed graph should be represented as a dictionary mapping of edges for each node.
def is_cyclic(graph): """ Return True if the directed graph g has a cycle. The directed graph should be represented as a dictionary mapping of edges for each node. """ path = set() def visit(vertex): path.add(vertex) for neighbour in graph.get(vertex, ()): if neighbo...
Return True if graph contains only one to one mappings. The directed graph should be represented as a dictionary mapping of edges for each node. Nodes should be passed a simple list.
def one_to_one(graph, nodes): """ Return True if graph contains only one to one mappings. The directed graph should be represented as a dictionary mapping of edges for each node. Nodes should be passed a simple list. """ edges = itertools.chain.from_iterable(graph.values()) return len(graph)...
Gets the type.group.label + key spec from an Element in an Overlay.
def get_overlay_spec(o, k, v): """ Gets the type.group.label + key spec from an Element in an Overlay. """ k = wrap_tuple(k) return ((type(v).__name__, v.group, v.label) + k if len(o.kdims) else (type(v).__name__,) + k)
Find a global ordering for layers in a HoloMap of CompositeOverlay types.
def layer_sort(hmap): """ Find a global ordering for layers in a HoloMap of CompositeOverlay types. """ orderings = {} for o in hmap: okeys = [get_overlay_spec(o, k, v) for k, v in o.data.items()] if len(okeys) == 1 and not okeys[0] in orderings: orderings[okeys[0]] = [] els...
Splits a global ordering of Layers into groups based on a slice of the spec. The grouping behavior can be modified by changing the length of spec the entries are grouped by.
def layer_groups(ordering, length=2): """ Splits a global ordering of Layers into groups based on a slice of the spec. The grouping behavior can be modified by changing the length of spec the entries are grouped by. """ group_orderings = defaultdict(list) for el in ordering: group_orderings[...
Given a list of key tuples to select, groups them into sensible chunks to avoid duplicating indexing operations.
def group_select(selects, length=None, depth=None): """ Given a list of key tuples to select, groups them into sensible chunks to avoid duplicating indexing operations. """ if length == None and depth == None: length = depth = len(selects[0]) getter = operator.itemgetter(depth-length) ...