adaptive.Learner2D#
- class adaptive.Learner2D(function: Callable, bounds: tuple[tuple[Union[float, numpy.float64, int, numpy.int64], Union[float, numpy.float64, int, numpy.int64]], tuple[Union[float, numpy.float64, int, numpy.int64], Union[float, numpy.float64, int, numpy.int64]]], loss_per_triangle: Optional[Callable] = None)[source]#
Bases:
BaseLearner
Learns and predicts a function βf: β^2 β β^Nβ.
- Parameters:
function (callable) β The function to learn. Must take a tuple of two real parameters and return a real number.
bounds (list of 2-tuples) β A list
[(a1, b1), (a2, b2)]
containing bounds, one per dimension.loss_per_triangle (callable, optional) β A function that returns the loss for every triangle. 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. See the notes for more details.
- pending_points#
Points that still have to be evaluated and are currently interpolated, see data_combined.
- Type:
- stack_size#
The size of the new candidate points stack. Set it to 1 to recalculate the best points at each call to
ask
.- Type:
int, default: 10
- aspect_ratio#
Average ratio of
x
span overy
span of a triangle. If there is more detail in eitherx
ory
theaspect_ratio
needs to be adjusted. Whenaspect_ratio > 1
the triangles will be stretched alongx
, otherwise alongy
.
Notes
Adapted from an initial implementation by Pauli Virtanen.
The sample points are chosen by estimating the point where the linear and cubic interpolants based on the existing points have maximal disagreement. This point is then taken as the next point to be sampled.
In practice, this sampling protocol results to sparser sampling of smooth regions, and denser sampling of regions where the function changes rapidly, which is useful if the function is expensive to compute.
This sampling procedure is not extremely fast, so to benefit from it, your function needs to be slow enough to compute.
loss_per_triangle takes a single parameter,
ip
, which is ascipy.interpolate.LinearNDInterpolator
. You can use the undocumented attributestri
andvalues
ofip
to get ascipy.spatial.Delaunay
and a vector of function values. These can be used to compute the loss. The functionsareas
anddeviations
to calculate the areas and deviations from a linear interpolation over each triangle.- ask(n: int, tell_pending: bool = True) tuple[list[tuple[float, float] | numpy.ndarray], list[float]] [source]#
Choose the next βnβ points to evaluate.
- interpolated_on_grid(n: Optional[int] = None) tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray] [source]#
Get the interpolated data on a grid.
- Parameters:
n (int, optional) β Number of points in x and y. If None (default) this number is evaluated by looking at the size of the smallest triangle.
- Returns:
xs (1D numpy.ndarray)
ys (1D numpy.ndarray)
interpolated_on_grid (2D numpy.ndarray)
- interpolator(*, scaled: bool = False) LinearNDInterpolator [source]#
A
scipy.interpolate.LinearNDInterpolator
instance containing the learnerβs data.- Parameters:
scaled (bool) β Use True if all points are inside the unit-square [(-0.5, 0.5), (-0.5, 0.5)] or False if the data points are inside the
learner.bounds
.- Returns:
interpolator
- Return type:
Examples
>>> xs, ys = [np.linspace(*b, num=100) for b in learner.bounds] >>> ip = learner.interpolator() >>> zs = ip(xs[:, None], ys[None, :])
- ip() LinearNDInterpolator [source]#
Deprecated, use self.interpolator(scaled=True)
- load_dataframe(df: DataFrame, with_default_function_args: bool = True, function_prefix: str = 'function.', x_name: str = 'x', y_name: str = 'y', z_name: str = 'z')[source]#
Load data from a
pandas.DataFrame
.If
with_default_function_args
is True, thenlearner.function
βs default arguments are set (usingfunctools.partial
) from the values in thepandas.DataFrame
.- Parameters:
df (pandas.DataFrame) β The data to load.
with_default_function_args (bool, optional) β The
with_default_function_args
used into_dataframe()
, by default Truefunction_prefix (str, optional) β The
function_prefix
used into_dataframe
, by default βfunction.βx_name (str, optional) β The
x_name
used into_dataframe
, by default βxβy_name (str, optional) β The
y_name
used into_dataframe
, by default βyβz_name (str, optional) β The
z_name
used into_dataframe
, by default βzβ
- loss(real: bool = True) float [source]#
Return the loss for the current state of the learner.
- Parameters:
real (bool, default: True) β If False, return the βexpectedβ loss, i.e. the loss including the as-yet unevaluated points (possibly by interpolation).
- plot(n=None, tri_alpha=0)[source]#
Plot the Learner2Dβs current state.
This plot function interpolates the data on a regular grid. The gridspacing is evaluated by checking the size of the smallest triangle.
- Parameters:
- Returns:
plot β A
holoviews.core.Overlay
ofholoviews.Image * holoviews.EdgePaths
. If the learner.function returns a vector output, aholoviews.core.HoloMap
of theholoviews.core.Overlay
s wil be returned.- Return type:
Notes
The plot object that is returned if
learner.function
returns a vector cannot be used with the live_plotting functionality.
- tell(point: tuple[float, float], value: float | collections.abc.Iterable[float]) None [source]#
Tell the learner about a single value.
- Parameters:
x (A value from the function domain) β
y (A value from the function image) β
- tell_pending(point: tuple[float, float]) None [source]#
Tell the learner that βxβ has been requested such that itβs not suggested again.
- to_dataframe(with_default_function_args: bool = True, function_prefix: str = 'function.', x_name: str = 'x', y_name: str = 'y', z_name: str = 'z') DataFrame [source]#
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 Truefunction_prefix (str, optional) β Prefix to the
learner.function
βs default argumentsβ names, by default βfunction.βseed_name (str, optional) β Name of the seed parameter, by default βseedβ
x_name (str, optional) β Name of the input x value, by default βxβ
y_name (str, optional) β Name of the input y value, by default βyβ
z_name (str, optional) β Name of the output value, by default βzβ
- Return type:
pandas.DataFrame
- Raises:
ImportError β If
pandas
is not installed.
- to_numpy()[source]#
Data as NumPy array of size
(npoints, 3)
iflearner.function
returns a scalar and(npoints, 2+vdim)
iflearner.function
returns a vector of lengthvdim
.
- property vdim: int#
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.
- property xy_scale: ndarray#
Custom loss functions#
- adaptive.learner.learner2D.default_loss(ip: LinearNDInterpolator) ndarray [source]#
Loss function that combines
deviations
andareas
of the triangles.Works with
Learner2D
only.- Parameters:
ip (
scipy.interpolate.LinearNDInterpolator
instance) β- Returns:
losses β Loss per triangle in
ip.tri
.- Return type:
numpy.ndarray
- adaptive.learner.learner2D.minimize_triangle_surface_loss(ip: LinearNDInterpolator) ndarray [source]#
Loss function that is similar to the distance loss function in the
Learner1D
. The loss is the area spanned by the 3D vectors of the vertices.Works with
Learner2D
only.- Parameters:
ip (
scipy.interpolate.LinearNDInterpolator
instance) β- Returns:
losses β Loss per triangle in
ip.tri
.- Return type:
numpy.ndarray
Examples
>>> from adaptive.learner.learner2D import minimize_triangle_surface_loss >>> def f(xy): ... x, y = xy ... return x**2 + y**2 >>> >>> learner = adaptive.Learner2D(f, bounds=[(-1, -1), (1, 1)], ... loss_per_triangle=minimize_triangle_surface_loss) >>>
- adaptive.learner.learner2D.uniform_loss(ip: LinearNDInterpolator) ndarray [source]#
Loss function that samples the domain uniformly.
Works with
Learner2D
only.- Parameters:
ip (
scipy.interpolate.LinearNDInterpolator
instance) β- Returns:
losses β Loss per triangle in
ip.tri
.- Return type:
numpy.ndarray
Examples
>>> from adaptive.learner.learner2D import uniform_loss >>> def f(xy): ... x, y = xy ... return x**2 + y**2 >>> >>> learner = adaptive.Learner2D( ... f, ... bounds=[(-1, -1), (1, 1)], ... loss_per_triangle=uniform_loss, ... ) >>>
- adaptive.learner.learner2D.resolution_loss_function(min_distance: float = 0, max_distance: float = 1) Callable[[LinearNDInterpolator], ndarray] [source]#
Loss function that is similar to the
default_loss
function, but you can set the maximimum and minimum size of a triangle.Works with
Learner2D
only.The arguments min_distance and max_distance should be in between 0 and 1 because the total area is normalized to 1.
- Returns:
loss_function
- Return type:
callable
Examples
>>> def f(xy): ... x, y = xy ... return x**2 + y**2 >>> >>> loss = resolution_loss_function(min_distance=0.01, max_distance=1) >>> learner = adaptive.Learner2D(f, bounds=[(-1, -1), (1, 1)], loss_per_triangle=loss)
Helper functions#
- adaptive.learner.learner2D.areas(ip: LinearNDInterpolator) ndarray [source]#
Returns the area per triangle of the triangulation inside a
LinearNDInterpolator
instance.Is useful when defining custom loss functions.
- Parameters:
ip (
scipy.interpolate.LinearNDInterpolator
instance) β- Returns:
areas β The area per triangle in
ip.tri
.- Return type:
numpy.ndarray
- adaptive.learner.learner2D.deviations(ip: LinearNDInterpolator) list[numpy.ndarray] [source]#
Returns the deviation of the linear estimate.
Is useful when defining custom loss functions.
- Parameters:
ip (
scipy.interpolate.LinearNDInterpolator
instance) β- Returns:
deviations β The deviation per triangle.
- Return type: