INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Uses Delauney triangulation to compute triangle simplices for
each point. | def from_vertices(cls, data):
"""
Uses Delauney triangulation to compute triangle simplices for
each point.
"""
try:
from scipy.spatial import Delaunay
except:
raise ImportError("Generating triangles from points requires, "
... |
Returns the EdgePaths by generating a triangle for each simplex. | def edgepaths(self):
"""
Returns the EdgePaths by generating a triangle for each simplex.
"""
if self._edgepaths:
return self._edgepaths
elif not len(self):
edgepaths = self.edge_type([], kdims=self.nodes.kdims[:2])
self._edgepaths = edgepaths
... |
Allows selecting data by the slices, sets and scalar values
along a particular dimension. The indices should be supplied as
keywords mapping between the selected dimension and
value. Additionally selection_specs (taking the form of a list
of type.group.label strings, types or functions) ... | def select(self, selection_specs=None, **selection):
"""
Allows selecting data by the slices, sets and scalar values
along a particular dimension. The indices should be supplied as
keywords mapping between the selected dimension and
value. Additionally selection_specs (taking the... |
Extends the ElementPlot _finalize_axis method to set appropriate
labels, and axes options for 3D Plots. | def _finalize_axis(self, key, **kwargs):
"""
Extends the ElementPlot _finalize_axis method to set appropriate
labels, and axes options for 3D Plots.
"""
axis = self.handles['axis']
self.handles['fig'].set_frameon(False)
axis.grid(self.show_grid)
axis.view_... |
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected. | def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
... |
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.
"""
import dask.dataframe as dd
if len(data.columns) > 1 or len(data) != 1:
return data
if isinstance(data, ... |
Dask does not support iloc, therefore iloc will execute
the call graph and lose the laziness of the operation. | def iloc(cls, dataset, index):
"""
Dask does not support iloc, therefore iloc will execute
the call graph and lose the laziness of the operation.
"""
rows, cols = index
scalar = False
if isinstance(cols, slice):
cols = [d.name for d in dataset.dimensio... |
Populate the sourceLinks and targetLinks for each node.
Also, if the source and target are not objects, assume they are indices. | def computeNodeLinks(cls, element, graph):
"""
Populate the sourceLinks and targetLinks for each node.
Also, if the source and target are not objects, assume they are indices.
"""
index = element.nodes.kdims[-1]
node_map = {}
if element.nodes.vdims:
va... |
Compute the value (size) of each node by summing the associated links. | def computeNodeValues(cls, graph):
"""
Compute the value (size) of each node by summing the associated links.
"""
for node in graph['nodes']:
source_val = np.sum([l['value'] for l in node['sourceLinks']])
target_val = np.sum([l['value'] for l in node['targetLinks'... |
Iteratively assign the depth (x-position) for each node.
Nodes are assigned the maximum depth of incoming neighbors plus one;
nodes with no incoming links are assigned depth zero, while
nodes with no outgoing links are assigned the maximum depth. | def computeNodeDepths(self, graph):
"""
Iteratively assign the depth (x-position) for each node.
Nodes are assigned the maximum depth of incoming neighbors plus one;
nodes with no incoming links are assigned depth zero, while
nodes with no outgoing links are assigned the maximum ... |
Get data from histogram, including bin_ranges and values. | def _process_hist(self, hist):
"""
Get data from histogram, including bin_ranges and values.
"""
self.cyclic = hist.get_dimension(0).cyclic
x = hist.kdims[0]
edges = hist.interface.coords(hist, x, edges=True)
values = hist.dimension_values(1)
hist_vals = n... |
Compute the ticks either as cyclic values in degrees or as roughly
evenly spaced bin centers. | def _compute_ticks(self, element, edges, widths, lims):
"""
Compute the ticks either as cyclic values in degrees or as roughly
evenly spaced bin centers.
"""
if self.xticks is None or not isinstance(self.xticks, int):
return None
if self.cyclic:
x0... |
Get axis settings options including ticks, x- and y-labels
and limits. | def _process_axsettings(self, hist, lims, ticks):
"""
Get axis settings options including ticks, x- and y-labels
and limits.
"""
axis_settings = dict(zip(self.axis_settings, [None, None, (None if self.overlaid else ticks)]))
return axis_settings |
Update all the artists in the histogram. Subclassable to
allow updating of further artists. | def _update_artists(self, key, hist, edges, hvals, widths, lims, ranges):
"""
Update all the artists in the histogram. Subclassable to
allow updating of further artists.
"""
plot_vals = zip(self.handles['artist'], edges, hvals, widths)
for bar, edge, height, width in plot... |
Subclassed to offset histogram by defined amount. | def _process_hist(self, hist):
"""
Subclassed to offset histogram by defined amount.
"""
edges, hvals, widths, lims, isdatetime = super(SideHistogramPlot, self)._process_hist(hist)
offset = self.offset * lims[3]
hvals *= 1-self.offset
hvals += offset
lims ... |
Process the bars and draw the offset line as necessary. If a
color map is set in the style of the 'main' ViewableElement object, color
the bars appropriately, respecting the required normalization
settings. | def _update_plot(self, key, element, bars, lims, ranges):
"""
Process the bars and draw the offset line as necessary. If a
color map is set in the style of the 'main' ViewableElement object, color
the bars appropriately, respecting the required normalization
settings.
"""... |
Use the given cmap to color the bars, applying the correct
color ranges as necessary. | def _colorize_bars(self, cmap, bars, element, main_range, dim):
"""
Use the given cmap to color the bars, applying the correct
color ranges as necessary.
"""
cmap_range = main_range[1] - main_range[0]
lower_bound = main_range[0]
colors = np.array(element.dimension... |
Compute colorbar offset and update separator line
if map is non-zero. | def _update_separator(self, offset):
"""
Compute colorbar offset and update separator line
if map is non-zero.
"""
offset_line = self.handles['offset_line']
if offset == 0:
offset_line.set_visible(False)
else:
offset_line.set_visible(True)
... |
Get unique index value for each bar | def _get_values(self):
"""
Get unique index value for each bar
"""
(gi, _), (ci, _), (si, _) = self._get_dims(self.hmap.last)
ndims = self.hmap.last.ndims
dims = self.hmap.last.kdims
dimensions = []
values = {}
for vidx, vtype in zip([gi, ci, si], ... |
Computes color and hatch combinations by
any combination of the 'group', 'category'
and 'stack'. | def _compute_styles(self, element, style_groups):
"""
Computes color and hatch combinations by
any combination of the 'group', 'category'
and 'stack'.
"""
style = self.lookup_options(element, 'style')[0]
sopts = []
for sopt in ['color', 'hatch']:
... |
Apply ticks with appropriate offsets. | def _finalize_ticks(self, axis, element, xticks, yticks, zticks):
"""
Apply ticks with appropriate offsets.
"""
yalignments = None
if xticks is not None:
ticks, labels, yalignments = zip(*sorted(xticks, key=lambda x: x[0]))
xticks = (list(ticks), list(labe... |
Group inherited from main element | def group(self):
"Group inherited from main element"
if self.main and self.main.group != type(self.main).__name__:
return self.main.group
else:
return 'AdjointLayout' |
Clone object and apply new group and/or label.
Applies relabeling to child up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to returned object
depth (int, optional): Depth to which... | def relabel(self, label=None, group=None, depth=1):
"""Clone object and apply new group and/or label.
Applies relabeling to child up to the supplied depth.
Args:
label (str, optional): New label to apply to returned object
group (str, optional): New group to apply to re... |
Return the values along the requested dimension.
Applies to the main object in the AdjointLayout.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior depends
... | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Applies to the main object in the AdjointLayout.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
... |
Compute a dict of {(row,column): (key, value)} elements from the
current set of items and specified number of columns. | def grid_items(self):
"""
Compute a dict of {(row,column): (key, value)} elements from the
current set of items and specified number of columns.
"""
if list(self.keys()) == []: return {}
cols = self._max_cols
return {(idx // cols, idx % cols): (key, item)
... |
Returns another NdLayout constituted of the last views of the
individual elements (if they are maps). | def last(self):
"""
Returns another NdLayout constituted of the last views of the
individual elements (if they are maps).
"""
last_items = []
for (k, v) in self.items():
if isinstance(v, NdMapping):
item = (k, v.clone((v.last_key, v.last)))
... |
Clones the NdLayout, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Additional arguments to pass to constructor
... | def clone(self, *args, **overrides):
"""Clones the NdLayout, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Add... |
Tuple indicating the number of rows and columns in the Layout. | def shape(self):
"Tuple indicating the number of rows and columns in the Layout."
num = len(self)
if num <= self._max_cols:
return (1, num)
nrows = num // self._max_cols
last_row_cols = num % self._max_cols
return nrows+(1 if last_row_cols else 0), min(num, se... |
Clones the Layout, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Additional arguments to pass to constructor
... | def clone(self, *args, **overrides):
"""Clones the Layout, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Type to cast object to
*args: Addit... |
Returns a json diff required to update an existing plot with
the latest plot data. | def diff(self, plot, serialize=True):
"""
Returns a json diff required to update an existing plot with
the latest plot data.
"""
diff = plot.state
if serialize:
return json.dumps(diff, cls=utils.PlotlyJSONEncoder)
else:
return diff |
Loads the plotly notebook resources. | def load_nb(cls, inline=True):
"""
Loads the plotly notebook resources.
"""
from IPython.display import publish_display_data
cls._loaded = True
init_notebook_mode(connected=not inline)
publish_display_data(data={MIME_TYPES['jlab-hv-load']:
... |
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 len(data) != 1:
return data
key = list(data.keys())[0]
if len(data[key]) == 1 and key in dataset.vdi... |
Utility used to make sure AST parser does not choke on unrecognized
magics. | def comment_out_magics(source):
"""
Utility used to make sure AST parser does not choke on unrecognized
magics.
"""
filtered = []
for line in source.splitlines():
if line.strip().startswith('%'):
filtered.append('# ' + line)
else:
filtered.append(line)
... |
If a cell ends in an expression that could be displaying a HoloViews
object (as determined using the AST), wrap it with a given prefix
and suffix string.
If the cell doesn't end in an expression, return the source unchanged. | def wrap_cell_expression(source, template='{expr}'):
"""
If a cell ends in an expression that could be displaying a HoloViews
object (as determined using the AST), wrap it with a given prefix
and suffix string.
If the cell doesn't end in an expression, return the source unchanged.
"""
cell_... |
Given the source of a cell, filter out the given magic and collect
the lines using the magic into a list.
If strip is True, the IPython syntax part of the magic (e.g %magic
or %%magic) is stripped from the returned lines. | def filter_magic(source, magic, strip=True):
"""
Given the source of a cell, filter out the given magic and collect
the lines using the magic into a list.
If strip is True, the IPython syntax part of the magic (e.g %magic
or %%magic) is stripped from the returned lines.
"""
filtered, magic_... |
Given the source of a cell, filter out all cell and line magics. | def strip_magics(source):
"""
Given the source of a cell, filter out all cell and line magics.
"""
filtered=[]
for line in source.splitlines():
if not line.startswith('%') or line.startswith('%%'):
filtered.append(line)
return '\n'.join(filtered) |
Given a cell's source, replace line magics using a formatting
template, where {line} is the string that follows the magic. | def replace_line_magic(source, magic, template='{line}'):
"""
Given a cell's source, replace line magics using a formatting
template, where {line} is the string that follows the magic.
"""
filtered = []
for line in source.splitlines():
if line.strip().startswith(magic):
subst... |
Given some source html substitute and annotated as applicable | def replace(self, src):
"Given some source html substitute and annotated as applicable"
for html in self.substitutions.keys():
if src == html:
annotation = self.annotation % self.substitutions[src][1]
return annotation + self.substitutions[src][0]
retu... |
Extract the subplot number from a subplot value string.
'x3' -> 3
'polar2' -> 2
'scene' -> 1
'y' -> 1
Note: the absence of a subplot number (e.g. 'y') is treated by plotly as
a subplot number of 1
Parameters
----------
subplot_val: str
Subplot string value (e.g. 'scene4')
... | def _get_subplot_number(subplot_val):
"""
Extract the subplot number from a subplot value string.
'x3' -> 3
'polar2' -> 2
'scene' -> 1
'y' -> 1
Note: the absence of a subplot number (e.g. 'y') is treated by plotly as
a subplot number of 1
Parameters
----------
subplot_val:... |
Make sure a layout subplot property is initialized for every subplot that
is referenced by a trace in the figure.
For example, if a figure contains a `scatterpolar` trace with the `subplot`
property set to `polar3`, this function will make sure the figure's layout
has a `polar3` property, and will init... | def _normalize_subplot_ids(fig):
"""
Make sure a layout subplot property is initialized for every subplot that
is referenced by a trace in the figure.
For example, if a figure contains a `scatterpolar` trace with the `subplot`
property set to `polar3`, this function will make sure the figure's layo... |
Given an input figure, return a dict containing the max subplot number
for each subplot type in the figure
Parameters
----------
fig: dict
A plotly figure dict
Returns
-------
dict
A dict from subplot type strings to integers indicating the largest
subplot number in... | def _get_max_subplot_ids(fig):
"""
Given an input figure, return a dict containing the max subplot number
for each subplot type in the figure
Parameters
----------
fig: dict
A plotly figure dict
Returns
-------
dict
A dict from subplot type strings to integers indic... |
Apply offsets to the subplot id numbers in a figure.
Note: This function mutates the input figure dict
Note: This function assumes that the normalize_subplot_ids function has
already been run on the figure, so that all layout subplot properties in
use are explicitly present in the figure's layout.
... | def _offset_subplot_ids(fig, offsets):
"""
Apply offsets to the subplot id numbers in a figure.
Note: This function mutates the input figure dict
Note: This function assumes that the normalize_subplot_ids function has
already been run on the figure, so that all layout subplot properties in
use... |
Scale a figure and translate it to sub-region of the original
figure canvas.
Note: If the input figure has a title, this title is converted into an
annotation and scaled along with the rest of the figure.
Note: This function mutates the input fig dict
Note: This function assumes that the normaliz... | def _scale_translate(fig, scale_x, scale_y, translate_x, translate_y):
"""
Scale a figure and translate it to sub-region of the original
figure canvas.
Note: If the input figure has a title, this title is converted into an
annotation and scaled along with the rest of the figure.
Note: This fun... |
Merge a sub-figure into a parent figure
Note: This function mutates the input fig dict, but it does not mutate
the subfig dict
Parameters
----------
fig: dict
The plotly figure dict into which the sub figure will be merged
subfig: dict
The plotly figure dict that will be copied... | def merge_figure(fig, subfig):
"""
Merge a sub-figure into a parent figure
Note: This function mutates the input fig dict, but it does not mutate
the subfig dict
Parameters
----------
fig: dict
The plotly figure dict into which the sub figure will be merged
subfig: dict
... |
Merge layout objects recursively
Note: This function mutates the input obj dict, but it does not mutate
the subobj dict
Parameters
----------
obj: dict
dict into which the sub-figure dict will be merged
subobj: dict
dict that sill be copied and merged into `obj` | def _merge_layout_objs(obj, subobj):
"""
Merge layout objects recursively
Note: This function mutates the input obj dict, but it does not mutate
the subobj dict
Parameters
----------
obj: dict
dict into which the sub-figure dict will be merged
subobj: dict
dict that sil... |
Compute normalized domain tuples for a list of widths and a subplot
spacing value
Parameters
----------
widths: list of float
List of the desired withs of each subplot. The length of this list
is also the specification of the number of desired subplots
spacing: float
Spacing... | def _compute_subplot_domains(widths, spacing):
"""
Compute normalized domain tuples for a list of widths and a subplot
spacing value
Parameters
----------
widths: list of float
List of the desired withs of each subplot. The length of this list
is also the specification of the nu... |
Construct a figure from a 2D grid of sub-figures
Parameters
----------
figures_grid: list of list of (dict or None)
2D list of plotly figure dicts that will be combined in a grid to
produce the resulting figure. None values maybe used to leave empty
grid cells
row_heights: list... | def figure_grid(figures_grid,
row_heights=None,
column_widths=None,
row_spacing=0.15,
column_spacing=0.15,
share_xaxis=False,
share_yaxis=False):
"""
Construct a figure from a 2D grid of sub-figures
Parameters
... |
Converts a cmap spec to a plotly colorscale
Args:
cmap: A recognized colormap by name or list of colors
levels: A list or integer declaring the color-levels
cmin: The lower bound of the color range
cmax: The upper bound of the color range
Returns:
A valid plotly colorsc... | def get_colorscale(cmap, levels=None, cmin=None, cmax=None):
"""Converts a cmap spec to a plotly colorscale
Args:
cmap: A recognized colormap by name or list of colors
levels: A list or integer declaring the color-levels
cmin: The lower bound of the color range
cmax: The upper b... |
Given a HoloViews Viewable return a corresponding plot instance. | def get_plot(self_or_cls, obj, renderer=None, **kwargs):
"""
Given a HoloViews Viewable return a corresponding plot instance.
"""
if isinstance(obj, DynamicMap) and obj.unbounded:
dims = ', '.join('%r' % dim for dim in obj.unbounded)
msg = ('DynamicMap cannot be d... |
Helper method to be used in the __call__ method to get a
suitable plot or widget object and the appropriate format. | def _validate(self, obj, fmt, **kwargs):
"""
Helper method to be used in the __call__ method to get a
suitable plot or widget object and the appropriate format.
"""
if isinstance(obj, tuple(self.widgets.values())):
return obj, 'html'
plot = self.get_plot(obj, ... |
Apply the post-render hooks to the data. | def _apply_post_render_hooks(self, data, obj, fmt):
"""
Apply the post-render hooks to the data.
"""
hooks = self.post_render_hooks.get(fmt,[])
for hook in hooks:
try:
data = hook(data, obj)
except Exception as e:
self.param... |
Renders plot or data structure and wraps the output in HTML.
The comm argument defines whether the HTML output includes
code to initialize a Comm, if the plot supplies one. | def html(self, obj, fmt=None, css=None, **kwargs):
"""
Renders plot or data structure and wraps the output in HTML.
The comm argument defines whether the HTML output includes
code to initialize a Comm, if the plot supplies one.
"""
plot, fmt = self._validate(obj, fmt)
... |
Returns data and metadata dictionaries containing HTML and JS
components to include render in app, notebook, or standalone
document. Depending on the backend the fmt defines the format
embedded in the HTML, e.g. png or svg. If comm is enabled the
JS code will set up a Websocket comm chan... | def components(self, obj, fmt=None, comm=True, **kwargs):
"""
Returns data and metadata dictionaries containing HTML and JS
components to include render in app, notebook, or standalone
document. Depending on the backend the fmt defines the format
embedded in the HTML, e.g. png or... |
Generates a static HTML with the rendered object in the
supplied format. Allows supplying a template formatting string
with fields to interpolate 'js', 'css' and the main 'html'. | def static_html(self, obj, fmt=None, template=None):
"""
Generates a static HTML with the rendered object in the
supplied format. Allows supplying a template formatting string
with fields to interpolate 'js', 'css' and the main 'html'.
"""
js_html, css_html = self.html_as... |
Render and export object as a widget to a static HTML
file. Allows supplying a custom template formatting string
with fields to interpolate 'js', 'css' and the main 'html'
containing the widget. Also provides options to export widget
data to a json file in the supplied json_path (default... | def export_widgets(self_or_cls, obj, filename, fmt=None, template=None,
json=False, json_path='', **kwargs):
"""
Render and export object as a widget to a static HTML
file. Allows supplying a custom template formatting string
with fields to interpolate 'js', 'css' ... |
Given an object or Element class, return the suitable plotting
class needed to render it with the current renderer. | def plotting_class(cls, obj):
"""
Given an object or Element class, return the suitable plotting
class needed to render it with the current renderer.
"""
if isinstance(obj, AdjointLayout) or obj is AdjointLayout:
obj = Layout
if isinstance(obj, type):
... |
Returns JS and CSS and for embedding of widgets. | def html_assets(cls, core=True, extras=True, backends=None, script=False):
"""
Returns JS and CSS and for embedding of widgets.
"""
if backends is None:
backends = [cls.backend] if cls.backend else []
# Get all the widgets and find the set of required js widget files... |
Save a HoloViews object to file, either using an explicitly
supplied format or to the appropriate default. | def save(self_or_cls, obj, basename, fmt='auto', key={}, info={}, options=None, **kwargs):
"""
Save a HoloViews object to file, either using an explicitly
supplied format or to the appropriate default.
"""
if info or key:
raise Exception('Renderer does not support sav... |
Loads any resources required for display of plots
in the Jupyter notebook | def load_nb(cls, inline=True):
"""
Loads any resources required for display of plots
in the Jupyter notebook
"""
with param.logging_level('ERROR'):
cls.notebook_context = True
cls.comm_manager = JupyterCommManager |
Deletes registered plots and calls Plot.cleanup | def _delete_plot(cls, plot_id):
"""
Deletes registered plots and calls Plot.cleanup
"""
plot = cls._plots.get(plot_id)
if plot is None:
return
plot.cleanup()
del cls._plots[plot_id] |
Return the strength of the match (None if no match) | def _match(cls, el, spec):
"Return the strength of the match (None if no match)"
spec_dict = dict(zip(['type', 'group', 'label'], spec.split('.')))
if not isinstance(el, Image) or spec_dict['type'] != 'Image':
raise NotImplementedError("Only Image currently supported")
sanit... |
Given a raster or input overlay, generate a list of matched
elements (None if no match) and corresponding tuple of match
strength values. | def _match_overlay(self, raster, overlay_spec):
"""
Given a raster or input overlay, generate a list of matched
elements (None if no match) and corresponding tuple of match
strength values.
"""
ordering = [None]*len(overlay_spec) # Elements to overlay
strengths = ... |
Returns a Dataset template used as a wrapper around the data
contained within the multi-interface dataset. | def _inner_dataset_template(cls, dataset):
"""
Returns a Dataset template used as a wrapper around the data
contained within the multi-interface dataset.
"""
from . import Dataset
vdims = dataset.vdims if getattr(dataset, 'level', None) is None else []
return Data... |
Tests if dimension is scalar in each subpath. | def isscalar(cls, dataset, dim):
"""
Tests if dimension is scalar in each subpath.
"""
if not dataset.data:
return True
ds = cls._inner_dataset_template(dataset)
isscalar = []
for d in dataset.data:
ds.data = d
isscalar.append(d... |
Applies selectiong on all the subpaths. | def select(cls, dataset, selection_mask=None, **selection):
"""
Applies selectiong on all the subpaths.
"""
if not dataset.data:
return []
ds = cls._inner_dataset_template(dataset)
data = []
for d in dataset.data:
ds.data = d
se... |
Allows selecting paths with usual NumPy slicing index. | def select_paths(cls, dataset, selection):
"""
Allows selecting paths with usual NumPy slicing index.
"""
return [s[0] for s in np.array([{0: p} for p in dataset.data])[selection]] |
Returns the shape of all subpaths, making it appear like a
single array of concatenated subpaths separated by NaN values. | def shape(cls, dataset):
"""
Returns the shape of all subpaths, making it appear like a
single array of concatenated subpaths separated by NaN values.
"""
if not dataset.data:
return (0, len(dataset.dimensions()))
rows, cols = 0, 0
ds = cls._inner_dat... |
Returns the length of the multi-tabular dataset making it appear
like a single array of concatenated subpaths separated by NaN
values. | def length(cls, dataset):
"""
Returns the length of the multi-tabular dataset making it appear
like a single array of concatenated subpaths separated by NaN
values.
"""
if not dataset.data:
return 0
length = 0
ds = cls._inner_dataset_template(d... |
Returns a single concatenated array of all subpaths separated
by NaN values. If expanded keyword is False an array of arrays
is returned. | def values(cls, dataset, dimension, expanded, flat):
"""
Returns a single concatenated array of all subpaths separated
by NaN values. If expanded keyword is False an array of arrays
is returned.
"""
if not dataset.data:
return np.array([])
values = []
... |
Splits a multi-interface Dataset into regular Datasets using
regular tabular interfaces. | def split(cls, dataset, start, end, datatype, **kwargs):
"""
Splits a multi-interface Dataset into regular Datasets using
regular tabular interfaces.
"""
objs = []
if datatype is None:
for d in dataset.data[start: end]:
objs.append(dataset.clon... |
Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimension(s) to compute histogram on
num_bins (int, optional): Number of bins
bin_range (t... | def hist(self, dimension=None, num_bins=20, bin_range=None,
adjoin=True, **kwargs):
"""Computes and adjoins histogram along specified dimension(s).
Defaults to first value dimension if present otherwise falls
back to first key dimension.
Args:
dimension: Dimens... |
Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
multi_index: Convert key dimensions to (multi-)index
Return... | def dframe(self, dimensions=None, multi_index=False):
"""Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
mul... |
Convert dimension values to columnar array.
Args:
dimensions: List of dimensions to return
Returns:
Array of columns corresponding to each dimension | def array(self, dimensions=None):
"""Convert dimension values to columnar array.
Args:
dimensions: List of dimensions to return
Returns:
Array of columns corresponding to each dimension
"""
if dimensions is None:
dims = [d for d in self.kdims... |
Deprecated method to convert any Element to a Table. | def table(self, datatype=None):
"Deprecated method to convert any Element to a Table."
if config.future_deprecations:
self.param.warning(
"The table method is deprecated and should no "
"longer be used. Instead cast the %s to a "
"a Table direc... |
Deprecated method to convert data to dictionary | def mapping(self, kdims=None, vdims=None, **kwargs):
"Deprecated method to convert data to dictionary"
if config.future_deprecations:
self.param.warning(
"The mapping method is deprecated and should no "
"longer be used. Use another one of the common "
... |
Formatted contents of table cell.
Args:
row (int): Integer index of table row
col (int): Integer index of table column
Returns:
Formatted table cell contents | def pprint_cell(self, row, col):
"""Formatted contents of table cell.
Args:
row (int): Integer index of table row
col (int): Integer index of table column
Returns:
Formatted table cell contents
"""
ndims = self.ndims
if col >= self.co... |
Return all constant dimensions. | def static_dimensions(self):
"""
Return all constant dimensions.
"""
dimensions = []
for dim in self.kdims:
if len(set(self.dimension_values(dim.name))) == 1:
dimensions.append(dim)
return dimensions |
Recursively descend through an Layout and NdMapping objects
in order to add the supplied dimension values to all contained
HoloMaps. | def _add_dimensions(self, item, dims, constant_keys):
"""
Recursively descend through an Layout and NdMapping objects
in order to add the supplied dimension values to all contained
HoloMaps.
"""
if isinstance(item, Layout):
item.fixed = False
dim_vals... |
Renders the supplied object and displays it using the active
GUI backend. | def show(self, obj):
"""
Renders the supplied object and displays it using the active
GUI backend.
"""
if self.interactive:
if isinstance(obj, list):
return [self.get_plot(o) for o in obj]
return self.get_plot(obj)
from .plot impor... |
Establish support for a kernel density estimate. | def _kde_support(bin_range, bw, gridsize, cut, clip):
"""Establish support for a kernel density estimate."""
kmin, kmax = bin_range[0] - bw * cut, bin_range[1] + bw * cut
if isfinite(clip[0]):
kmin = max(kmin, clip[0])
if isfinite(clip[1]):
kmax = min(kmax, clip[1])
return np.linspac... |
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 ... |
Returns the latest plot data to update an existing plot. | def diff(self, plot):
"""
Returns the latest plot data to update an existing plot.
"""
if self.fig == 'auto':
figure_format = self.params('fig').objects[0]
else:
figure_format = self.fig
return self.html(plot, figure_format) |
Render matplotlib figure object and return the corresponding
data. If as_script is True, the content will be split in an
HTML and a JS component.
Similar to IPython.core.pylabtools.print_figure but without
any IPython dependency. | def _figure_data(self, plot, fmt='png', bbox_inches='tight', as_script=False, **kwargs):
"""
Render matplotlib figure object and return the corresponding
data. If as_script is True, the content will be split in an
HTML and a JS component.
Similar to IPython.core.pylabtools.prin... |
Render a matplotlib animation object and return the corresponding data. | def _anim_data(self, anim, fmt):
"""
Render a matplotlib animation object and return the corresponding data.
"""
(writer, _, anim_kwargs, extra_args) = ANIMATION_OPTS[fmt]
if extra_args != []:
anim_kwargs = dict(anim_kwargs, extra_args=extra_args)
if self.fps... |
Compute the tight bounding box for each figure once, reducing
number of required canvas draw calls from N*2 to N+1 as a
function of the number of frames.
Tight bounding box computing code here mirrors:
matplotlib.backend_bases.FigureCanvasBase.print_figure
as it hasn't been fact... | def _compute_bbox(self, fig, kw):
"""
Compute the tight bounding box for each figure once, reducing
number of required canvas draw calls from N*2 to N+1 as a
function of the number of frames.
Tight bounding box computing code here mirrors:
matplotlib.backend_bases.Figure... |
Initialize matplotlib backend | def load_nb(cls, inline=True):
"""
Initialize matplotlib backend
"""
import matplotlib.pyplot as plt
backend = plt.get_backend()
if backend not in ['agg', 'module://ipykernel.pylab.backend_inline']:
plt.switch_backend('agg') |
Cleans up unused custom trees if all objects referencing the
custom id have been garbage collected or tree is otherwise
unreferenced. | def cleanup_custom_options(id, weakref=None):
"""
Cleans up unused custom trees if all objects referencing the
custom id have been garbage collected or tree is otherwise
unreferenced.
"""
try:
if Store._options_context:
return
weakrefs = Store._weakrefs.get(id, [])
... |
Context manager to temporarily set the skip_invalid and warn_on_skip
class parameters on Options. | def options_policy(skip_invalid, warn_on_skip):
"""
Context manager to temporarily set the skip_invalid and warn_on_skip
class parameters on Options.
"""
settings = (Options.skip_invalid, Options.warn_on_skip)
(Options.skip_invalid, Options.warn_on_skip) = (skip_invalid, warn_on_skip)
yield
... |
Return a fuzzy match message based on the OptionError | def format_options_error(self):
"""
Return a fuzzy match message based on the OptionError
"""
allowed_keywords = self.allowed_keywords
target = allowed_keywords.target
matches = allowed_keywords.fuzzy_match(self.invalid_keyword)
if not matches:
matches... |
Print the traceback of the exception wrapped by the AbbreviatedException. | def print_traceback(self):
"""
Print the traceback of the exception wrapped by the AbbreviatedException.
"""
traceback.print_exception(self.etype, self.value, self.traceback) |
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. | def filtered(self, allowed):
"""
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.
"""
kws = {k:v for k,v in self.kwargs.items() if k in allowed}
... |
Truncates all contained Palette objects to a maximum number
of samples and returns a new Options object containing the
truncated or resampled Palettes. | def max_cycles(self, num):
"""
Truncates all contained Palette objects to a maximum number
of samples and returns a new Options object containing the
truncated or resampled Palettes.
"""
kwargs = {kw: (arg[num] if isinstance(arg, Palette) else arg)
for k... |
Returns True if the options cycle, otherwise False | def cyclic(self):
"Returns True if the options cycle, otherwise False"
return any(isinstance(val, Cycle) for val in self.kwargs.values()) |
Computes a merged Options object for the given group
name from the existing Options on the node and the
new Options which are passed in. | def _merge_options(self, identifier, group_name, options):
"""
Computes a merged Options object for the given group
name from the existing Options on the node and the
new Options which are passed in.
"""
if group_name not in self.groups:
raise KeyError("Group ... |
Find the closest node or path to an the arbitrary path that is
supplied down the tree from the given node. The mode argument
may be either 'node' or 'path' which determines the return
type. | def find(self, path, mode='node'):
"""
Find the closest node or path to an the arbitrary path that is
supplied down the tree from the given node. The mode argument
may be either 'node' or 'path' which determines the return
type.
"""
path = path.split('.') if isins... |
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 | def closest(self, obj, group, defaults=True):
"""
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 ch... |
Using inheritance up to the root, get the complete Options
object for the given node and the specified group. | def options(self, group, target=None, defaults=True):
"""
Using inheritance up to the root, get the complete Options
object for the given node and the specified group.
"""
if target is None:
target = self.path
if self.groups.get(group, None) is None:
... |
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. | def strongest_match(cls, overlay, mode, backend=None):
"""
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 th... |
Finds any applicable compositor and applies it. | def collapse_element(cls, overlay, ranges=None, mode='data', backend=None):
"""
Finds any applicable compositor and applies it.
"""
from .element import Element
from .overlay import Overlay, CompositeOverlay
unpack = False
if not isinstance(overlay, CompositeOverl... |
Given a map of Overlays, apply all applicable compositors. | def collapse(cls, holomap, ranges=None, mode='data'):
"""
Given a map of Overlays, apply all applicable compositors.
"""
# No potential compositors
if cls.definitions == []:
return holomap
# Apply compositors
clone = holomap.clone(shared_data=False)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.