Skip to content

adaptive.LearnerND

LearnerND

LearnerND(func, bounds, loss_per_simplex=None, *, anisotropic=False, triangulation_backend='auto')

Bases: BaseLearner

Learns and predicts a function 'f: ℝ^N → ℝ^M'.

Parameters:

Name Type Description Default
func

The function to learn. Must take a tuple of N real parameters and return a real number or an arraylike of length M.

required
bounds list of 2-tuples or scipy.spatial.ConvexHull

A list [(a_1, b_1), (a_2, b_2), ..., (a_n, b_n)] containing bounds, one pair per dimension. Or a ConvexHull that defines the boundary of the domain.

required
loss_per_simplex callable

A function that returns the loss for a simplex. If not provided, then a default is used, which uses the deviation from a linear estimate, as well as triangle area, to determine the loss.

None
anisotropic bool

If True, the triangulation is stretched along the local gradient when choosing new points. Only works with scalar output.

False
triangulation_backend str or type

Which triangulation implementation to use: "auto" (default, prefers the optional Rust-accelerated adaptive-triangulation <https://github.com/python-adaptive/adaptive-triangulation>_ package when it is installed), "python", "rust", or a Triangulation-compatible class.

'auto'

Attributes:

Name Type Description
data dict

Sampled points and values.

points numpy array

Coordinates of the currently known points

values numpy array

The values of each of the known points

pending_points set

Points that still have to be evaluated.

Notes

The sample points are chosen by estimating the point where the gradient is maximal. This is based on the currently known points.

In practice, this sampling protocol results to sparser sampling of flat regions, and denser sampling of regions where the function has a high gradient, which is useful if the function is expensive to compute.

This sampling procedure is not fast, so to benefit from it, your function needs to be slow enough to compute.

This class keeps track of all known points. It triangulates these points and with every simplex it associates a loss. Then if you request points that you will compute in the future, it will subtriangulate a real simplex with the pending points inside it and distribute the loss among it's children based on volume.

Source code in adaptive/learner/learnerND.py
def __init__(
    self,
    func,
    bounds,
    loss_per_simplex=None,
    *,
    anisotropic=False,
    triangulation_backend="auto",
):
    self._triangulation_class = resolve_triangulation_class(triangulation_backend)
    self._vdim = None
    # Prefer the Rust implementation of the default loss when the Rust
    # backend is active; it computes the same embedded simplex volume.
    self.loss_per_simplex = loss_per_simplex or rust_default_loss or default_loss

    if hasattr(self.loss_per_simplex, "nth_neighbors"):
        if self.loss_per_simplex.nth_neighbors > 1:
            raise NotImplementedError(
                "The provided loss function wants "
                "next-nearest neighboring simplices for the loss computation, "
                "this feature is not yet implemented, either use "
                "nth_neightbors = 0 or 1"
            )
        self.nth_neighbors = self.loss_per_simplex.nth_neighbors
    else:
        self.nth_neighbors = 0

    self.data = OrderedDict()
    self.pending_points = set()

    self.bounds = bounds
    if isinstance(bounds, scipy.spatial.ConvexHull):
        hull_points = bounds.points[bounds.vertices]
        self._bounds_points = sorted(map(tuple, hull_points))
        self._bbox = tuple(zip(hull_points.min(axis=0), hull_points.max(axis=0)))
        self._interior = scipy.spatial.Delaunay(self._bounds_points)
    else:
        self._bounds_points = sorted(map(tuple, itertools.product(*bounds)))
        self._bbox = tuple(tuple(map(float, b)) for b in bounds)
        self._interior = None

    self.ndim = len(self._bbox)

    self.function = func
    self._tri = None
    self._losses = {}

    self._pending_to_simplex = {}  # vertex → simplex

    # triangulation of the pending points inside a specific simplex
    self._subtriangulations = {}  # simplex → triangulation

    # scale to unit hypercube
    # for the input
    self._transform = np.linalg.inv(np.diag(np.diff(self._bbox).flat))
    # for the output
    self._min_value = None
    self._max_value = None
    self._old_scale = None
    self._output_multiplier = (
        1  # If we do not know anything, do not scale the values
    )
    self._recompute_losses_factor = 1.1

    # create a private random number generator with fixed seed
    self._random = random.Random(1)
    self.anisotropic = anisotropic

    # all real triangles that have not been subdivided and the pending
    # triangles heap of tuples (-loss, real simplex, sub_simplex or None)

    # _simplex_queue is a heap of tuples (-loss, real_simplex, sub_simplex)
    # It contains all real and pending simplices except for real simplices
    # that have been subdivided.
    # _simplex_queue may contain simplices that have been deleted, this is
    #  because deleting those items from the heap is an expensive operation,
    # so when popping an item, you should check that the simplex that has
    # been returned has not been deleted. This checking is done by
    # _pop_highest_existing_simplex
    self._simplex_queue = SortedKeyList(key=_simplex_evaluation_priority)

loss_per_simplex instance-attribute

loss_per_simplex = loss_per_simplex or rust_default_loss or default_loss

nth_neighbors instance-attribute

nth_neighbors = self.loss_per_simplex.nth_neighbors

data instance-attribute

data = OrderedDict()

pending_points instance-attribute

pending_points = set()

bounds instance-attribute

bounds = bounds

ndim instance-attribute

ndim = len(self._bbox)

function instance-attribute

function = func

anisotropic instance-attribute

anisotropic = anisotropic

npoints property

npoints

Number of evaluated points.

vdim property

vdim

Length of the output of learner.function. If the output is unsized (when it's a scalar) then vdim = 1.

As long as no data is known vdim = 1.

bounds_are_done property

bounds_are_done

tri property

tri

An adaptive.learner.triangulation.Triangulation instance with all the points of the learner.

values property

values

Get the values from data as a numpy array.

points property

points

Get the points from data as a numpy array.

new

new() -> LearnerND

Create a new learner with the same function and bounds.

Source code in adaptive/learner/learnerND.py
def new(self) -> LearnerND:
    """Create a new learner with the same function and bounds."""
    return LearnerND(
        self.function,
        self.bounds,
        self.loss_per_simplex,
        anisotropic=self.anisotropic,
        triangulation_backend=self._triangulation_class,
    )

to_numpy

to_numpy()

Data as NumPy array of size (npoints, dim+vdim), where dim is the size of the input dimension and vdim is the length of the return value of learner.function.

Source code in adaptive/learner/learnerND.py
def to_numpy(self):
    """Data as NumPy array of size ``(npoints, dim+vdim)``, where ``dim`` is the
    size of the input dimension and ``vdim`` is the length of the return value
    of ``learner.function``."""
    return np.array([(*p, *np.atleast_1d(v)) for p, v in sorted(self.data.items())])

to_dataframe

to_dataframe(with_default_function_args: bool = True, function_prefix: str = 'function.', point_names: tuple[str, ...] = ('x', 'y', 'z'), value_name: str = 'value') -> DataFrame

Return the data as a pandas.DataFrame.

Parameters:

Name Type Description Default
with_default_function_args bool

Include the learner.function's default arguments as a column, by default True

True
function_prefix str

Prefix to the learner.function's default arguments' names, by default "function."

'function.'
point_names tuple[str, ...]

Names of the input points, should be the same length as number of input parameters by default ("x", "y", "z" )

('x', 'y', 'z')
value_name str

Name of the output value, by default "value"

'value'

Returns:

Type Description
DataFrame

Raises:

Type Description
ImportError

If pandas is not installed.

Source code in adaptive/learner/learnerND.py
def to_dataframe(  # type: ignore[override]
    self,
    with_default_function_args: bool = True,
    function_prefix: str = "function.",
    point_names: tuple[str, ...] = ("x", "y", "z"),
    value_name: str = "value",
) -> pandas.DataFrame:
    """Return the data as a `pandas.DataFrame`.

    Parameters
    ----------
    with_default_function_args : bool, optional
        Include the ``learner.function``'s default arguments as a
        column, by default True
    function_prefix : str, optional
        Prefix to the ``learner.function``'s default arguments' names,
        by default "function."
    point_names : tuple[str, ...], optional
        Names of the input points, should be the same length as number
        of input parameters by default ("x", "y", "z" )
    value_name : str, optional
        Name of the output value, by default "value"

    Returns
    -------
    pandas.DataFrame

    Raises
    ------
    ImportError
        If `pandas` is not installed.
    """
    if not with_pandas:
        raise ImportError("pandas is not installed.")
    if len(point_names) != self.ndim:
        raise ValueError(
            f"point_names ({point_names}) should have the"
            f" same length as learner.ndims ({self.ndim})"
        )
    data = [(*x, y) for x, y in self.data.items()]
    df = pandas.DataFrame(data, columns=[*point_names, value_name])
    df.attrs["inputs"] = list(point_names)
    df.attrs["output"] = value_name
    if with_default_function_args:
        assign_defaults(self.function, df, function_prefix)
    return df

load_dataframe

load_dataframe(df: DataFrame, with_default_function_args: bool = True, function_prefix: str = 'function.', point_names: tuple[str, ...] = ('x', 'y', 'z'), value_name: str = 'value')

Load data from a pandas.DataFrame.

If with_default_function_args is True, then learner.function's default arguments are set (using functools.partial) from the values in the pandas.DataFrame.

Parameters:

Name Type Description Default
df DataFrame

The data to load.

required
with_default_function_args bool

The with_default_function_args used in to_dataframe(), by default True

True
function_prefix str

The function_prefix used in to_dataframe, by default "function."

'function.'
point_names str

The point_names used in to_dataframe, by default ("x", "y", "z")

('x', 'y', 'z')
value_name str

The value_name used in to_dataframe, by default "value"

'value'
Source code in adaptive/learner/learnerND.py
def load_dataframe(  # type: ignore[override]
    self,
    df: pandas.DataFrame,
    with_default_function_args: bool = True,
    function_prefix: str = "function.",
    point_names: tuple[str, ...] = ("x", "y", "z"),
    value_name: str = "value",
):
    """Load data from a `pandas.DataFrame`.

    If ``with_default_function_args`` is True, then ``learner.function``'s
    default arguments are set (using `functools.partial`) from the values
    in the `pandas.DataFrame`.

    Parameters
    ----------
    df : pandas.DataFrame
        The data to load.
    with_default_function_args : bool, optional
        The ``with_default_function_args`` used in ``to_dataframe()``,
        by default True
    function_prefix : str, optional
        The ``function_prefix`` used in ``to_dataframe``, by default "function."
    point_names : str, optional
        The ``point_names`` used in ``to_dataframe``, by default ("x", "y", "z")
    value_name : str, optional
        The ``value_name`` used in ``to_dataframe``, by default "value"
    """
    self.tell_many(df[list(point_names)].values, df[value_name].values)
    if with_default_function_args:
        self.function = partial_function_from_dataframe(
            self.function, df, function_prefix
        )

tell

tell(point, value)
Source code in adaptive/learner/learnerND.py
def tell(self, point, value):
    point = tuple(point)
    if point in self.data:
        return  # we already know about the point

    if value is None:
        return self.tell_pending(point)

    self.pending_points.discard(point)
    tri = self.tri
    self.data[point] = value

    if not self.inside_bounds(point):
        return

    self._update_range(value)
    if tri is not None:
        simplex = self._pending_to_simplex.get(point)
        if simplex is not None and not self._simplex_exists(simplex):
            simplex = None
        # Keep Bowyer-Watson in the globally scaled coordinates. The
        # anisotropic per-simplex transform is only used for point
        # selection, not for cavity construction.
        to_delete, to_add = tri.add_point(point, simplex, transform=self._transform)
        self._update_losses(to_delete, to_add)

get_local_transform_matrix

get_local_transform_matrix(simplex)
Source code in adaptive/learner/learnerND.py
def get_local_transform_matrix(self, simplex):
    scale = self._transform

    if simplex is None or self.tri is None or not self.anisotropic:
        return scale

    neighbors = set.union(*[self.tri.vertex_to_simplices[i] for i in simplex])
    indices = set.union(set(), *neighbors)

    points = np.array([self.points[i] for i in indices])
    values = [self.data[tuple(p)] for p in points]

    if isinstance(values[0], Iterable):
        raise ValueError("Anisotropic learner only works with 1D output")

    # Do a linear least square fit
    # A x = B, find x
    points = points @ scale
    ones = np.ones((len(points), 1))
    A = np.hstack((points, ones))
    B = np.array(values, dtype=float)
    fit = np.linalg.lstsq(A, B, rcond=None)[0]
    *gradient, _constant = fit
    # we do not need the constant, only the gradient

    # gradient is a vector of the amount of the slope in each direction
    magnitude = np.linalg.norm(gradient)

    if np.isclose(magnitude, 0):
        return scale  # there is no noticable gradient

    # Make it a 2d numpy array and normalise it.
    gradient = np.array([gradient], dtype=float) / magnitude
    projection_matrix = gradient.T @ gradient
    identity = np.eye(self.ndim)

    factor = math.sqrt(magnitude**2 + 1) - 1

    scale_along_gradient = projection_matrix * factor + identity
    m = np.dot(scale_along_gradient, scale)
    return m.T

inside_bounds

inside_bounds(point)

Check whether a point is inside the bounds.

Source code in adaptive/learner/learnerND.py
def inside_bounds(self, point):
    """Check whether a point is inside the bounds."""
    if self._interior is not None:
        return self._interior.find_simplex(point, tol=1e-8) >= 0
    else:
        eps = 1e-8
        return all(
            (mn - eps) <= p <= (mx + eps) for p, (mn, mx) in zip(point, self._bbox)
        )

tell_pending

tell_pending(point, *, simplex=None)
Source code in adaptive/learner/learnerND.py
def tell_pending(self, point, *, simplex=None):
    point = tuple(point)
    if not self.inside_bounds(point):
        return

    self.pending_points.add(point)

    if self.tri is None:
        return

    for simpl in self._simplices_containing_point(point, simplex):
        _, to_add = self._add_pending_point_to_simplex(point, simpl)
        if to_add is None:
            continue
        self._update_subsimplex_losses(simpl, to_add)

ask

ask(n, tell_pending=True)

Chose points for learners.

Source code in adaptive/learner/learnerND.py
def ask(self, n, tell_pending=True):
    """Chose points for learners."""
    if not tell_pending:
        with restore(self):
            return self._ask_and_tell_pending(n)
    else:
        return self._ask_and_tell_pending(n)

loss

loss(real=True)
Source code in adaptive/learner/learnerND.py
@cache_latest
def loss(self, real=True):
    # XXX: compute pending loss if real == False
    losses = self._losses if self.tri is not None else {}
    return max(losses.values()) if losses else float("inf")

remove_unfinished

remove_unfinished()
Source code in adaptive/learner/learnerND.py
def remove_unfinished(self):
    # XXX: implement this method
    self.pending_points = set()
    self._subtriangulations = {}
    self._pending_to_simplex = {}

plot

plot(n=None, tri_alpha=0)

Plot the function we want to learn, only works in 2D.

Parameters:

Name Type Description Default
n int

the number of boxes in the interpolation grid along each axis

None
tri_alpha float (0 to 1)

Opacity of triangulation lines

0
Source code in adaptive/learner/learnerND.py
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)
            scale_factor = np.product(np.diag(self._transform))
            a_sq = np.sqrt(np.min(self.tri.volumes()) * scale_factor)
            n = max(10, int(0.658 / a_sq))

        xs = ys = np.linspace(0, 1, n)
        xs = xs * (x[1] - x[0]) + x[0]
        ys = ys * (y[1] - y[0]) + y[0]
        z = self._ip()(xs[:, None], ys[None, :]).squeeze()

        im = hv.Image(np.rot90(z), bounds=lbrt)

        if tri_alpha:
            points = np.array(
                [self.tri.get_vertices(s) for s in self.tri.simplices]
            )
            points = np.pad(
                points[:, [0, 1, 2, 0], :],
                pad_width=((0, 0), (0, 1), (0, 0)),
                mode="constant",
                constant_values=np.nan,
            ).reshape(-1, 2)
            tris = hv.EdgePaths([points])
        else:
            tris = hv.EdgePaths([])
    else:
        im = hv.Image([], bounds=lbrt)
        tris = hv.EdgePaths([])
    return im.opts(cmap="viridis") * tris.opts(
        line_width=0.5, alpha=tri_alpha, tools=[]
    )

plot_slice

plot_slice(cut_mapping, n=None)

Plot a 1D or 2D interpolated slice of a N-dimensional function.

Parameters:

Name Type Description Default
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.

required
n int

the number of boxes in the interpolation grid along each axis

None
Source code in adaptive/learner/learnerND.py
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)
        p = hv.Path((x, y))

        # Plot with 5% margins such that the boundary points are visible
        margin = 0.05 / self._transform[ind, ind]
        plot_bounds = (x.min() - margin, x.max() + margin)
        return p.redim(x={"range": plot_bounds})

    elif plot_dim == 2:
        if self.vdim > 1:
            raise NotImplementedError(
                "holoviews currently does not support 3D surface plots in bokeh."
            )
        if n is None:
            # Calculate how many grid points are needed.
            # factor from A=√3/4 * a² (equilateral triangle)
            scale_factor = np.product(np.diag(self._transform))
            a_sq = np.sqrt(np.min(self.tri.volumes()) * scale_factor)
            n = max(10, int(0.658 / a_sq))

        xs = ys = np.linspace(0, 1, n)
        xys = [xs[:, None], ys[None, :]]
        values = [
            (
                cut_mapping[i]
                if i in cut_mapping
                else xys.pop(0) * (b[1] - b[0]) + b[0]
            )
            for i, b in enumerate(self._bbox)
        ]

        lbrt = [b for i, b in enumerate(self._bbox) if i not in cut_mapping]
        lbrt = np.reshape(lbrt, (2, 2)).T.flatten().tolist()

        if len(self.data) >= 4:
            z = self._ip()(*values).squeeze()
            im = hv.Image(np.rot90(z), bounds=lbrt)
        else:
            im = hv.Image([], bounds=lbrt)

        return im.opts(cmap="viridis")
    else:
        raise ValueError("Only 1 or 2-dimensional plots can be generated.")

plot_3D

plot_3D(with_triangulation=False, return_fig=False)

Plot the learner's data in 3D using plotly.

Does not work with the adaptive.notebook_integration.live_plot functionality.

Parameters:

Name Type Description Default
with_triangulation bool

Add the verticices to the plot.

False
return_fig bool

Return the plotly.graph_objs.Figure object instead of showing the rendered plot (default).

False

Returns:

Name Type Description
plot plotly.offline.iplot object

The 3D plot of learner.data.

Source code in adaptive/learner/learnerND.py
def plot_3D(self, with_triangulation=False, return_fig=False):
    """Plot the learner's data in 3D using plotly.

    Does *not* work with the
    `adaptive.notebook_integration.live_plot` functionality.

    Parameters
    ----------
    with_triangulation : bool, default: False
        Add the verticices to the plot.
    return_fig : bool, default: False
        Return the `plotly.graph_objs.Figure` object instead of showing
        the rendered plot (default).

    Returns
    -------
    plot : `plotly.offline.iplot` object
        The 3D plot of ``learner.data``.
    """
    plotly = ensure_plotly()

    plots = []

    vertices = self.tri.vertices
    if with_triangulation:
        Xe, Ye, Ze = [], [], []
        for simplex in self.tri.simplices:
            for s in itertools.combinations(simplex, 2):
                Xe += [vertices[i][0] for i in s] + [None]
                Ye += [vertices[i][1] for i in s] + [None]
                Ze += [vertices[i][2] for i in s] + [None]

        plots.append(
            plotly.graph_objs.Scatter3d(
                x=Xe,
                y=Ye,
                z=Ze,
                mode="lines",
                line={"color": "rgb(125,125,125)", "width": 1},
                hoverinfo="none",
            )
        )

    Xn, Yn, Zn = zip(*vertices)
    colors = [self.data[p] for p in self.tri.vertices]
    marker = {
        "symbol": "circle",
        "size": 3,
        "color": colors,
        "colorscale": "Viridis",
        "line": {"color": "rgb(50,50,50)", "width": 0.5},
    }

    plots.append(
        plotly.graph_objs.Scatter3d(
            x=Xn,
            y=Yn,
            z=Zn,
            mode="markers",
            name="actors",
            marker=marker,
            hoverinfo="text",
        )
    )

    axis = {
        "showbackground": False,
        "showline": False,
        "zeroline": False,
        "showgrid": False,
        "showticklabels": False,
        "title": "",
    }

    layout = plotly.graph_objs.Layout(
        showlegend=False,
        scene={"xaxis": axis, "yaxis": axis, "zaxis": axis},
        margin={"t": 100},
        hovermode="closest",
    )

    fig = plotly.graph_objs.Figure(data=plots, layout=layout)

    return fig if return_fig else plotly.offline.iplot(fig)

plot_isoline

plot_isoline(level=0.0, n=None, tri_alpha=0)

Plot the isoline at a specific level, only works in 2D.

Parameters:

Name Type Description Default
level float

The value of the function at which you would like to see the isoline.

0
n int

The number of boxes in the interpolation grid along each axis. This is passed to plot.

None
tri_alpha float

The opacity of the overlaying triangulation. This is passed to plot.

0

Returns:

Type Description
Overlay

The plot of the isoline(s). This overlays a plot with a holoviews.element.Path.

Source code in adaptive/learner/learnerND.py
def plot_isoline(self, level=0.0, n=None, tri_alpha=0):
    """Plot the isoline at a specific level, only works in 2D.

    Parameters
    ----------
    level : float, default: 0
        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 lvl in level:
            plot = plot * self.plot_isoline(level=lvl, 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).opts(color="black")
    return plot * contour

plot_isosurface

plot_isosurface(level=0.0, hull_opacity=0.2)

Plots a linearly interpolated isosurface.

This is the 3D analog of an isoline. Does not work with the adaptive.notebook_integration.live_plot functionality.

Parameters:

Name Type Description Default
level float

the function value which you are interested in.

0.0
hull_opacity float

the opacity of the hull of the domain.

0.0

Returns:

Name Type Description
plot plotly.offline.iplot object

The plot object of the isosurface.

Source code in adaptive/learner/learnerND.py
def plot_isosurface(self, level=0.0, hull_opacity=0.2):
    """Plots a linearly interpolated isosurface.

    This is the 3D analog of an isoline. Does *not* work with the
    `adaptive.notebook_integration.live_plot` functionality.

    Parameters
    ----------
    level : float, default: 0.0
        the function value which you are interested in.
    hull_opacity : float, default: 0.0
        the opacity of the hull of the domain.

    Returns
    -------
    plot : `plotly.offline.iplot` object
        The plot object of the isosurface.
    """
    plotly = ensure_plotly()

    vertices, faces = self._get_iso(level, which="surface")
    x, y, z = zip(*vertices)

    fig = plotly.figure_factory.create_trisurf(
        x=x, y=y, z=z, plot_edges=False, simplices=faces, title="Isosurface"
    )
    isosurface = fig.data[0]
    isosurface.update(
        lighting={
            "ambient": 1,
            "diffuse": 1,
            "roughness": 1,
            "specular": 0,
            "fresnel": 0,
        }
    )

    if hull_opacity < 1e-3:
        # Do not compute the hull_mesh.
        return plotly.offline.iplot(fig)

    hull_mesh = self._get_hull_mesh(opacity=hull_opacity)
    return plotly.offline.iplot([isosurface, hull_mesh])

Custom loss functions

default_loss

default_loss(simplex, values, value_scale)

Computes the average of the volumes of the simplex.

Parameters:

Name Type Description Default
simplex list of tuples

Each entry is one point of the simplex.

required
values list of values

The scaled function values of each of the simplex points.

required
value_scale float

The scale of values, where values = function_values * value_scale.

required

Returns:

Name Type Description
loss float
Source code in adaptive/learner/learnerND.py
def default_loss(simplex, values, value_scale):
    """
    Computes the average of the volumes of the simplex.

    Parameters
    ----------
    simplex : list of tuples
        Each entry is one point of the simplex.
    values : list of values
        The scaled function values of each of the simplex points.
    value_scale : float
        The scale of values, where ``values = function_values * value_scale``.

    Returns
    -------
    loss : float
    """
    if isinstance(values[0], Iterable):
        pts = [(*x, *y) for x, y in zip(simplex, values)]
    else:
        pts = [(*x, y) for x, y in zip(simplex, values)]
    return simplex_volume_in_embedding(pts)

uniform_loss

uniform_loss(simplex, values, value_scale)

Uniform loss.

Parameters:

Name Type Description Default
simplex list of tuples

Each entry is one point of the simplex.

required
values list of values

The scaled function values of each of the simplex points.

required
value_scale float

The scale of values, where values = function_values * value_scale.

required

Returns:

Name Type Description
loss float
Source code in adaptive/learner/learnerND.py
def uniform_loss(simplex, values, value_scale):
    """
    Uniform loss.

    Parameters
    ----------
    simplex : list of tuples
        Each entry is one point of the simplex.
    values : list of values
        The scaled function values of each of the simplex points.
    value_scale : float
        The scale of values, where ``values = function_values * value_scale``.

    Returns
    -------
    loss : float
    """
    return volume(simplex)

std_loss

std_loss(simplex, values, value_scale)

Computes the loss of the simplex based on the standard deviation.

Parameters:

Name Type Description Default
simplex list of tuples

Each entry is one point of the simplex.

required
values list of values

The scaled function values of each of the simplex points.

required
value_scale float

The scale of values, where values = function_values * value_scale.

required

Returns:

Name Type Description
loss float
Source code in adaptive/learner/learnerND.py
def std_loss(simplex, values, value_scale):
    """
    Computes the loss of the simplex based on the standard deviation.

    Parameters
    ----------
    simplex : list of tuples
        Each entry is one point of the simplex.
    values : list of values
        The scaled function values of each of the simplex points.
    value_scale : float
        The scale of values, where ``values = function_values * value_scale``.

    Returns
    -------
    loss : float
    """

    r = np.linalg.norm(np.std(values, axis=0))
    vol = volume(simplex)

    dim = len(simplex) - 1

    return r.flat * np.power(vol, 1.0 / dim) + vol