holoviews.core.options module#
Options and OptionTrees allow different classes of options (e.g. matplotlib-specific styles and plot specific parameters) to be defined separately from the core data structures and away from visualization specific code.
There are three classes that form the options system:
Cycle:
Used to define infinite cycles over a finite set of elements, using either an explicit list or some pre-defined collection (e.g. from matplotlib rcParams). For instance, a Cycle object can be used loop a set of display colors for multiple curves on a single axis.
Options:
Containers of arbitrary keyword values, including optional keyword validation, support for Cycle objects and inheritance.
OptionTree:
A subclass of AttrTree that is used to define the inheritance relationships between a collection of Options objects. Each node of the tree supports a group of Options objects and the leaf nodes inherit their keyword values from parent nodes up to the root.
Store:
A singleton class that stores all global and custom options and links HoloViews objects, the chosen plotting backend and the IPython extension together.
- exception holoviews.core.options.AbbreviatedException(etype, value, traceback)[source]#
Bases:
Exception
Raised by the abbreviate_exception context manager when it is appropriate to present an abbreviated the traceback and exception message in the notebook.
Particularly useful when processing style options supplied by the user which may not be valid.
- exception holoviews.core.options.CallbackError[source]#
Bases:
RuntimeError
An error raised during a callback.
- class holoviews.core.options.Compositor(pattern, operation, group, mode, transfer_options=False, transfer_parameters=False, output_type=None, backends=None, **kwargs)[source]#
Bases:
Parameterized
A Compositor is a way of specifying an operation to be automatically applied to Overlays that match a specified pattern upon display.
Any Operation that takes an Overlay as input may be used to define a compositor.
For instance, a compositor may be defined to automatically display three overlaid monochrome matrices as an RGB image as long as the values names of those matrices match ‘R’, ‘G’ and ‘B’.
Parameter Definitions
mode = Selector(default='data', label='Mode', names={}, objects=['data', 'display'])
The mode of the Compositor object which may be either ‘data’ or ‘display’.
backends = List(bounds=(0, None), default=[], label='Backends')
Defines which backends to apply the Compositor for.
operation = Parameter(allow_None=True, label='Operation')
The Operation to apply when collapsing overlays.
pattern = String(default='', label='Pattern')
The overlay pattern to be processed. An overlay pattern is a sequence of elements specified by dotted paths separated by * . For instance the following pattern specifies three overlaid matrices with values of ‘RedChannel’, ‘GreenChannel’ and ‘BlueChannel’ respectively: ‘Image.RedChannel * Image.GreenChannel * Image.BlueChannel. This pattern specification could then be associated with the RGB operation that returns a single RGB matrix for display.
group = String(allow_None=True, default='', label='Group')
The group identifier for the output of this particular compositor
kwargs = Dict(allow_None=True, class_=<class 'dict'>, label='Kwargs')
Optional set of parameters to pass to the operation.
transfer_options = Boolean(default=False, label='Transfer options')
Whether to transfer the options from the input to the output.
transfer_parameters = Boolean(default=False, label='Transfer parameters')
Whether to transfer plot options which match to the operation.
- apply(value, input_ranges, backend=None)[source]#
Apply the compositor on the input with the given input ranges.
- classmethod collapse(holomap, ranges=None, mode='data')[source]#
Given a map of Overlays, apply all applicable compositors.
- classmethod collapse_element(overlay, ranges=None, mode='data', backend=None)[source]#
Finds any applicable compositor and applies it.
- classmethod map(obj, mode='data', backend=None)[source]#
Applies compositor operations to any HoloViews element or container using the map method.
- match_level(overlay)[source]#
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.
- property output_type#
Returns the operation output_type unless explicitly overridden in the kwargs.
- classmethod strongest_match(overlay, mode, backend=None)[source]#
Returns the single strongest matching compositor operation given an overlay. If no matches are found, None is returned.
The best match is defined as the compositor operation with the highest match value as returned by the match_level method.
- class holoviews.core.options.Cycle(cycle=None, **params)[source]#
Bases:
Parameterized
A simple container class that specifies cyclic options. A typical example would be to cycle the curve colors in an Overlay composed of an arbitrary number of curves. The values may be supplied as an explicit list or a key to look up in the default cycles attribute.
Parameter Definitions
key = String(allow_None=True, default='default_colors', label='Key')
The key in the default_cycles dictionary used to specify the color cycle if values is not supplied.
values = List(bounds=(0, None), default=[], label='Values')
The values the cycle will iterate over.
- class holoviews.core.options.Keywords(values=None, target=None)[source]#
Bases:
object
A keywords objects represents a set of Python keywords. It is list-like and ordered but it is also a set without duplicates. When passed as **kwargs, Python keywords are not ordered but this class always lists keywords in sorted order.
In addition to containing the list of keywords, Keywords has an optional target which describes what the keywords are applicable to.
This class is for internal use only and should not be in the user namespace.
- exception holoviews.core.options.OptionError(invalid_keyword, allowed_keywords, group_name=None, path=None)[source]#
Bases:
Exception
Custom exception raised when there is an attempt to apply invalid options. Stores the necessary information to construct a more readable message for the user if caught and processed appropriately.
- class holoviews.core.options.OptionTree(items=None, identifier=None, parent=None, groups=None, options=None, backend=None, **kwargs)[source]#
Bases:
AttrTree
A subclass of AttrTree that is used to define the inheritance relationships between a collection of Options objects. Each node of the tree supports a group of Options objects and the leaf nodes inherit their keyword values from parent nodes up to the root.
Supports the ability to search the tree for the closest valid path using the find method, or compute the appropriate Options value given an object and a mode. For a given node of the tree, the options method computes a Options object containing the result of inheritance for a given group up to the root of the tree.
When constructing an OptionTree, you can specify the option groups as a list (i.e. empty initial option groups at the root) or as a dictionary (e.g. groups={‘style’:Option()}). You can also initialize the OptionTree with the options argument together with the **kwargs - see StoreOptions.merge_options for more information on the options specification syntax.
You can use the string specifier ‘.’ to refer to the root node in the options specification. This acts as an alternative was of specifying the options groups of the current node. Note that this approach method may only be used with the group lists format.
- closest(obj, group, defaults=True, backend=None)[source]#
This method is designed to be called from the root of the tree. Given any LabelledData object, this method will return the most appropriate Options object, including inheritance.
In addition, closest supports custom options by checking the object
- class holoviews.core.options.Options(key=None, allowed_keywords=None, merge_keywords=True, max_cycles=None, **kwargs)[source]#
Bases:
object
An Options object holds a collection of keyword options. In addition, Options support (optional) keyword validation as well as infinite indexing over the set of supplied cyclic values.
Options support inheritance of setting values via the __call__ method. By calling an Options object with additional keywords, you can create a new Options object inheriting the parent options.
- property cyclic#
Returns True if the options cycle, otherwise False
- filtered(allowed)[source]#
Return a new Options object that is filtered by the specified list of keys. Mutating self.kwargs to filter is unsafe due to the option expansion that occurs on initialization.
- keywords_target(target)[source]#
Helper method to easily set the target on the allowed_keywords Keywords.
- max_cycles(num)[source]#
Truncates all contained Palette objects to a maximum number of samples and returns a new Options object containing the truncated or resampled Palettes.
- property options#
Access of the options keywords when no cycles are defined.
- class holoviews.core.options.Palette(key, **params)[source]#
Bases:
Cycle
Palettes allow easy specifying a discrete sampling of an existing colormap. Palettes may be supplied a key to look up a function function in the colormap class attribute. The function should accept a float scalar in the specified range and return a RGB(A) tuple. The number of samples may also be specified as a parameter.
The range and samples may conveniently be overridden with the __getitem__ method.
Parameter Definitions
Parameters inherited from:
holoviews.core.options.Cycle
: valueskey = String(default='grayscale', label='Key')
Palettes look up the Palette values based on some key.
range = NumericTuple(default=(0, 1), label='Range', length=2)
The range from which the Palette values are sampled.
samples = Integer(default=32, inclusive_bounds=(True, True), label='Samples')
The number of samples in the given range to supply to the sample_fn.
sample_fn = Callable(default=<function linspace at 0x10884c5b0>, label='Sample fn')
The function to generate the samples, by default linear.
reverse = Boolean(default=False, label='Reverse')
Whether to reverse the palette.
- sample_fn(stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, *, device=None)[source]#
Return evenly spaced numbers over a specified interval.
Returns num evenly spaced samples, calculated over the interval [start, stop].
The endpoint of the interval can optionally be excluded.
Changed in version 1.20.0: Values are rounded towards
-inf
instead of0
when an integerdtype
is specified. The old behavior can still be obtained withnp.linspace(start, stop, num).astype(int)
Parameters#
- startarray_like
The starting value of the sequence.
- stoparray_like
The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of
num + 1
evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.- numint, optional
Number of samples to generate. Default is 50. Must be non-negative.
- endpointbool, optional
If True, stop is the last sample. Otherwise, it is not included. Default is True.
- retstepbool, optional
If True, return (samples, step), where step is the spacing between samples.
- dtypedtype, optional
The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred dtype will never be an integer; float is chosen even if the arguments would produce an array of integers.
- axisint, optional
The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
- devicestr, optional
The device on which to place the created array. Default: None. For Array-API interoperability only, so must be
"cpu"
if passed.Added in version 2.0.0.
Returns#
- samplesndarray
There are num equally spaced samples in the closed interval
[start, stop]
or the half-open interval[start, stop)
(depending on whether endpoint is True or False).- stepfloat, optional
Only returned if retstep is True
Size of spacing between samples.
See Also#
- arangeSimilar to linspace, but uses a step size (instead of the
number of samples).
- geomspaceSimilar to linspace, but with numbers spaced evenly on a log
scale (a geometric progression).
- logspaceSimilar to geomspace, but with the end points specified as
logarithms.
how-to-partition
Examples#
>>> import numpy as np >>> np.linspace(2.0, 3.0, num=5) array([2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Graphical illustration:
>>> import matplotlib.pyplot as plt >>> N = 8 >>> y = np.zeros(N) >>> x1 = np.linspace(0, 10, N, endpoint=True) >>> x2 = np.linspace(0, 10, N, endpoint=False) >>> plt.plot(x1, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show()
- exception holoviews.core.options.SkipRendering(message='', warn=True)[source]#
Bases:
Exception
A SkipRendering exception in the plotting code will make the display hooks fall back to a text repr. Used to skip rendering of DynamicMaps with exhausted element generators.
- class holoviews.core.options.Store[source]#
Bases:
object
The Store is what links up HoloViews objects to their corresponding options and to the appropriate classes of the chosen backend (e.g. for rendering).
In addition, Store supports pickle operations that automatically pickle and unpickle the corresponding options for a HoloViews object.
- classmethod add_style_opts(component, new_options, backend=None)[source]#
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 corresponding plotting class.
- classmethod dump(obj, file, protocol=0)[source]#
Equivalent to pickle.dump except that the HoloViews option tree is saved appropriately.
- classmethod dumps(obj, protocol=0)[source]#
Equivalent to pickle.dumps except that the HoloViews option tree is saved appropriately.
- classmethod info(obj, ansi=True, backend='matplotlib', visualization=True, recursive=False, pattern=None, elements=None)[source]#
Show information about a particular object or component class including the applicable style and plot options. Returns None if the object is not parameterized.
- classmethod load(filename)[source]#
Equivalent to pickle.load except that the HoloViews trees is restored appropriately.
- classmethod loaded_backends()[source]#
Returns a list of the backends that have been loaded, based on the available OptionTrees.
- classmethod loads(pickle_string)[source]#
Equivalent to pickle.loads except that the HoloViews trees is restored appropriately.
- classmethod lookup(backend, obj)[source]#
Given an object, lookup the corresponding customized option tree if a single custom tree is applicable.
- output_settings[source]#
alias of
OutputSettings
- classmethod register(associations, backend, style_aliases=None)[source]#
Register the supplied dictionary of associations between elements and plotting classes to the specified backend.
- classmethod render(obj)[source]#
Using any display hooks that have been registered, render the object to a dictionary of MIME types and metadata information.
- classmethod set_current_backend(backend)[source]#
Use this method to set the backend to run the switch hooks
- class holoviews.core.options.StoreOptions[source]#
Bases:
object
A collection of utilities for advanced users for creating and setting customized option trees on the Store. Designed for use by either advanced users or the %opts line and cell magics which use this machinery.
This class also holds general classmethods for working with OptionTree instances: as OptionTrees are designed for attribute access it is best to minimize the number of methods implemented on that class and implement the necessary utilities on StoreOptions instead.
Lastly this class offers a means to record all OptionErrors generated by an option specification. This is used for validation purposes.
- classmethod apply_customizations(spec, options)[source]#
Apply the given option specs to the supplied options tree.
- classmethod capture_ids(obj)[source]#
Given an list of ids, capture a list of ids that can be restored using the restore_ids.
- classmethod create_custom_trees(obj, options=None, backend=None)[source]#
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 need to be matched as set to their new values.
- classmethod expand_compositor_keys(spec)[source]#
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’.
- classmethod id_offset()[source]#
Compute an appropriate offset for future id values given the set of ids currently defined across backends.
- classmethod merge_options(groups, options=None, **kwargs)[source]#
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) >>> sorted(merged['Curve']['style'].items()) [('color', 'b'), ('linewidth', 10)]
- classmethod options(obj, options=None, **kwargs)[source]#
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.options.set_options function for more information on the options specification format.
- classmethod propagate_ids(obj, match_id, new_id, applied_keys, backend=None)[source]#
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
- classmethod record_skipped_option(error)[source]#
Record the OptionError associated with a skipped option if currently recording
- classmethod restore_ids(obj, ids)[source]#
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.
- classmethod set_options(obj, options=None, backend=None, **kwargs)[source]#
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 Image components in the object. The key ‘Image.Channel’ would only customize Images in the object that have the group ‘Channel’.
The corresponding value is then a list of Option objects specified with an appropriate category (‘plot’, ‘style’ or ‘norm’). For instance, using the keys described above, the specs could be:
{‘Image:[Options(‘style’, cmap=’jet’)]}
Or setting two types of option at once:
- {‘Image.Channel’:[Options(‘plot’, size=50),
Options(‘style’, cmap=’Blues’)]}
Relationship to the %%opts magic#
This function matches the functionality supplied by the %%opts cell magic in the IPython extension. In fact, you can use the same syntax as the IPython cell magic to achieve the same customization as shown above:
from holoviews.util.parser import OptsSpec set_options(my_image, OptsSpec.parse(“Image (cmap=’jet’)”))
Then setting both plot and style options:
set_options(my_image, OptsSpec.parse(“Image [size=50] (cmap=’Blues’)”))
- classmethod start_recording_skipped()[source]#
Start collecting OptionErrors for all skipped options recorded with the record_skipped_option method
- classmethod state(obj, state=None)[source]#
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.
- classmethod stop_recording_skipped()[source]#
Stop collecting OptionErrors recorded with the record_skipped_option method and return them
- classmethod tree_to_dict(tree)[source]#
Given an OptionTree, convert it into the equivalent dictionary format.
- classmethod update_backends(id_mapping, custom_trees, backend=None)[source]#
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.
- classmethod validate_spec(spec, backends=None)[source]#
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, i.e. Options.skip_invalid is False.
- class holoviews.core.options.abbreviated_exception[source]#
Bases:
object
Context manager used to to abbreviate tracebacks using an AbbreviatedException when a backend may raise an error due to incorrect style options.
- holoviews.core.options.cleanup_custom_options(id, weakref=None)[source]#
Cleans up unused custom trees if all objects referencing the custom id have been garbage collected or tree is otherwise unreferenced.