INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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. Using the new_window option the app m...
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 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 ...
Return the display size associated with a plot before rendering to any particular format. Used to generate appropriate HTML display.
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.
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
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.
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.
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.
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 (... ).
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.
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.
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.
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.
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) ...
Takes the output of group_select selecting subgroups iteratively avoiding duplicating select operations.
def iterative_select(obj, dimensions, selects, depth=None): """ Takes the output of group_select selecting subgroups iteratively, avoiding duplicating select operations. """ ndims = len(dimensions) depth = depth if depth is not None else ndims items = [] if isinstance(selects, dict): ...
Find a file given folder and filename. If the filename can be resolved directly returns otherwise walks the supplied folder.
def find_file(folder, filename): """ Find a file given folder and filename. If the filename can be resolved directly returns otherwise walks the supplied folder. """ matches = [] if os.path.isabs(filename) and os.path.isfile(filename): return filename for root, _, filenames in os.wal...
Checks whether the supplied data is of DataFrame type.
def is_dataframe(data): """ Checks whether the supplied data is of DataFrame type. """ dd = None if 'dask' in sys.modules and 'pandas' in sys.modules: import dask.dataframe as dd return((pd is not None and isinstance(data, pd.DataFrame)) or (dd is not None and isinstance(data, ...
Checks whether the supplied data is of Series type.
def is_series(data): """ Checks whether the supplied data is of Series type. """ dd = None if 'dask' in sys.modules: import dask.dataframe as dd return((pd is not None and isinstance(data, pd.Series)) or (dd is not None and isinstance(data, dd.Series)))
Whether the object is a method on a parameterized object.
def is_param_method(obj, has_deps=False): """Whether the object is a method on a parameterized object. Args: obj: Object to check has_deps (boolean, optional): Check for dependencies Whether to also check whether the method has been annotated with param.depends Returns: ...
Temporarily set parameters on Parameterized object to constant = False.
def disable_constant(parameterized): """ Temporarily set parameters on Parameterized object to constant=False. """ params = parameterized.params().values() constants = [p.constant for p in params] for p in params: p.constant = False try: yield except: raise ...
Function to get the first non - auxiliary object label attribute from an NdMapping.
def get_ndmapping_label(ndmapping, attr): """ Function to get the first non-auxiliary object label attribute from an NdMapping. """ label = None els = itervalues(ndmapping.data) while label is None: try: el = next(els) except StopIteration: return None...
Return a complete dictionary mapping between stream parameter names to their applicable renames excluding parameters listed in exclude_params.
def stream_name_mapping(stream, exclude_params=['name'], reverse=False): """ Return a complete dictionary mapping between stream parameter names to their applicable renames, excluding parameters listed in exclude_params. If reverse is True, the mapping is from the renamed strings to the origina...
Given a stream and a kwargs dictionary of parameter values map to the corresponding dictionary where the keys are substituted with the appropriately renamed string.
def rename_stream_kwargs(stream, kwargs, reverse=False): """ Given a stream and a kwargs dictionary of parameter values, map to the corresponding dictionary where the keys are substituted with the appropriately renamed string. If reverse, the output will be a dictionary using the original param...
Given a list of streams return a flat list of parameter name excluding those listed in the exclude list.
def stream_parameters(streams, no_duplicates=True, exclude=['name']): """ Given a list of streams, return a flat list of parameter name, excluding those listed in the exclude list. If no_duplicates is enabled, a KeyError will be raised if there are parameter name clashes across the streams. """...
Return a list of stream parameters that have not been associated with any of the key dimensions.
def dimensionless_contents(streams, kdims, no_duplicates=True): """ Return a list of stream parameters that have not been associated with any of the key dimensions. """ names = stream_parameters(streams, no_duplicates) return [name for name in names if name not in kdims]
Return a list of dimensions that have not been associated with any streams.
def unbound_dimensions(streams, kdims, no_duplicates=True): """ Return a list of dimensions that have not been associated with any streams. """ params = stream_parameters(streams, no_duplicates) return [d for d in kdims if d not in params]
Fills in tuple keys with dimensioned stream values as appropriate.
def wrap_tuple_streams(unwrapped, kdims, streams): """ Fills in tuple keys with dimensioned stream values as appropriate. """ param_groups = [(s.contents.keys(), s) for s in streams] pairs = [(name,s) for (group, s) in param_groups for name in group] substituted = [] for pos,el in enumerate...
Drop any dimensioned streams from the keys and kdims.
def drop_streams(streams, kdims, keys): """ Drop any dimensioned streams from the keys and kdims. """ stream_params = stream_parameters(streams) inds, dims = zip(*[(ind, kdim) for ind, kdim in enumerate(kdims) if kdim not in stream_params]) get = operator.itemgetter(*inds)...
Get value iterator from dictionary for Python 2 and 3
def itervalues(obj): "Get value iterator from dictionary for Python 2 and 3" return iter(obj.values()) if sys.version_info.major == 3 else obj.itervalues()
Get key iterator from dictionary for Python 2 and 3
def iterkeys(obj): "Get key iterator from dictionary for Python 2 and 3" return iter(obj.keys()) if sys.version_info.major == 3 else obj.iterkeys()
Gets a path from an Labelled object or from a tuple of an existing path and a labelled object. The path strings are sanitized and capitalized.
def get_path(item): """ Gets a path from an Labelled object or from a tuple of an existing path and a labelled object. The path strings are sanitized and capitalized. """ sanitizers = [group_sanitizer, label_sanitizer] if isinstance(item, tuple): path, item = item if item.lab...
Given a path a list of existing paths and counts for each of the existing paths.
def make_path_unique(path, counts, new): """ Given a path, a list of existing paths and counts for each of the existing paths. """ added = False while any(path == c[:i] for c in counts for i in range(1, len(c)+1)): count = counts[path] counts[path] += 1 if (not new and le...
Efficient cartesian product of a list of 1D arrays returning the expanded array views for each dimensions. By default arrays are flattened which may be controlled with the flat flag. The array views can be turned into regular arrays with the copy flag.
def cartesian_product(arrays, flat=True, copy=False): """ Efficient cartesian product of a list of 1D arrays returning the expanded array views for each dimensions. By default arrays are flattened, which may be controlled with the flat flag. The array views can be turned into regular arrays with the...
Allows efficiently indexing into a cartesian product without expanding it. The values should be defined as a list of iterables making up the cartesian product and a linear index returning the cross product of the values at the supplied index.
def cross_index(values, index): """ Allows efficiently indexing into a cartesian product without expanding it. The values should be defined as a list of iterables making up the cartesian product and a linear index, returning the cross product of the values at the supplied index. """ lengths ...
Returns the indices of the lexicographical sorting order of the supplied arrays.
def arglexsort(arrays): """ Returns the indices of the lexicographical sorting order of the supplied arrays. """ dtypes = ','.join(array.dtype.str for array in arrays) recarray = np.empty(len(arrays[0]), dtype=dtypes) for i, array in enumerate(arrays): recarray['f%s' % i] = array ...
Given a DynamicMap return all streams that have any dimensioned parameters i. e parameters also listed in the key dimensions.
def dimensioned_streams(dmap): """ Given a DynamicMap return all streams that have any dimensioned parameters i.e parameters also listed in the key dimensions. """ dimensioned = [] for stream in dmap.streams: stream_params = stream_parameters([stream]) if set([str(k) for k in dma...
Expand the coordinates along a dimension of the gridded dataset into an ND - array matching the dimensionality of the dataset.
def expand_grid_coords(dataset, dim): """ Expand the coordinates along a dimension of the gridded dataset into an ND-array matching the dimensionality of the dataset. """ arrays = [dataset.interface.coords(dataset, d.name, True) for d in dataset.kdims] idx = dataset.get_dimensi...
Safely converts NumPy datetime64 to a datetime object.
def dt64_to_dt(dt64): """ Safely converts NumPy datetime64 to a datetime object. """ ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's') return dt.datetime.utcfromtimestamp(ts)
Computes a bounding range and density from a number of samples assumed to be evenly spaced. Density is rounded to machine precision using significant digits reported by sys. float_info. dig.
def bound_range(vals, density, time_unit='us'): """ Computes a bounding range and density from a number of samples assumed to be evenly spaced. Density is rounded to machine precision using significant digits reported by sys.float_info.dig. """ if not len(vals): return(np.nan, np.nan, de...
Validates regular sampling of a 1D array ensuring that the difference in sampling steps is at most rtol times the smallest sampling step. Returns a boolean indicating whether the sampling is regular.
def validate_regular_sampling(values, rtol=10e-6): """ Validates regular sampling of a 1D array ensuring that the difference in sampling steps is at most rtol times the smallest sampling step. Returns a boolean indicating whether the sampling is regular. """ diffs = np.diff(values) return (l...
Computes a grid density given the edges and number of samples. Handles datetime grids correctly by computing timedeltas and computing a density for the given time_unit.
def compute_density(start, end, length, time_unit='us'): """ Computes a grid density given the edges and number of samples. Handles datetime grids correctly by computing timedeltas and computing a density for the given time_unit. """ if isinstance(start, int): start = float(start) if isinsta...
Computes a date range given a start date end date and the number of samples.
def date_range(start, end, length, time_unit='us'): """ Computes a date range given a start date, end date and the number of samples. """ step = (1./compute_density(start, end, length, time_unit)) if pd and isinstance(start, pd.Timestamp): start = start.to_datetime64() step = np.time...
Converts a datetime type to an integer with the supplied time unit.
def dt_to_int(value, time_unit='us'): """ Converts a datetime type to an integer with the supplied time unit. """ if pd: if isinstance(value, pd.Period): value = value.to_timestamp() if isinstance(value, pd.Timestamp): try: value = value.to_datetim...
Converts cftime to timestamp since epoch in milliseconds
def cftime_to_timestamp(date, time_unit='us'): """Converts cftime to timestamp since epoch in milliseconds Non-standard calendars (e.g. Julian or no leap calendars) are converted to standard Gregorian calendar. This can cause extra space to be added for dates that don't exist in the original calend...
Given a set of values returns the indices of each of those values in the source array.
def search_indices(values, source): """ Given a set of values returns the indices of each of those values in the source array. """ orig_indices = source.argsort() return orig_indices[np.searchsorted(source[orig_indices], values)]
Computes edges as midpoints of the bin centers. The first and last boundaries are equidistant from the first and last midpoints respectively.
def compute_edges(edges): """ Computes edges as midpoints of the bin centers. The first and last boundaries are equidistant from the first and last midpoints respectively. """ edges = np.asarray(edges) if edges.dtype.kind == 'i': edges = edges.astype('f') midpoints = (edges[:-1]...
Converts a MIME bundle into HTML.
def mimebundle_to_html(bundle): """ Converts a MIME bundle into HTML. """ if isinstance(bundle, tuple): data, metadata = bundle else: data = bundle html = data.get('text/html', '') if 'application/javascript' in data: js = data['application/javascript'] html +...
Converts a NumPy scalar to a regular python type.
def numpy_scalar_to_python(scalar): """ Converts a NumPy scalar to a regular python type. """ scalar_type = type(scalar) if np.issubclass_(scalar_type, np.float_): return float(scalar) elif np.issubclass_(scalar_type, np.int_): return int(scalar) return scalar
Recursively iterates over type group label and overlay key finding the closest matching spec.
def closest_match(match, specs, depth=0): """ Recursively iterates over type, group, label and overlay key, finding the closest matching spec. """ new_specs = [] match_lengths = [] for i, spec in specs: if spec[0] == match[0]: new_specs.append((i, spec[1:])) else:...
Conveniently add new aliases as keyword arguments. For instance you can add a new alias with add_aliases ( short = Longer string )
def add_aliases(self_or_cls, **kwargs): """ Conveniently add new aliases as keyword arguments. For instance you can add a new alias with add_aliases(short='Longer string') """ self_or_cls.aliases.update({v:k for k,v in kwargs.items()})
Remove a list of aliases.
def remove_aliases(self_or_cls, aliases): """ Remove a list of aliases. """ for k,v in self_or_cls.aliases.items(): if v in aliases: self_or_cls.aliases.pop(k)
Whether or not the identifier will be prefixed. Strings that require the prefix are generally not recommended.
def prefixed(self, identifier, version): """ Whether or not the identifier will be prefixed. Strings that require the prefix are generally not recommended. """ invalid_starting = ['Mn', 'Mc', 'Nd', 'Pc'] if identifier.startswith('_'): return True return((identifi...
Remove diacritics and accents from the input leaving other unicode characters alone.
def remove_diacritics(self_or_cls, identifier): """ Remove diacritics and accents from the input leaving other unicode characters alone.""" chars = '' for c in identifier: replacement = unicodedata.normalize('NFKD', c).encode('ASCII', 'ignore') if replacem...
Given a unicode character c return the shortened unicode name ( as a list of tokens ) by applying the eliminations substitutions and transforms.
def shortened_character_name(self_or_cls, c, eliminations=[], substitutions={}, transforms=[]): """ Given a unicode character c, return the shortened unicode name (as a list of tokens) by applying the eliminations, substitutions and transforms. """ name = unicodedata.name...
Strip underscores to make sure the number is correct after join
def _process_underscores(self, tokens): "Strip underscores to make sure the number is correct after join" groups = [[str(''.join(el))] if b else list(el) for (b,el) in itertools.groupby(tokens, lambda k: k=='_')] flattened = [el for group in groups for el in group] proc...
Accumulate blocks of hex and separate blocks by underscores
def sanitize(self, name, valid_fn): "Accumulate blocks of hex and separate blocks by underscores" invalid = {'\a':'a','\b':'b', '\v':'v','\f':'f','\r':'r'} for cc in filter(lambda el: el in name, invalid.keys()): raise Exception("Please use a raw string or escape control code '\%s'" ...
The set of samples available along a particular dimension.
def values(cls, dataset, dim, expanded=True, flat=True, compute=True): """ The set of samples available along a particular dimension. """ dim_idx = dataset.get_dimension_index(dim) if dim_idx in [0, 1]: l, b, r, t = dataset.bounds.lbrt() dim2, dim1 = datas...
Slice the underlying numpy array in sheet coordinates.
def select(cls, dataset, selection_mask=None, **selection): """ Slice the underlying numpy array in sheet coordinates. """ selection = {k: slice(*sel) if isinstance(sel, tuple) else sel for k, sel in selection.items()} coords = tuple(selection[kd.name] if kd....
Sample the Raster along one or both of its dimensions returning a reduced dimensionality type which is either a ItemTable Curve or Scatter. If two dimension samples and a new_xaxis is provided the sample will be the value of the sampled unit indexed by the value in the new_xaxis tuple.
def sample(cls, dataset, samples=[]): """ Sample the Raster along one or both of its dimensions, returning a reduced dimensionality type, which is either a ItemTable, Curve or Scatter. If two dimension samples and a new_xaxis is provided the sample will be the value of th...
Given a dataset object and data in the appropriate format for the interface return a simple scalar.
def unpack_scalar(cls, dataset, data): """ Given a dataset object and data in the appropriate format for the interface, return a simple scalar. """ if np.isscalar(data) or len(data) != 1: return data key = list(data.keys())[0] if len(data[key]) == 1 a...
Given the real and imaginary parts of a complex number determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations.
def mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ i = 0 c = complex(x,y) z = 0.0j for i in range(max_iters): z = z*z + c ...
Return the lower and upper bounds of values along dimension.
def range(self, dim, data_range=True, dimension_range=True): """Return the lower and upper bounds of values along dimension. Range of the y-dimension includes the symmetric or assymetric error. Args: dimension: The dimension to compute the range on. data_range (...
Property to access the Histogram values provided for backward compatibility
def values(self): "Property to access the Histogram values provided for backward compatibility" if util.config.future_deprecations: self.param.warning('Histogram.values is deprecated in favor of ' 'common dimension_values method.') return self.dimension...
Property to access the Histogram edges provided for backward compatibility
def edges(self): "Property to access the Histogram edges provided for backward compatibility" if util.config.future_deprecations: self.param.warning('Histogram.edges is deprecated in favor of ' 'common dimension_values method.') return self.interface.co...
Stacks an ( Nd ) Overlay of Area or Curve Elements by offsetting their baselines. To stack a HoloMap or DynamicMap use the map method.
def stack(cls, areas): """ Stacks an (Nd)Overlay of Area or Curve Elements by offsetting their baselines. To stack a HoloMap or DynamicMap use the map method. """ if not len(areas): return areas baseline = np.zeros(len(areas.values()[0])) stack...
Cleans up references to the plot on the attached Stream subscribers.
def cleanup(self): """ Cleans up references to the plot on the attached Stream subscribers. """ plots = self.traverse(lambda x: x, [Plot]) for plot in plots: if not isinstance(plot, (GenericCompositePlot, GenericElementPlot, GenericOverlayPlot)): ...
Matches a specification against the current Plot.
def matches(self, spec): """ Matches a specification against the current Plot. """ if callable(spec) and not isinstance(spec, type): return spec(self) elif isinstance(spec, type): return isinstance(self, spec) else: raise ValueError("Matching specs have to be ...
Traverses any nested DimensionedPlot returning a list of all plots that match the specs. The specs should be supplied as a list of either Plot types or callables which should return a boolean given the plot class.
def traverse(self, fn=None, specs=None, full_breadth=True): """ Traverses any nested DimensionedPlot returning a list of all plots that match the specs. The specs should be supplied as a list of either Plot types or callables, which should return a boolean given the plot class. ...
Returns the formatted dimension group strings for a particular frame.
def _frame_title(self, key, group_size=2, separator='\n'): """ Returns the formatted dimension group strings for a particular frame. """ if self.layout_dimensions is not None: dimensions, key = zip(*self.layout_dimensions.items()) elif not self.dynamic and (no...