holoviews.core.util module#
- class holoviews.core.util.ArgSpec(args, varargs, keywords, defaults)#
Bases:
tuple
- args#
Alias for field number 0
- defaults#
Alias for field number 3
- keywords#
Alias for field number 2
- varargs#
Alias for field number 1
- class holoviews.core.util.Config(*, default_cmap, default_gridded_cmap, default_heatmap_cmap, future_deprecations, image_rtol, no_padding, warn_options_call, name)[source]#
Bases:
ParameterizedFunction
Set of boolean configuration values to change HoloViews’ global behavior. Typically used to control warnings relating to deprecations or set global parameter such as style ‘themes’.
Parameter Definitions
future_deprecations = Boolean(default=False, label='Future deprecations')
Whether to warn about future deprecations
image_rtol = Number(default=0.001, inclusive_bounds=(True, True), label='Image rtol')
The tolerance used to enforce regular sampling for regular, gridded data where regular sampling is expected. Expressed as the maximal allowable sampling difference between sample locations.
no_padding = Boolean(default=False, label='No padding')
Disable default padding (introduced in 1.13.0).
warn_options_call = Boolean(default=True, label='Warn options call')
Whether to warn when the deprecated __call__ options syntax is used (the opts method should now be used instead). It is recommended that users switch this on to update any uses of __call__ as it will be deprecated in future.
default_cmap = String(default='kbc_r', label='Default cmap')
Global default colormap. Prior to HoloViews 1.14.0, the default value was ‘fire’ which can be set for backwards compatibility.
default_gridded_cmap = String(default='kbc_r', label='Default gridded cmap')
Global default colormap for gridded elements (i.e. Image, Raster and QuadMesh). Can be set to ‘fire’ to match raster defaults prior to HoloViews 1.14.0 while allowing the default_cmap to be the value of ‘kbc_r’ used in HoloViews >= 1.14.0
default_heatmap_cmap = String(default='kbc_r', label='Default heatmap cmap')
Global default colormap for HeatMap elements. Prior to HoloViews 1.14.0, the default value was the ‘RdYlBu_r’ colormap.
- class holoviews.core.util.HashableJSON(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]#
Bases:
JSONEncoder
Extends JSONEncoder to generate a hashable string for as many types of object as possible including nested objects and objects that are not normally hashable. The purpose of this class is to generate unique strings that once hashed are suitable for use in memoization and other cases where deep equality must be tested without storing the entire object.
By default JSONEncoder supports booleans, numbers, strings, lists, tuples and dictionaries. In order to support other types such as sets, datetime objects and mutable objects such as pandas Dataframes or numpy arrays, HashableJSON has to convert these types to datastructures that can normally be represented as JSON.
Support for other object types may need to be introduced in future. By default, unrecognized object types are represented by their id.
One limitation of this approach is that dictionaries with composite keys (e.g. tuples) are not supported due to the JSON spec.
- default(obj)[source]#
Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return super().default(o)
- class holoviews.core.util.ProgressIndicator(*, label, percent_range, name)[source]#
Bases:
Parameterized
Baseclass for any ProgressIndicator that indicates progress as a completion percentage.
Parameter Definitions
percent_range = NumericTuple(default=(0.0, 100.0), label='Percent range', length=2)
The total percentage spanned by the progress bar when called with a value between 0% and 100%. This allows an overall completion in percent to be broken down into smaller sub-tasks that individually complete to 100 percent.
label = String(allow_None=True, default='Progress', label='Label')
The label of the current progress bar.
- exception holoviews.core.util.VersionError(msg, version=None, min_version=None, **kwargs)[source]#
Bases:
Exception
Raised when there is a library version mismatch.
- holoviews.core.util.arglexsort(arrays)[source]#
Returns the indices of the lexicographical sorting order of the supplied arrays.
- holoviews.core.util.argspec(callable_obj)[source]#
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.
- holoviews.core.util.asarray(arraylike, strict=True)[source]#
Converts arraylike objects to NumPy ndarray types. Errors if object is not arraylike and strict option is enabled.
- holoviews.core.util.bound_range(vals, density, time_unit='us')[source]#
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.
- holoviews.core.util.callable_name(callable_obj)[source]#
Attempt to return a meaningful name identifying a callable or generator
- holoviews.core.util.capitalize_unicode_name(s)[source]#
Turns a string such as ‘capital delta’ into the shortened, capitalized version, in this case simply ‘Delta’. Used as a transform in sanitize_identifier.
- holoviews.core.util.cartesian_product(arrays, flat=True, copy=False)[source]#
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.
- holoviews.core.util.cast_array_to_int64(array)[source]#
Convert a numpy array to int64. Suppress the following warning emitted by Numpy, which as of 12/2021 has been extensively discussed (pandas-dev/pandas#22384) and whose fate (possible revert) has not yet been settled:
FutureWarning : casting datetime64[ns] values to int64 with .astype(…) is deprecated and will raise in a future version. Use .view(…) instead.
- holoviews.core.util.cftime_to_timestamp(date, time_unit='us')[source]#
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 calendar. In order to handle these dates correctly a custom bokeh model with support for other calendars would have to be defined.
Parameters#
date : cftime datetime object (or array)
Returns#
time_unit since 1970-01-01 00:00:00
- holoviews.core.util.closest_match(match, specs, depth=0)[source]#
Recursively iterates over type, group, label and overlay key, finding the closest matching spec.
- holoviews.core.util.compute_density(start, end, length, time_unit='us')[source]#
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.
- holoviews.core.util.compute_edges(edges)[source]#
Computes edges as midpoints of the bin centers. The first and last boundaries are equidistant from the first and last midpoints respectively.
- holoviews.core.util.cross_index(values, index)[source]#
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.
- holoviews.core.util.date_range(start, end, length, time_unit='us')[source]#
Computes a date range given a start date, end date and the number of samples.
- holoviews.core.util.deephash(obj)[source]#
Given an object, return a hash using HashableJSON. This hash is not architecture, Python version or platform independent.
- holoviews.core.util.deprecated_opts_signature(args, kwargs)[source]#
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.
- holoviews.core.util.dimension_range(lower, upper, hard_range, soft_range, padding=None, log=False)[source]#
Computes the range along a dimension by combining the data range with the Dimension soft_range and range.
- holoviews.core.util.dimension_sort(odict, kdims, vdims, key_index)[source]#
Sorts data by key using usual Python tuple sorting semantics or sorts in categorical order for any categorical Dimensions.
- holoviews.core.util.dimensioned_streams(dmap)[source]#
Given a DynamicMap return all streams that have any dimensioned parameters, i.e. parameters also listed in the key dimensions.
- holoviews.core.util.dimensionless_contents(streams, kdims, no_duplicates=True)[source]#
Return a list of stream parameters that have not been associated with any of the key dimensions.
- holoviews.core.util.disable_constant(parameterized)[source]#
Temporarily set parameters on Parameterized object to constant=False.
- holoviews.core.util.drop_streams(streams, kdims, keys)[source]#
Drop any dimensioned streams from the keys and kdims.
- holoviews.core.util.dt64_to_dt(dt64)[source]#
Safely converts NumPy datetime64 to a datetime object.
- holoviews.core.util.dt_to_int(value, time_unit='us')[source]#
Converts a datetime type to an integer with the supplied time unit.
- holoviews.core.util.expand_grid_coords(dataset, dim)[source]#
Expand the coordinates along a dimension of the gridded dataset into an ND-array matching the dimensionality of the dataset.
- holoviews.core.util.find_minmax(lims, olims)[source]#
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.
- holoviews.core.util.find_range(values, soft_range=None)[source]#
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.
- holoviews.core.util.flatten(line)[source]#
Flatten an arbitrarily nested sequence.
Inspired by: pd.core.common.flatten
Parameters#
- linesequence
The sequence to flatten
Notes#
This only flattens list, tuple, and dict sequences.
Returns#
flattened : generator
- holoviews.core.util.get_method_owner(method)[source]#
Gets the instance that owns the supplied method
- holoviews.core.util.get_ndmapping_label(ndmapping, attr)[source]#
Function to get the first non-auxiliary object label attribute from an NdMapping.
- holoviews.core.util.get_overlay_spec(o, k, v)[source]#
Gets the type.group.label + key spec from an Element in an Overlay.
- holoviews.core.util.get_path(item)[source]#
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.
- holoviews.core.util.group_select(selects, length=None, depth=None)[source]#
Given a list of key tuples to select, groups them into sensible chunks to avoid duplicating indexing operations.
- holoviews.core.util.int_to_alpha(n, upper=True)[source]#
Generates alphanumeric labels of form A-Z, AA-ZZ etc.
- holoviews.core.util.is_cyclic(graph)[source]#
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.
- holoviews.core.util.is_dataframe(data)[source]#
Checks whether the supplied data is of DataFrame type.
- holoviews.core.util.is_int(obj, int_like=False)[source]#
Checks for int types including the native Python type and NumPy-like objects
Parameters#
- obj
Object to check for integer type
- int_likeboolean
Check for float types with integer value
Returns#
Boolean indicating whether the supplied value is of integer type.
- holoviews.core.util.is_param_method(obj, has_deps=False)[source]#
Whether the object is a method on a parameterized object.
Parameters#
- obj
Object to check
- has_depsboolean, optional
Check for dependencies Whether to also check whether the method has been annotated with param.depends
Returns#
A boolean value indicating whether the object is a method on a Parameterized object and if enabled whether it has any dependencies
- holoviews.core.util.isdatetime(value)[source]#
Whether the array or scalar is recognized datetime type.
- holoviews.core.util.isequal(value1, value2)[source]#
Compare two values, returning a boolean.
Will apply the comparison to all elements of an array/dataframe.
- holoviews.core.util.isfinite(val)[source]#
Helper function to determine if scalar or array value is finite extending np.isfinite with support for None, string, datetime types.
- holoviews.core.util.isnat(val)[source]#
Checks if the value is a NaT. Should only be called on datetimelike objects.
- holoviews.core.util.iterative_select(obj, dimensions, selects, depth=None)[source]#
Takes the output of group_select selecting subgroups iteratively, avoiding duplicating select operations.
- holoviews.core.util.layer_groups(ordering, length=2)[source]#
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.
- holoviews.core.util.layer_sort(hmap)[source]#
Find a global ordering for layers in a HoloMap of CompositeOverlay types.
- holoviews.core.util.lazy_isinstance(obj, class_or_tuple)[source]#
Lazy isinstance check
Will only import the module of the object if the module of the obj matches the first value of an item in class_or_tuple.
lazy_isinstance(obj, ‘dask.dataframe:DataFrame’)
- Will :
check if the first module is dask
If it dask, import dask.dataframe
Do an isinstance check for dask.dataframe.DataFrame
- holoviews.core.util.make_path_unique(path, counts, new)[source]#
Given a path, a list of existing paths and counts for each of the existing paths.
- holoviews.core.util.match_spec(element, specification)[source]#
Matches the group.label specification of the supplied element against the supplied specification dictionary returning the value of the best match.
- holoviews.core.util.max_extents(extents, zrange=False)[source]#
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.
- holoviews.core.util.max_range(ranges, combined=True)[source]#
Computes the maximal lower and upper bounds from a list bounds.
Parameters#
- rangeslist of tuples
A list of range tuples
- combinedboolean, optional
Whether to combine bounds Whether range should be computed on lower and upper bound independently or both at once
Returns#
The maximum range as a single tuple
- holoviews.core.util.merge_dimensions(dimensions_list)[source]#
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) >>> dimensions [Dimension('A'), Dimension('B')] >>> dimensions[0].values [1, 2, 3, 4]
- holoviews.core.util.merge_option_dicts(old_opts, new_opts)[source]#
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’}}
- and
new_opts = {‘a’: {‘y’: ‘new’, ‘z’: ‘new’}, ‘b’: {‘k’: ‘new’}}
- this returns a dictionary
{‘a’: {‘x’: ‘old’, ‘y’: ‘new’, ‘z’: ‘new’}, ‘b’: {‘k’: ‘new’}}
- holoviews.core.util.merge_options_to_dict(options)[source]#
Given a collection of Option objects or partial option dictionaries, merge everything to a single dictionary.
- class holoviews.core.util.ndmapping_groupby(*, sort, name)[source]#
Bases:
ParameterizedFunction
Apply a groupby operation to an NdMapping, using pandas to improve performance (if available).
Parameter Definitions
sort = Boolean(default=False, label='Sort')
Whether to apply a sorted groupby
- holoviews.core.util.numpy_scalar_to_python(scalar)[source]#
Converts a NumPy scalar to a regular python type.
- holoviews.core.util.one_to_one(graph, nodes)[source]#
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.
- holoviews.core.util.parse_datetime(date)[source]#
Parses dates specified as string or integer or pandas Timestamp
- holoviews.core.util.parse_datetime_selection(sel)[source]#
Parses string selection specs as datetimes.
- class holoviews.core.util.periodic(period, count, callback, timeout=None, block=False)[source]#
Bases:
Thread
Run a callback count times with a given period without blocking.
If count is None, will run till timeout (which may be forever if None).
- run()[source]#
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
- holoviews.core.util.process_ellipses(obj, key, vdim_selection=False)[source]#
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 (i.e. the resulting key will be exactly one longer than the number of kdims). Note: this flag should not be used for composite types.
- holoviews.core.util.range_pad(lower, upper, padding=None, log=False)[source]#
Pads the range by a fraction of the interval
- holoviews.core.util.rename_stream_kwargs(stream, kwargs, reverse=False)[source]#
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 parameter names given a dictionary using the renamed equivalents.
- holoviews.core.util.resolve_dependent_kwargs(kwargs)[source]#
Resolves parameter dependencies in the supplied dictionary
Resolves parameter values, Parameterized instance methods and parameterized functions with dependencies in the supplied dictionary.
Parameters#
- kwargsdict
A dictionary of keyword arguments
Returns#
A new dictionary where any parameter dependencies have been resolved.
- holoviews.core.util.resolve_dependent_value(value)[source]#
Resolves parameter dependencies on the supplied value
Resolves parameter values, Parameterized instance methods, parameterized functions with dependencies on the supplied value, including such parameters embedded in a list, tuple, dictionary, or slice.
Parameters#
- value
A value which will be resolved
Returns#
A new value where any parameter dependencies have been resolved.
- class holoviews.core.util.sanitize_identifier_fn(*, _lookup_table, aliases, capitalize, disable_leading_underscore, disallowed, eliminations, substitutions, transforms, name)[source]#
Bases:
ParameterizedFunction
Sanitizes group/label values for use in AttrTree attribute access.
Special characters are sanitized using their (lowercase) unicode name using the unicodedata module. For instance:
>>> unicodedata.name(u'$').lower() 'dollar sign'
As these names are often very long, this parameterized function allows filtered, substitutions and transforms to help shorten these names appropriately.
Parameter Definitions
capitalize = Boolean(default=True, label='Capitalize')
Whether the first letter should be converted to uppercase. Note, this will only be applied to ASCII characters in order to make sure paths aren’t confused with method names.
eliminations = List(bounds=(0, None), default=['extended', 'accent', 'small', 'letter', 'sign', 'digit', 'latin', 'greek', 'arabic-indic', 'with', 'dollar'], label='Eliminations')
Lowercase strings to be eliminated from the unicode names in order to shorten the sanitized name ( lowercase). Redundant strings should be removed but too much elimination could cause two unique strings to map to the same sanitized output.
substitutions = Dict(class_=<class 'dict'>, default={'circumflex': 'power', 'asterisk': 'times', 'solidus': 'over'}, label='Substitutions')
Lowercase substitutions of substrings in unicode names. For instance the ^ character has the name ‘circumflex accent’ even though it is more typically used for exponentiation. Note that substitutions occur after filtering and that there should be no ordering dependence between substitutions.
transforms = List(bounds=(0, None), default=[<function capitalize_unicode_name at 0x116a3ade0>], label='Transforms')
List of string transformation functions to apply after filtering and substitution in order to further compress the unicode name. For instance, the default capitalize_unicode_name function will turn the string “capital delta” into “Delta”.
disallowed = List(bounds=(0, None), default=['trait_names', '_ipython_display_', '_getAttributeNames'], label='Disallowed')
An explicit list of name that should not be allowed as attribute names on Tree objects. By default, prevents IPython from creating an entry called Trait_names due to an inconvenient getattr check (during tab-completion).
disable_leading_underscore = Boolean(default=False, label='Disable leading underscore')
Whether leading underscores should be allowed to be sanitized with the leading prefix.
aliases = Dict(class_=<class 'dict'>, default={}, label='Aliases')
A dictionary of aliases mapping long strings to their short, sanitized equivalents
_lookup_table = Dict(class_=<class 'dict'>, default={}, label=' lookup table')
Cache of previously computed sanitizations
- add_aliases(**kwargs)[source]#
Conveniently add new aliases as keyword arguments. For instance you can add a new alias with add_aliases(short=’Longer string’)
- prefixed(identifier)[source]#
Whether or not the identifier will be prefixed. Strings that require the prefix are generally not recommended.
- holoviews.core.util.search_indices(values, source)[source]#
Given a set of values returns the indices of each of those values in the source array.
- holoviews.core.util.sort_topologically(graph)[source]#
Stackless topological sorting.
- graph = {
3 : [1], 5 : [3], 4 : [2], 6 : [4],
}
sort_topologically(graph) [[1, 2], [3, 4], [5, 6]]
- holoviews.core.util.stream_name_mapping(stream, exclude_params=None, reverse=False)[source]#
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 original stream parameter names.
- holoviews.core.util.stream_parameters(streams, no_duplicates=True, exclude=None)[source]#
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.
- holoviews.core.util.tree_attribute(identifier)[source]#
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)
- holoviews.core.util.unbound_dimensions(streams, kdims, no_duplicates=True)[source]#
Return a list of dimensions that have not been associated with any streams.
- holoviews.core.util.unique_array(arr)[source]#
Returns an array of unique values in the input order.
Parameters#
- arrnp.ndarray or list
The array to compute unique values on
Returns#
A new array of unique values
- holoviews.core.util.unique_iterator(seq)[source]#
Returns an iterator containing all non-duplicate elements in the input sequence.
- holoviews.core.util.validate_dynamic_argspec(callback, kdims, streams)[source]#
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 keywords.
If the callbacks use *args, None is returned to indicate that kdim values must be passed to the Callable by position. In this situation, Callable passes *args and **kwargs directly to the callback.
If the callback doesn’t use **kwargs, the accepted keywords are validated against the stream parameter names.