How to use the adaptive.notebook_integration.ensure_holoviews function in adaptive

To help you get started, we’ve selected a few adaptive 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 python-adaptive / adaptive / adaptive / learner / new_learnerND.py View on Github external
def _plot_1d(self):
        assert isinstance(self.domain, Interval)
        hv = ensure_holoviews()

        xs, ys = zip(*sorted(self.data.items())) if self.data else ([], [])
        if self.vdim == 1:
            p = hv.Path([]) * hv.Scatter((xs, ys))
        else:
            p = hv.Path((xs, ys)) * hv.Scatter([])

        # Plot with 5% empty margins such that the boundary points are visible
        a, b = self.domain.bounds
        margin = 0.05 * (b - a)
        plot_bounds = (a - margin, b + margin)

        return p.redim(x=dict(range=plot_bounds))
github python-adaptive / adaptive / adaptive / learner / new_learnerND.py View on Github external
def _plot_nd(self, n=None, tri_alpha=0):
        # XXX: Copied from LearnerND. At the moment we reach deep into internal
        #      datastructures of self.domain. We should see what data we need and
        #      add APIs to 'Domain' to support this.
        hv = ensure_holoviews()
        if self.vdim > 1:
            raise NotImplementedError(
                "holoviews currently does not support", "3D surface plots in bokeh."
            )
        if self.ndim != 2:
            raise NotImplementedError(
                "Only 2D plots are implemented: You can "
                "plot a 2D slice with 'plot_slice'."
            )
        x, y = self.domain.bounding_box
        lbrt = x[0], y[0], x[1], y[1]

        if len(self.data) >= 4:
            if n is None:
                # Calculate how many grid points are needed.
                # factor from A=√3/4 * a² (equilateral triangle)
github python-adaptive / adaptive / adaptive / learner / learnerND.py View on Github external
The value of the function at which you would like to see
            the isoline.
        n : int
            The number of boxes in the interpolation grid along each axis.
            This is passed to `plot`.
        tri_alpha : float
            The opacity of the overlaying triangulation. This is passed
            to `plot`.

        Returns
        -------
        `holoviews.core.Overlay`
            The plot of the isoline(s). This overlays a `plot` with a
            `holoviews.element.Path`.
        """
        hv = ensure_holoviews()
        if n == -1:
            plot = hv.Path([])
        else:
            plot = self.plot(n=n, tri_alpha=tri_alpha)

        if isinstance(level, Iterable):
            for l in level:
                plot = plot * self.plot_isoline(level=l, n=-1)
            return plot

        vertices, lines = self._get_iso(level, which="line")
        paths = [[vertices[i], vertices[j]] for i, j in lines]
        contour = hv.Path(paths)

        contour_opts = dict(color="black")
        contour = contour.opts(style=contour_opts)
github python-adaptive / adaptive / adaptive / learner / learnerND.py View on Github external
def plot(self, n=None, tri_alpha=0):
        """Plot the function we want to learn, only works in 2D.

        Parameters
        ----------
        n : int
            the number of boxes in the interpolation grid along each axis
        tri_alpha : float (0 to 1)
            Opacity of triangulation lines
        """
        hv = ensure_holoviews()
        if self.vdim > 1:
            raise NotImplementedError(
                "holoviews currently does not support", "3D surface plots in bokeh."
            )
        if self.ndim != 2:
            raise NotImplementedError(
                "Only 2D plots are implemented: You can "
                "plot a 2D slice with 'plot_slice'."
            )
        x, y = self._bbox
        lbrt = x[0], y[0], x[1], y[1]

        if len(self.data) >= 4:
            if n is None:
                # Calculate how many grid points are needed.
                # factor from A=√3/4 * a² (equilateral triangle)
github python-adaptive / adaptive / adaptive / learner / integrator_learner.py View on Github external
def plot(self):
        hv = ensure_holoviews()
        ivals = sorted(self.ivals, key=attrgetter("a"))
        if not self.data:
            return hv.Path([])
        xs, ys = zip(*[(x, y) for ival in ivals for x, y in sorted(ival.data.items())])
        return hv.Path((xs, ys))
github python-adaptive / adaptive / adaptive / learner / balancing_learner.py View on Github external
plotter : callable, optional
            A function that takes the learner as a argument and returns a
            holoviews object. By default ``learner.plot()`` will be called.
        dynamic : bool, default True
            Return a `holoviews.core.DynamicMap` if True, else a
            `holoviews.core.HoloMap`. The `~holoviews.core.DynamicMap` is
            rendered as the sliders change and can therefore not be exported
            to html. The `~holoviews.core.HoloMap` does not have this problem.

        Returns
        -------
        dm : `holoviews.core.DynamicMap` (default) or `holoviews.core.HoloMap`
             A `DynamicMap` ``(dynamic=True)`` or `HoloMap`
             ``(dynamic=False)`` with sliders that are defined by `cdims`.
        """
        hv = ensure_holoviews()
        cdims = cdims or self._cdims_default

        if cdims is None:
            cdims = [{"i": i} for i in range(len(self.learners))]
        elif not isinstance(cdims[0], dict):
            # Normalize the format
            keys, values_list = cdims
            cdims = [dict(zip(keys, values)) for values in values_list]

        mapping = {tuple(_cdims.values()): l for l, _cdims in zip(self.learners, cdims)}

        d = defaultdict(list)
        for _cdims in cdims:
            for k, v in _cdims.items():
                d[k].append(v)
github python-adaptive / adaptive / adaptive / learner / learnerND.py View on Github external
def plot_slice(self, cut_mapping, n=None):
        """Plot a 1D or 2D interpolated slice of a N-dimensional function.

        Parameters
        ----------
        cut_mapping : dict (int → float)
            for each fixed dimension the value, the other dimensions
            are interpolated. e.g. ``cut_mapping = {0: 1}``, so from
            dimension 0 ('x') to value 1.
        n : int
            the number of boxes in the interpolation grid along each axis
        """
        hv = ensure_holoviews()
        plot_dim = self.ndim - len(cut_mapping)
        if plot_dim == 1:
            if not self.data:
                return hv.Scatter([]) * hv.Path([])
            elif self.vdim > 1:
                raise NotImplementedError(
                    "multidimensional output not yet" " supported by `plot_slice`"
                )
            n = n or 201
            values = [
                cut_mapping.get(i, np.linspace(*self._bbox[i], n))
                for i in range(self.ndim)
            ]
            ind = next(i for i in range(self.ndim) if i not in cut_mapping)
            x = values[ind]
            y = self._ip()(*values)
github python-adaptive / adaptive / adaptive / learner / learner1D.py View on Github external
def plot(self, *, scatter_or_line="scatter"):
        """Returns a plot of the evaluated data.

        Parameters
        ----------
        scatter_or_line : str, default: "scatter"
            Plot as a scatter plot ("scatter") or a line plot ("line").

        Returns
        -------
        plot : `holoviews.Overlay`
            Plot of the evaluated data.
        """
        if scatter_or_line not in ("scatter", "line"):
            raise ValueError("scatter_or_line must be 'scatter' or 'line'")
        hv = ensure_holoviews()

        xs, ys = zip(*sorted(self.data.items())) if self.data else ([], [])
        if scatter_or_line == "scatter":
            if self.vdim == 1:
                plots = [hv.Scatter((xs, ys))]
            else:
                plots = [hv.Scatter((xs, _ys)) for _ys in np.transpose(ys)]
        else:
            plots = [hv.Path((xs, ys))]

        # Put all plots in an Overlay because a DynamicMap can't handle changing
        # datatypes, e.g. when `vdim` isn't yet known and the live_plot is running.
        p = hv.Overlay(plots)
        # Plot with 5% empty margins such that the boundary points are visible
        margin = 0.05 * (self.bounds[1] - self.bounds[0])
        plot_bounds = (self.bounds[0] - margin, self.bounds[1] + margin)