How to use the holoviews.core.util function in holoviews

To help you get started, we’ve selected a few holoviews examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github holoviz / holoviews / holoviews / plotting / mpl / path.py View on Github external
def get_data(self, element, ranges, style):
        with abbreviated_exception():
            style = self._apply_transforms(element, ranges, style)

        cdim = element.get_dimension(self.color_index)
        style_mapping = any(True for v in style.values() if isinstance(v, util.arraylike_types))
        dims = element.kdims
        xdim, ydim = dims
        generic_dt_format = Dimension.type_formatters[np.datetime64]
        paths, cvals, dims = [], [], {}
        for path in element.split(datatype='columns'):
            xarr, yarr = path[xdim.name], path[ydim.name]
            if util.isdatetime(xarr):
                dt_format = Dimension.type_formatters.get(type(xarr[0]), generic_dt_format)
                xarr = date2num(xarr)
                dims[0] = xdim(value_format=DateFormatter(dt_format))
            if util.isdatetime(yarr):
                dt_format = Dimension.type_formatters.get(type(yarr[0]), generic_dt_format)
                yarr = date2num(yarr)
                dims[1] = ydim(value_format=DateFormatter(dt_format))
            arr = np.column_stack([xarr, yarr])
            if not (cdim or style_mapping):
                paths.append(arr)
                continue
            length = len(xarr)
            for (s1, s2) in zip(range(length-1), range(1, length+1)):
                if cdim:
                    cvals.append(path[cdim.name])
                paths.append(arr[s1:s2+1])
github holoviz / holoviews / holoviews / core / spaces.py View on Github external
def _initial_key(self):
        """
        Construct an initial key for based on the lower range bounds or
        values on the key dimensions.
        """
        key = []
        undefined = []
        stream_params = set(util.stream_parameters(self.streams))
        for kdim in self.kdims:
            if str(kdim) in stream_params:
                key.append(None)
            elif kdim.default:
                key.append(kdim.default)
            elif kdim.values:
                if all(util.isnumeric(v) for v in kdim.values):
                    key.append(sorted(kdim.values)[0])
                else:
                    key.append(kdim.values[0])
            elif kdim.range[0] is not None:
                key.append(kdim.range[0])
            else:
                undefined.append(kdim)
        if undefined:
            msg = ('Dimension(s) {undefined_dims} do not specify range or values needed '
github holoviz / holoviews / holoviews / core / data / __init__.py View on Github external
# If a 1D cross-section of 2D space return Curve
            if self.interface.gridded and self.ndims == 2 and len(dims) == 1:
                new_type = Curve
                kdims = [self.get_dimension(kd) for kd in dims]
            else:
                new_type = Table
                kdims = self.kdims

            if np.isscalar(selection):
                selection = [samples[0]+(selection,)]
            else:
                reindexed = selection.clone(new_type=Dataset).reindex(kdims)
                selection = tuple(reindexed.columns(kdims+self.vdims).values())

            datatype = list(util.unique_iterator(self.datatype+['dataframe', 'dict']))
            return self.clone(selection, kdims=kdims, new_type=new_type,
                              datatype=datatype)

        lens = set(len(util.wrap_tuple(s)) for s in samples)
        if len(lens) > 1:
            raise IndexError('Sample coordinates must all be of the same length.')

        if closest:
            try:
                samples = self.closest(samples)
            except NotImplementedError:
                pass
        samples = [util.wrap_tuple(s) for s in samples]
        return self.clone(self.interface.sample(self, samples), new_type=Table)
github holoviz / holoviews / holoviews / plotting / mpl / element.py View on Github external
elif el_min < vmin:
                self.cbar_extend = 'min'
            elif el_max > vmax:
                self.cbar_extend = 'max'
            else:
                self.cbar_extend = 'neither'

        # Define special out-of-range colors on colormap
        colors = {}
        for k, val in self.clipping_colors.items():
            if val == 'transparent':
                colors[k] = {'color': 'w', 'alpha': 0}
            elif isinstance(val, tuple):
                colors[k] = {'color': val[:3],
                             'alpha': val[3] if len(val) > 3 else 1}
            elif isinstance(val, util.basestring):
                color = val
                alpha = 1
                if color.startswith('#') and len(color) == 9:
                    alpha = int(color[-2:], 16)/255.
                    color = color[:-2]
                colors[k] = {'color': color, 'alpha': alpha}

        if not isinstance(cmap, mpl_colors.Colormap):
            if isinstance(cmap, dict):
                # The palette needs to correspond to the map's limits (vmin/vmax). So use the same
                # factors as in the map's clim computation above.
                range_key = dim_range_key(vdim)
                if range_key in ranges and 'factors' in ranges[range_key]:
                    factors = ranges[range_key]['factors']
                else:
                    factors = util.unique_array(values)
github holoviz / holoviews / holoviews / core / data / iris.py View on Github external
def coords(cls, dataset, dim, ordered=False, expanded=False):
        dim = dataset.get_dimension(dim, strict=True)
        if expanded:
            return util.expand_grid_coords(dataset, dim.name)
        data = dataset.data.coords(dim.name)[0].points
        if ordered and np.all(data[1:] < data[:-1]):
            data = data[::-1]
        return data
github holoviz / holoviews / holoviews / core / accessors.py View on Github external
clone (bool, optional): Whether to clone object
                Options can be applied in place with clone=False
            **kwargs: Keywords of options
                Set of options to apply to the object

        For backwards compatibility, this method also supports the
        option group semantics now offered by the hv.opts.apply_groups
        utility. This usage will be deprecated and for more
        information see the apply_options_type docstring.

        Returns:
            Returns the object or a clone with the options applied
        """
        if self._mode is None:
            apply_groups, _, _ = util.deprecated_opts_signature(args, kwargs)
            if apply_groups and util.config.future_deprecations:
                msg = ("Calling the .opts method with options broken down by options "
                       "group (i.e. separate plot, style and norm groups) is deprecated. "
                       "Use the .options method converting to the simplified format "
                       "instead or use hv.opts.apply_groups for backward compatibility.")
                param.main.warning(msg)

        return self._dispatch_opts( *args, **kwargs)
github holoviz / holoviews / holoviews / core / data / pandas.py View on Github external
def concat(cls, datasets, dimensions, vdims):
        dataframes = []
        for key, ds in datasets:
            data = ds.data.copy()
            for d, k in zip(dimensions, key):
                data[d.name] = k
            dataframes.append(data)
        kwargs = dict(sort=False) if util.pandas_version >= '0.23.0' else {}
        return pd.concat(dataframes, **kwargs)
github holoviz / holoviews / holoviews / core / data.py View on Github external
def sort(cls, columns, by=[]):
        data = columns.data
        if len(by) == 1:
            sorting = cls.values(columns, by[0]).argsort()
        else:
            arrays = [columns.dimension_values(d) for d in by]
            sorting = util.arglexsort(arrays)
        return OrderedDict([(d, v[sorting]) for d, v in columns.data.items()])
github holoviz / holoviews / holoviews / util / __init__.py View on Github external
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 = zip(*hmap.data.keys())
        params = util.get_param_values(hmap)
        kdims = [d(values=list(util.unique_iterator(values))) for d, values in
                 zip(hmap.kdims, dim_values)]
        return DynamicMap(dynamic_fn, streams=streams, **dict(params, kdims=kdims))
github holoviz / holoviews / holoviews / streams.py View on Github external
def _set_stream_parameters(self, **kwargs):
        """
        Sets the stream parameters which are expected to be declared
        constant.
        """
        with util.disable_constant(self):
            self.set_param(**kwargs)