INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Simple name_generator designed for HoloViews objects. | def simple_name_generator(obj):
"""
Simple name_generator designed for HoloViews objects.
Objects are labeled with {group}-{label} for each nested
object, based on a depth-first search. Adjacent objects with
identical representations yield only a single copy of the
representation, to avoid lon... |
Classmethod that applies conditional encoding based on mime - type. Given an entry as returned by __call__ return the data in the appropriate encoding. | def encode(cls, entry):
"""
Classmethod that applies conditional encoding based on
mime-type. Given an entry as returned by __call__ return the
data in the appropriate encoding.
"""
(data, info) = entry
if info['mime_type'] in cls.utf8_mime_types:
retu... |
Add the file extension if not already present | def _filename(self_or_cls, filename):
"Add the file extension if not already present"
if not filename.endswith(self_or_cls.file_ext):
return '%s.%s' % (filename, self_or_cls.file_ext)
else:
return filename |
Returns a merged metadata info dictionary from the supplied function and additional dictionaries | def _merge_metadata(self_or_cls, obj, fn, *dicts):
"""
Returns a merged metadata info dictionary from the supplied
function and additional dictionaries
"""
merged = dict([(k,v) for d in dicts for (k,v) in d.items()])
return dict(merged, **fn(obj)) if fn else merged |
Given a list or NdMapping type containing file paths return a Layout of Collators which can be called to load a given set of files using the current Importer. | def collect(self_or_cls, files, drop=[], metadata=True):
"""
Given a list or NdMapping type containing file paths return a
Layout of Collators, which can be called to load a given set
of files using the current Importer.
If supplied as a list each file is expected to disambiguat... |
Returns the format fields otherwise raise exception | def parse_fields(cls, formatter):
"Returns the format fields otherwise raise exception"
if formatter is None: return []
try:
parse = list(string.Formatter().parse(formatter))
return set(f for f in list(zip(*parse))[1] if f is not None)
except:
raise S... |
If a filename is supplied it will be used. Otherwise a filename will be generated from the supplied object. Note that if the explicit filename uses the { timestamp } field it will be formatted upon export. | def add(self, obj=None, filename=None, data=None, info={}, **kwargs):
"""
If a filename is supplied, it will be used. Otherwise, a
filename will be generated from the supplied object. Note that
if the explicit filename uses the {timestamp} field, it will
be formatted upon export.... |
Find a unique basename for a new file/ key where existing is either a list of ( basename ext ) pairs or an absolute path to a directory. | def _unique_name(self, basename, ext, existing, force=False):
"""
Find a unique basename for a new file/key where existing is
either a list of (basename, ext) pairs or an absolute path to
a directory.
By default, uniqueness is enforced depending on the state of
the uniqu... |
Export the archive directory or file. | def export(self, timestamp=None, info={}):
"""
Export the archive, directory or file.
"""
tval = tuple(time.localtime()) if timestamp is None else timestamp
tstamp = time.strftime(self.timestamp_format, tval)
info = dict(info, timestamp=tstamp)
export_name = self... |
Print the current ( unexported ) contents of the archive | def contents(self, maxlen=70):
"Print the current (unexported) contents of the archive"
lines = []
if len(self._files) == 0:
print("Empty %s" % self.__class__.__name__)
return
fnames = [self._truncate_name(maxlen=maxlen, *k) for k in self._files]
max_len ... |
Return a list of filename entries currently in the archive | def listing(self):
"Return a list of filename entries currently in the archive"
return ['.'.join([f,ext]) if ext else f for (f,ext) in self._files.keys()] |
A helper utility to display a progress bar when iterating over a collection of a fixed length or a generator ( with a declared length ). | def progress(iterator, enum=False, length=None):
"""
A helper utility to display a progress bar when iterating over a
collection of a fixed length or a generator (with a declared
length).
If enum=True, then equivalent to enumerate with a progress bar.
"""
progress = ProgressBar()
length... |
Returns the figure in html format on the first call and | def _plot_figure(self, idx, fig_format='json'):
"""
Returns the figure in html format on the
first call and
"""
self.plot.update(idx)
if self.embed:
return self.renderer.diff(self.plot) |
Calculate the true density along x and adjust the top and bottom bounds so that the density along y will be equal. | def __equalize_densities(self,nominal_bounds,nominal_density):
"""
Calculate the true density along x, and adjust the top and
bottom bounds so that the density along y will be equal.
Returns (adjusted_bounds, true_density)
"""
left,bottom,right,top = nominal_bounds.lbrt(... |
Convert a point ( x y ) in Sheet coordinates to continuous matrix coordinates. | def sheet2matrix(self,x,y):
"""
Convert a point (x,y) in Sheet coordinates to continuous
matrix coordinates.
Returns (float_row,float_col), where float_row corresponds to
y, and float_col to x.
Valid for scalar or array x and y.
Note about Bounds For a Sheet wi... |
Convert a point ( x y ) in sheet coordinates to the integer row and column index of the matrix cell in which that point falls given a bounds and density. Returns ( row column ). | def sheet2matrixidx(self,x,y):
"""
Convert a point (x,y) in sheet coordinates to the integer row
and column index of the matrix cell in which that point falls,
given a bounds and density. Returns (row,column).
Note that if coordinates along the right or bottom boundary
... |
Convert a floating - point location ( float_row float_col ) in matrix coordinates to its corresponding location ( x y ) in sheet coordinates. | def matrix2sheet(self,float_row,float_col):
"""
Convert a floating-point location (float_row,float_col) in
matrix coordinates to its corresponding location (x,y) in
sheet coordinates.
Valid for scalar or array float_row and float_col.
Inverse of sheet2matrix().
... |
Return ( x y ) where x and y are the floating point coordinates of the * center * of the given matrix cell ( row col ). If the matrix cell represents a 0. 2 by 0. 2 region then the center location returned would be 0. 1 0. 1. | def matrixidx2sheet(self,row,col):
"""
Return (x,y) where x and y are the floating point coordinates
of the *center* of the given matrix cell (row,col). If the
matrix cell represents a 0.2 by 0.2 region, then the center
location returned would be 0.1,0.1.
NOTE: This is N... |
Given arbitrary sheet coordinates return the sheet coordinates of the center of the closest unit. | def closest_cell_center(self,x,y):
"""
Given arbitrary sheet coordinates, return the sheet coordinates
of the center of the closest unit.
"""
return self.matrixidx2sheet(*self.sheet2matrixidx(x,y)) |
Return x y where x is a vector of sheet coordinates representing the x - center of each matrix cell and y represents the corresponding y - center of the cell. | def sheetcoordinates_of_matrixidx(self):
"""
Return x,y where x is a vector of sheet coordinates
representing the x-center of each matrix cell, and y
represents the corresponding y-center of the cell.
"""
rows,cols = self.shape
return self.matrixidx2sheet(np.arang... |
Gets the matrix indices of a slice within an array of size sheetshape from a sliceshape positioned at coord. | def findinputslice(coord, sliceshape, sheetshape):
"""
Gets the matrix indices of a slice within an array of size
sheetshape from a sliceshape, positioned at coord.
"""
center_row, center_col = coord
n_rows, n_cols = sliceshape
sheet_rows, sheet_cols = sheetshape
... |
Return the correct slice for a weights/ mask matrix at this ConnectionField s location on the sheet ( i. e. for getting the correct submatrix of the weights or mask in case the unit is near the edge of the sheet ). | def positionlesscrop(self,x,y,sheet_coord_system):
"""
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge of the sheet).
"""
... |
Offset the bounds_template to this cf s location and store the result in the bounds attribute. | def positionedcrop(self,x,y,sheet_coord_system):
"""
Offset the bounds_template to this cf's location and store the
result in the 'bounds' attribute.
Also stores the input_sheet_slice for access by C.
"""
cf_row,cf_col = sheet_coord_system.sheet2matrixidx(x,y)
bo... |
Crop the slice to the SheetCoordinateSystem s bounds. | def crop_to_sheet(self,sheet_coord_system):
"Crop the slice to the SheetCoordinateSystem's bounds."
maxrow,maxcol = sheet_coord_system.shape
self[0] = max(0,self[0])
self[1] = min(maxrow,self[1])
self[2] = max(0,self[2])
self[3] = min(maxcol,self[3]) |
Create the odd Slice that best approximates the specified sheet - coordinate bounds. | def _createoddslicespec(bounds,scs,min_matrix_radius):
"""
Create the 'odd' Slice that best approximates the specified
sheet-coordinate bounds.
The supplied bounds are translated to have a center at the
center of one of the sheet's units (we arbitrarily use the
center un... |
Convert an iterable boundsspec ( supplying l b r t of a BoundingRegion ) into a Slice specification. | def _boundsspec2slicespec(boundsspec,scs):
"""
Convert an iterable boundsspec (supplying l,b,r,t of a
BoundingRegion) into a Slice specification.
Includes all units whose centers are within the specified
sheet-coordinate bounds specified by boundsspec.
Exact inverse of ... |
Convert an iterable slicespec ( supplying r1 r2 c1 c2 of a Slice ) into a BoundingRegion specification. | def _slicespec2boundsspec(slicespec,scs):
"""
Convert an iterable slicespec (supplying r1,r2,c1,c2 of a
Slice) into a BoundingRegion specification.
Exact inverse of _boundsspec2slicespec().
"""
r1,r2,c1,c2 = slicespec
left,bottom = scs.matrix2sheet(r2,c1)
... |
A Chord plot is always drawn on a unit circle. | def get_extents(self, element, ranges, range_type='combined'):
"""
A Chord plot is always drawn on a unit circle.
"""
if range_type == 'extents':
return element.nodes.extents
xdim, ydim = element.nodes.kdims[:2]
xpad = .05 if self.label_index is None else 0.25... |
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 or len(data.columns) > 1:
return data
return data.iat[0,0] |
Returns the data of a Dataset as a dataframe avoiding copying if it already a dataframe type. | def as_dframe(cls, dataset):
"""
Returns the data of a Dataset as a dataframe avoiding copying
if it already a dataframe type.
"""
if issubclass(dataset.interface, PandasInterface):
return dataset.data
else:
return dataset.dframe() |
Escapes a list of values to a string converting to unicode for safety. | def escape_vals(vals, escape_numerics=True):
"""
Escapes a list of values to a string, converting to
unicode for safety.
"""
# Ints formatted as floats to disambiguate with counter mode
ints, floats = "%.1f", "%.10f"
escaped = []
for v in vals:
if isinstance(v, np.timedelta64):
... |
Saves frames data into a json file at the specified json_path named with the widget uuid. | def save_json(self, frames):
"""
Saves frames data into a json file at the
specified json_path, named with the widget uuid.
"""
if self.json_save_path is None: return
path = os.path.join(self.json_save_path, '%s.json' % self.id)
if not os.path.isdir(self.json_save... |
Helper utility to access the active renderer for a given extension. | def renderer(name):
"""
Helper utility to access the active renderer for a given extension.
"""
try:
if name not in Store.renderers:
extension(name)
return Store.renderers[name]
except ImportError:
msg = ('Could not find a {name!r} renderer, available renderers ar... |
Saves the supplied object to file. | def save(obj, filename, fmt='auto', backend=None, **kwargs):
"""
Saves the supplied object to file.
The available output formats depend on the backend being used. By
default and if the filename is a string the output format will be
inferred from the file extension. Otherwise an explicit format
... |
Renders the HoloViews object to the corresponding object in the specified backend e. g. a Matplotlib or Bokeh figure. | def render(obj, backend=None, **kwargs):
"""
Renders the HoloViews object to the corresponding object in the
specified backend, e.g. a Matplotlib or Bokeh figure.
The backend defaults to the currently declared default
backend. The resulting object can then be used with other objects
in the spec... |
Format option group kwargs into canonical options format | def _group_kwargs_to_options(cls, obj, kwargs):
"Format option group kwargs into canonical options format"
groups = Options._option_groups
if set(kwargs.keys()) - set(groups):
raise Exception("Keyword options %s must be one of %s" % (groups,
','.join(repr... |
Apply the groups to a single specified backend | def _apply_groups_to_backend(cls, obj, options, backend, clone):
"Apply the groups to a single specified backend"
obj_handle = obj
if options is None:
if clone:
obj_handle = obj.map(lambda x: x.clone(id=None))
else:
obj.map(lambda x: setatt... |
Group options by backend and filter out output group appropriately | def _grouped_backends(cls, options, backend):
"Group options by backend and filter out output group appropriately"
if options is None:
return [(backend or Store.current_backend, options)]
dfltdict = defaultdict(dict)
for spec, groups in options.items():
if 'outpu... |
Applies nested options definition grouped by type. | def apply_groups(cls, obj, options=None, backend=None, clone=True, **kwargs):
"""Applies nested options definition grouped by type.
Applies options on an object or nested group of objects,
returning a new object with the options applied. This method
accepts the separate option namespace... |
Deprecated not expected to be used by any current code | def _cellmagic(cls, options, obj, strict=False):
"Deprecated, not expected to be used by any current code"
options, failure = cls._process_magic(options, strict)
if failure: return obj
if not isinstance(obj, Dimensioned):
return obj
else:
return StoreOptio... |
Deprecated not expected to be used by any current code | def _linemagic(cls, options, strict=False, backend=None):
"Deprecated, not expected to be used by any current code"
backends = None if backend is None else [backend]
options, failure = cls._process_magic(options, strict, backends=backends)
if failure: return
with options_policy(s... |
Set default options for a session. | def defaults(cls, *options, **kwargs):
"""Set default options for a session.
Set default options for a session. whether in a Python script or
a Jupyter notebook.
Args:
*options: Option objects used to specify the defaults.
backend: The plotting extension the opti... |
Given a list of flat Option objects which may or may not have backend in their kwargs return a list of grouped backend | def _expand_by_backend(cls, options, backend):
"""
Given a list of flat Option objects which may or may not have
'backend' in their kwargs, return a list of grouped backend
"""
groups = defaultdict(list)
used_fallback = False
for obj in options:
if 'ba... |
Validates and expands a dictionaries of options indexed by type [. group ] [. label ] keys into separate style plot norm and output options. | def _expand_options(cls, options, backend=None):
"""
Validates and expands a dictionaries of options indexed by
type[.group][.label] keys into separate style, plot, norm and
output options.
opts._expand_options({'Image': dict(cmap='viridis', show_title=False)})
retu... |
Generates an error message for an invalid option suggesting similar options through fuzzy matching. | def _options_error(cls, opt, objtype, backend, valid_options):
"""
Generates an error message for an invalid option suggesting
similar options through fuzzy matching.
"""
current_backend = Store.current_backend
loaded_backends = Store.loaded_backends()
kws = Keywo... |
Given a list of Option objects ( such as those returned from OptsSpec. parse_options ) or an %opts or %%opts magic string return a list of corresponding option builder reprs. The namespace is typically given as hv if fully qualified namespaces are desired. | def _builder_reprs(cls, options, namespace=None, ns=None):
"""
Given a list of Option objects (such as those returned from
OptsSpec.parse_options) or an %opts or %%opts magic string,
return a list of corresponding option builder reprs. The
namespace is typically given as 'hv' if ... |
Returns a dictionary of element names to allowed keywords | def _element_keywords(cls, backend, elements=None):
"Returns a dictionary of element names to allowed keywords"
if backend not in Store.loaded_backends():
return {}
mapping = {}
backend_options = Store.options(backend)
elements = elements if elements is not None else... |
Generates a list of streams to attach to the returned DynamicMap. If the input is a DynamicMap any streams that are supplying values for the key dimension of the input are inherited. And the list of supplied stream classes and instances are processed and added to the list. | def _get_streams(self, map_obj, watch=True):
"""
Generates a list of streams to attach to the returned DynamicMap.
If the input is a DynamicMap any streams that are supplying values
for the key dimension of the input are inherited. And the list
of supplied stream classes and inst... |
Evaluates any parameterized methods in the kwargs | def _eval_kwargs(self):
"""Evaluates any parameterized methods in the kwargs"""
evaled_kwargs = {}
for k, v in self.p.kwargs.items():
if util.is_param_method(v):
v = v()
evaled_kwargs[k] = v
return evaled_kwargs |
Generate function to dynamically apply the operation. Wraps an existing HoloMap or DynamicMap. | def _dynamic_operation(self, map_obj):
"""
Generate function to dynamically apply the operation.
Wraps an existing HoloMap or DynamicMap.
"""
if not isinstance(map_obj, DynamicMap):
def dynamic_operation(*key, **kwargs):
kwargs = dict(self._eval_kwargs... |
Accepts a HoloMap and a dynamic callback function creating an equivalent DynamicMap from the HoloMap. | def _make_dynamic(self, hmap, dynamic_fn, streams):
"""
Accepts a HoloMap and a dynamic callback function creating
an equivalent DynamicMap from the HoloMap.
"""
if isinstance(hmap, ViewableElement):
return DynamicMap(dynamic_fn, streams=streams)
dim_values = ... |
Triggers update to a plot on a refresh event | def _trigger_refresh(self, key):
"Triggers update to a plot on a refresh event"
if self.top_level:
self.update(key)
else:
self.current_key = None
self.current_frame = None |
Unity - based normalization to scale data into 0 - 1 range. | def norm(values, min=None, max=None):
"""Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
values: Array of values to be normalized
min (float, optional): Lower bound of normalization range
max (float, optional): Upper bound of normaliza... |
Bins data into declared bins | def bin(values, bins, labels=None):
"""Bins data into declared bins
Bins data into declared bins. By default each bin is labelled
with bin center values but an explicit list of bin labels may be
defined.
Args:
values: Array of values to be binned
bins: List or array containing the ... |
Maps discrete values to supplied categories. | def categorize(values, categories, default=None):
"""Maps discrete values to supplied categories.
Replaces discrete values in input array with a fixed set of
categories defined either as a list or dictionary.
Args:
values: Array of values to be categorized
categories: List or dict of c... |
Bins continuous values. | def bin(self, bins, labels=None):
"""Bins continuous values.
Bins continuous using the provided bins and assigns labels
either computed from each bins center point or from the
supplied labels.
Args:
bins: List or array containing the bin boundaries
label... |
Replaces discrete values with supplied categories | def categorize(self, categories, default=None):
"""Replaces discrete values with supplied categories
Replaces discrete values in input array into a fixed set of
categories defined either as a list or dictionary.
Args:
categories: List or dict of categories to map inputs to
... |
Unity - based normalization to scale data into 0 - 1 range. | def norm(self, limits=None):
"""Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
limits: tuple of (min, max) defining the normalization range
"""
kwargs = {}
if limits is not None:
kwargs = {'min': li... |
Determines whether the dim transform can be applied to the Dataset i. e. whether all referenced dimensions can be resolved. | def applies(self, dataset):
"""
Determines whether the dim transform can be applied to the
Dataset, i.e. whether all referenced dimensions can be
resolved.
"""
if isinstance(self.dimension, dim):
applies = self.dimension.applies(dataset)
else:
... |
Evaluates the transform on the supplied dataset. | def apply(self, dataset, flat=False, expanded=None, ranges={}, all_values=False):
"""Evaluates the transform on the supplied dataset.
Args:
dataset: Dataset object to evaluate the expression on
flat: Whether to flatten the returned array
expanded: Whether to use the ... |
Computes the node quad glyph data. x | def _compute_quads(self, element, data, mapping):
"""
Computes the node quad glyph data.x
"""
quad_mapping = {'left': 'x0', 'right': 'x1', 'bottom': 'y0', 'top': 'y1'}
quad_data = dict(data['scatter_1'])
quad_data.update({'x0': [], 'x1': [], 'y0': [], 'y1': []})
f... |
Computes labels for the nodes and adds it to the data. | def _compute_labels(self, element, data, mapping):
"""
Computes labels for the nodes and adds it to the data.
"""
if element.vdims:
edges = Dataset(element)[element[element.vdims[0].name]>0]
nodes = list(np.unique([edges.dimension_values(i) for i in range(2)]))
... |
Replace edge start and end hover data with label_index data. | def _patch_hover(self, element, data):
"""
Replace edge start and end hover data with label_index data.
"""
if not (self.inspection_policy == 'edges' and 'hover' in self.handles):
return
lidx = element.nodes.get_dimension(self.label_index)
src, tgt = [dimensio... |
Select a style by name e. g. set_style ( default ). To revert to the previous style use the key unset or False. | def set_style(key):
"""
Select a style by name, e.g. set_style('default'). To revert to the
previous style use the key 'unset' or False.
"""
if key is None:
return
elif not key or key in ['unset', 'backup']:
if 'backup' in styles:
plt.rcParams.update(styles['backup'])... |
Builds a parameter filter using the supplied pattern ( may be a general Python regular expression ) | def regexp_filter(self_or_cls, pattern):
"""
Builds a parameter filter using the supplied pattern (may be a
general Python regular expression)
"""
def inner_filter(name, p):
name_match = re.search(pattern,name)
if name_match is not None:
re... |
Get parameter information from the supplied class or object. | def get_parameter_info(cls, obj, ansi=False, show_values=True,
pattern=None, max_col_len=40):
"""
Get parameter information from the supplied class or object.
"""
if cls.ppager is None: return ''
if pattern is not None:
obj = ParamFilter(ob... |
Turn the supplied heading text into a suitable heading with optional underline and color. | def heading(cls, heading_text, char='=', level=0, ansi=False):
"""
Turn the supplied heading text into a suitable heading with
optional underline and color.
"""
heading_color = cls.headings[level] if ansi else '%s'
if char is None:
return heading_color % '%s\n... |
Show information about an object in the given category. ANSI color codes may be enabled or disabled. | def info(cls, obj, ansi=False, backend='matplotlib', visualization=True,
pattern=None, elements=[]):
"""
Show information about an object in the given category. ANSI
color codes may be enabled or disabled.
"""
cls.elements = elements
ansi_escape = re.compile(... |
Return the type. group. label dotted information | def component_type(cls_or_slf, node):
"Return the type.group.label dotted information"
if node is None: return ''
return cls_or_slf.type_formatter.format(type=str(type(node).__name__)) |
Recursive function that builds up an ASCII tree given an AttrTree node. | def recurse(cls_or_slf, node, attrpath=None, attrpaths=[], siblings=[], level=0, value_dims=True):
"""
Recursive function that builds up an ASCII tree given an
AttrTree node.
"""
level, lines = cls_or_slf.node_info(node, attrpath, attrpaths, siblings, level, value_dims)
a... |
Given a node return relevant information. | def node_info(cls_or_slf, node, attrpath, attrpaths, siblings, level, value_dims):
"""
Given a node, return relevant information.
"""
opts = None
if hasattr(node, 'children'):
(lvl, lines) = (level, [(level, cls_or_slf.component_type(node))])
opts = cls_or... |
Return the information summary for an Element. This consists of the dotted name followed by an value dimension names. | def element_info(cls_or_slf, node, siblings, level, value_dims):
"""
Return the information summary for an Element. This consists
of the dotted name followed by an value dimension names.
"""
info = cls_or_slf.component_type(node)
if len(node.kdims) >= 1:
info ... |
Split a Path type containing a single NaN separated path into multiple subpaths. | def split_path(path):
"""
Split a Path type containing a single NaN separated path into
multiple subpaths.
"""
path = path.split(0, 1)[0]
values = path.dimension_values(0)
splits = np.concatenate([[0], np.where(np.isnan(values))[0]+1, [None]])
subpaths = []
data = PandasInterface.as_... |
Given a 2D selection consisting of slices/ coordinates a SheetCoordinateSystem and the shape of the array returns a new BoundingBox representing the sliced region. | def compute_slice_bounds(slices, scs, shape):
"""
Given a 2D selection consisting of slices/coordinates, a
SheetCoordinateSystem and the shape of the array returns a new
BoundingBox representing the sliced region.
"""
xidx, yidx = slices
ys, xs = shape
l, b, r, t = scs.bounds.lbrt()
... |
Aggregation function to get the first non - zero value. | def reduce_fn(x):
"""
Aggregation function to get the first non-zero value.
"""
values = x.values if pd and isinstance(x, pd.Series) else x
for v in values:
if not is_nan(v):
return v
return np.NaN |
Lay out nodes on a circle and add node index. | def circular_layout(nodes):
"""
Lay out nodes on a circle and add node index.
"""
N = len(nodes)
if not N:
return ([], [], [])
circ = np.pi/N*np.arange(N)*2
x = np.cos(circ)
y = np.sin(circ)
return (x, y, nodes) |
Compute quadratic bezier spline given start and end coordinate and two control points. | def quadratic_bezier(start, end, c0=(0, 0), c1=(0, 0), steps=50):
"""
Compute quadratic bezier spline given start and end coordinate and
two control points.
"""
steps = np.linspace(0, 1, steps)
sx, sy = start
ex, ey = end
cx0, cy0 = c0
cx1, cy1 = c1
xs = ((1-steps)**3*sx + 3*((1-... |
Given a Graph element containing abstract edges compute edge segments directly connecting the source and target nodes. This operation depends on pandas and is a lot faster than the pure NumPy equivalent. | def connect_edges_pd(graph):
"""
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation depends on pandas and is a lot faster than the pure
NumPy equivalent.
"""
edges = graph.dframe()
edges.index.name = 'grap... |
Given a Graph element containing abstract edges compute edge segments directly connecting the source and target nodes. This operation just uses internal HoloViews operations and will be a lot slower than the pandas equivalent. | def connect_edges(graph):
"""
Given a Graph element containing abstract edges compute edge
segments directly connecting the source and target nodes. This
operation just uses internal HoloViews operations and will be a
lot slower than the pandas equivalent.
"""
paths = []
for start, end ... |
Get the coordinates of the 2D aggregate maintaining the correct sorting order. | def _get_coords(self, obj):
"""
Get the coordinates of the 2D aggregate, maintaining the correct
sorting order.
"""
xdim, ydim = obj.dimensions(label=True)[:2]
xcoords = obj.dimension_values(xdim, False)
ycoords = obj.dimension_values(ydim, False)
# Deter... |
Generates a gridded Dataset from a column - based dataset and lists of xcoords and ycoords | def _aggregate_dataset(self, obj, xcoords, ycoords):
"""
Generates a gridded Dataset from a column-based dataset and
lists of xcoords and ycoords
"""
dim_labels = obj.dimensions(label=True)
vdims = obj.dimensions()[2:]
xdim, ydim = dim_labels[:2]
shape = (... |
Generates a categorical 2D aggregate by inserting NaNs at all cross - product locations that do not already have a value assigned. Returns a 2D gridded Dataset object. | def _process(self, obj, key=None):
"""
Generates a categorical 2D aggregate by inserting NaNs at all
cross-product locations that do not already have a value assigned.
Returns a 2D gridded Dataset object.
"""
if isinstance(obj, Dataset) and obj.interface.gridded:
... |
Initializes a new plot object with the last available frame. | def initialize_plot(self, ranges=None, plot=None, plots=None, source=None):
"""
Initializes a new plot object with the last available frame.
"""
# Get element key and ranges for frame
element = self.hmap.last
key = self.keys[-1]
self.current_frame = element
... |
Updates an existing plot with data corresponding to the key. | def update_frame(self, key, ranges=None, plot=None):
"""
Updates an existing plot with data corresponding
to the key.
"""
element = self._get_frame(key)
self._get_title_div(key, '12pt')
# Cache frame object id to skip updating data if unchanged
previous_i... |
The set of samples available along a particular dimension. | def dimension_values(self, dim, expanded=True, flat=True):
"""
The set of samples available along a particular dimension.
"""
dim_idx = self.get_dimension_index(dim)
if not expanded and dim_idx == 0:
return np.array(range(self.data.shape[1]))
elif not expanded... |
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(self, samples=[], **sample_values):
"""
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
... |
Reduces the Raster using functions provided via the kwargs where the keyword is the dimension to be reduced. Optionally a label_prefix can be provided to prepend to the result Element label. | def reduce(self, dimensions=None, function=None, **reduce_map):
"""
Reduces the Raster using functions provided via the
kwargs, where the keyword is the dimension to be reduced.
Optionally a label_prefix can be provided to prepend to
the result Element label.
"""
... |
Returns a clone of the object with matching parameter values containing the specified args and kwargs. | def clone(self, data=None, shared_data=True, new_type=None, link=True,
*args, **overrides):
"""
Returns a clone of the object with matching parameter values
containing the specified args and kwargs.
If shared_data is set to True and no data explicitly supplied,
the... |
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 ) may be supplied which will ens... | 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... |
Allows sampling of an Image as an iterator of coordinates matching the key dimensions returning a new object containing just the selected samples. Alternatively may supply kwargs to sample a coordinate on an object. On an Image the coordinates are continuously indexed and will always snap to the nearest coordinate. | def sample(self, samples=[], **kwargs):
"""
Allows sampling of an Image as an iterator of coordinates
matching the key dimensions, returning a new object containing
just the selected samples. Alternatively may supply kwargs to
sample a coordinate on an object. On an Image the coo... |
Given a single coordinate or multiple coordinates as a tuple or list of tuples or keyword arguments matching the dimension closest will find the closest actual x/ y coordinates. | def closest(self, coords=[], **kwargs):
"""
Given a single coordinate or multiple coordinates as
a tuple or list of tuples or keyword arguments matching
the dimension closest will find the closest actual x/y
coordinates.
"""
if kwargs and coords:
raise... |
Returns an raster element or raw numpy array from a PNG image file using matplotlib. | def load_image(cls, filename, height=1, array=False, bounds=None, bare=False, **kwargs):
"""
Returns an raster element or raw numpy array from a PNG image
file, using matplotlib.
The specified height determines the bounds of the raster
object in sheet coordinates: by default the... |
Conversion from HSV to RGB. | def rgb(self):
"""
Conversion from HSV to RGB.
"""
coords = tuple(self.dimension_values(d, expanded=False)
for d in self.kdims)
data = [self.dimension_values(d, flat=False)
for d in self.vdims]
hsv = self.hsv_to_rgb(*data[:3])
... |
Converts a QuadMesh into a TriMesh. | def trimesh(self):
"""
Converts a QuadMesh into a TriMesh.
"""
# Generate vertices
xs = self.interface.coords(self, 0, edges=True)
ys = self.interface.coords(self, 1, edges=True)
if xs.ndim == 1:
if np.all(xs[1:] < xs[:-1]):
xs = xs[::... |
Fixed version of IPyton. completer. completions_sorting_key | def completions_sorting_key(cls, word):
"Fixed version of IPyton.completer.completions_sorting_key"
prio1, prio2 = 0, 0
if word.startswith('__'): prio1 = 2
elif word.startswith('_'): prio1 = 1
if word.endswith('='): prio1 = -1
if word.startswith('%%'):
if... |
Finds the list of resources from the keyword parameters and pops them out of the params dictionary. | def _get_resources(self, args, params):
"""
Finds the list of resources from the keyword parameters and pops
them out of the params dictionary.
"""
resources = []
disabled = []
for resource in ['holoviews'] + list(Store.renderers.keys()):
if resource i... |
Displays javascript and CSS to initialize HoloViews widgets. | def load_hvjs(cls, logo=False, bokeh_logo=False, mpl_logo=False, plotly_logo=False,
JS=True, message='HoloViewsJS successfully loaded.'):
"""
Displays javascript and CSS to initialize HoloViews widgets.
"""
import jinja2
# Evaluate load_notebook.html template wi... |
Generates a docstring that can be used to enable tab - completion of resources. | def tab_completion_docstring(self_or_cls):
"""
Generates a docstring that can be used to enable tab-completion
of resources.
"""
elements = ['%s=Boolean' %k for k in list(Store.renderers.keys())]
for name, p in self_or_cls.params().items():
param_type = p.__cl... |
Get the dictionary of valid completions | def setup_completer(cls):
"Get the dictionary of valid completions"
try:
for element in Store.options().keys():
options = Store.options()['.'.join(element)]
plotkws = options['plot'].allowed_keywords
stylekws = options['style'].allowed_keywords... |
Supply the appropriate key in Store. options and supply suggestions for further completion. | def dotted_completion(cls, line, sorted_keys, compositor_defs):
"""
Supply the appropriate key in Store.options and supply
suggestions for further completion.
"""
completion_key, suggestions = None, []
tokens = [t for t in reversed(line.replace('.', ' ').split())]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.