diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml new file mode 100644 index 000000000..f02bb89a7 --- /dev/null +++ b/.github/workflows/typecheck.yml @@ -0,0 +1,26 @@ +name: Type checking + +on: + pull_request: + push: + branches: [main] + +jobs: + typecheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: Install uv + uses: astral-sh/setup-uv@v6 + - name: Install dependencies and type checkers + run: | + uv venv --python 3.13 + uv pip install '.[test,other,notebook]' scipy-stubs==1.18.1.1 pandas-stubs==3.1.2.261202 ty==1.2.0 mypy==2.4.1 + - name: Run ty + run: .venv/bin/ty check --error-on-warning --python .venv adaptive tests/typing_contract.py + - name: Run mypy + run: .venv/bin/mypy adaptive tests/typing_contract.py diff --git a/.github/workflows/typeguard.yml b/.github/workflows/typeguard.yml deleted file mode 100644 index c89a44425..000000000 --- a/.github/workflows/typeguard.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: typeguard - -on: - pull_request: - push: - branches: [main] - -jobs: - typeguard: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: "3.13" - - name: Install uv - uses: astral-sh/setup-uv@v6 - - name: Test with nox - run: uv run --group nox nox -e pytest_typeguard diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e41c84989..a6028d096 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -23,7 +23,7 @@ repos: args: ["ruff", "--fix", "--ignore=E402,B018,F704"] additional_dependencies: [jupytext, ruff] - repo: https://github.com/pre-commit/mirrors-mypy - rev: "v1.15.0" + rev: "v2.4.1" hooks: - id: mypy - exclude: ipynb_filter.py + files: ^adaptive/ diff --git a/adaptive/__init__.py b/adaptive/__init__.py index 34f75d9ac..5dae0fe1d 100644 --- a/adaptive/__init__.py +++ b/adaptive/__init__.py @@ -19,7 +19,7 @@ ) from adaptive.runner import AsyncRunner, BlockingRunner, Runner -from adaptive import learner, runner, utils # isort:skip +from adaptive import learner, notebook_integration, runner, types as types, utils # isort:skip __all__ = [ "learner", @@ -46,4 +46,4 @@ ] # to avoid confusion with `notebook_extension` -del notebook_integration # type: ignore[name-defined] # noqa: F821 +del notebook_integration diff --git a/adaptive/_types.py b/adaptive/_types.py deleted file mode 100644 index 3f56bf59b..000000000 --- a/adaptive/_types.py +++ /dev/null @@ -1,24 +0,0 @@ -# Only used for static type checkers, should only be imported in `if TYPE_CHECKING` block -# Workaround described in https://github.com/agronholm/typeguard/issues/456 - -import concurrent.futures as concurrent -from typing import TypeAlias - -import distributed -import ipyparallel -import loky -import mpi4py.futures - -from adaptive.utils import SequentialExecutor - -ExecutorTypes: TypeAlias = ( - concurrent.ProcessPoolExecutor - | concurrent.ThreadPoolExecutor - | SequentialExecutor - | loky.reusable_executor._ReusablePoolExecutor - | distributed.Client - | distributed.cfexecutor.ClientExecutor - | mpi4py.futures.MPIPoolExecutor - | ipyparallel.Client - | ipyparallel.client.view.ViewExecutor -) diff --git a/adaptive/learner/_sorted_types.py b/adaptive/learner/_sorted_types.py new file mode 100644 index 000000000..fdb4cab86 --- /dev/null +++ b/adaptive/learner/_sorted_types.py @@ -0,0 +1,32 @@ +"""Static interfaces for the untyped sorted mapping dependencies.""" + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable, KeysView, Mapping, Sequence + from typing import TypeVar + + _Key = TypeVar("_Key") + _Value = TypeVar("_Value") + + # The sorted mapping libraries are not typed. Their classes extend dict, + # but keys() also supports indexing and slicing in sorted order. + class _SortedKeys(KeysView[_Key], Sequence[_Key]): ... + + class SortedDict(dict[_Key, _Value]): + def keys(self) -> _SortedKeys[_Key]: ... # type: ignore[override] # ty: ignore[incompatible-method-override] + def bisect_left(self, key: _Key) -> int: ... + def index(self, key: _Key) -> int: ... + def peekitem(self, index: int = -1) -> tuple[_Key, _Value]: ... + + class ItemSortedDict(SortedDict[_Key, _Value]): + def __init__( + self, + key: Callable[[_Key, _Value], object], + mapping: Mapping[_Key, _Value] = ..., + ) -> None: ... +else: + from sortedcollections.recipes import ItemSortedDict + from sortedcontainers.sorteddict import SortedDict + +__all__ = ["ItemSortedDict", "SortedDict"] diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index 2ee309924..11da98c75 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -2,19 +2,25 @@ from collections.abc import Callable from math import sqrt +from typing import TYPE_CHECKING, Any, TypeAlias, cast import cloudpickle import numpy as np +from numpy.typing import NDArray from adaptive.learner.base_learner import BaseLearner from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Float, Int, Real from adaptive.utils import ( assign_defaults, cache_latest, partial_function_from_dataframe, ) +if TYPE_CHECKING: + from holoviews.element import Histogram +else: + Histogram = Any + try: import pandas @@ -24,6 +30,11 @@ with_pandas = False +_Seed: TypeAlias = int | np.integer[Any] +_Sample: TypeAlias = float | np.float64 | np.int_ +_AverageData: TypeAlias = tuple[dict[_Seed, _Sample], int, _Sample, _Sample] + + class AverageLearner(BaseLearner): """A naive implementation of adaptive computing of averages. @@ -49,9 +60,14 @@ class AverageLearner(BaseLearner): Number of evaluated points. """ + data: dict[_Seed, _Sample] + pending_points: set[_Seed] + + npoints: int + def __init__( self, - function: Callable[[int], Real], + function: Callable[[int], Any], atol: float | None = None, rtol: float | None = None, min_npoints: int = 2, @@ -65,14 +81,14 @@ def __init__( self.data = {} self.pending_points = set() - self.function = function # type: ignore + self.function: Callable[..., Any] = function self.atol = atol self.rtol = rtol self.npoints = 0 # Cannot estimate standard deviation with fewer than 2 points. self.min_npoints = max(min_npoints, 2) - self.sum_f: Real = 0.0 - self.sum_f_sq: Real = 0.0 + self.sum_f: _Sample = 0.0 + self.sum_f_sq: _Sample = 0.0 def new(self) -> AverageLearner: """Create a copy of `~adaptive.AverageLearner` without the data.""" @@ -82,11 +98,11 @@ def new(self) -> AverageLearner: def n_requested(self) -> int: return self.npoints + len(self.pending_points) - def to_numpy(self): + def to_numpy(self) -> NDArray[Any]: """Data as NumPy array of size (npoints, 2) with seeds and values.""" return np.array(sorted(self.data.items())) - def to_dataframe( # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -126,14 +142,14 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", seed_name: str = "seed", y_name: str = "y", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -160,7 +176,7 @@ def load_dataframe( # type: ignore[override] self.function, df, function_prefix ) - def ask(self, n: int, tell_pending: bool = True) -> tuple[list[int], list[Float]]: + def ask(self, n: int, tell_pending: bool = True) -> tuple[list[int], list[float]]: points = list(range(self.n_requested, self.n_requested + n)) if any(p in self.data or p in self.pending_points for p in points): @@ -177,7 +193,7 @@ def ask(self, n: int, tell_pending: bool = True) -> tuple[list[int], list[Float] self.tell_pending(p) return points, loss_improvements - def tell(self, n: Int, value: Real) -> None: + def tell(self, n: _Seed, value: _Sample) -> None: if n in self.data: # The point has already been added before. return @@ -188,16 +204,17 @@ def tell(self, n: Int, value: Real) -> None: self.sum_f_sq += value**2 self.npoints += 1 - def tell_pending(self, n: int) -> None: + def tell_pending(self, n: _Seed) -> None: self.pending_points.add(n) @property - def mean(self) -> Float: + def mean(self) -> float: """The average of all values in `data`.""" - return self.sum_f / self.npoints + # Division of these real scalars produces a float or a numpy.float64. + return cast(float, self.sum_f / self.npoints) @property - def std(self) -> Float: + def std(self) -> float: """The corrected sample standard deviation of the values in `data`.""" n = self.npoints @@ -210,11 +227,9 @@ def std(self) -> Float: return sqrt(numerator / (n - 1)) @cache_latest - def loss(self, real: bool = True, *, n=None) -> Float: + def loss(self, real: bool = True, *, n: int | None = None) -> float: if n is None: n = self.npoints if real else self.n_requested - else: - n = n if min(self.npoints, n) < self.min_npoints: return np.inf standard_error = self.std / sqrt(n) @@ -225,18 +240,18 @@ def loss(self, real: bool = True, *, n=None) -> Float: rloss /= abs(mean) return max(aloss, rloss) - def _loss_improvement(self, n: int) -> Float: + def _loss_improvement(self, n: int) -> float: loss = self.loss() if np.isfinite(loss): return loss - self.loss(n=self.npoints + n) else: return np.inf - def remove_unfinished(self): + def remove_unfinished(self) -> None: """Remove uncomputed data from the learner.""" self.pending_points = set() - def plot(self): + def plot(self) -> Histogram: """Returns a histogram of the evaluated data. Returns @@ -251,13 +266,13 @@ def plot(self): vals = hv.Points(vals) return hv.operation.histogram(vals, num_bins=num_bins, dimension="y") - def _get_data(self) -> tuple[dict[int, Real], int, Real, Real]: + def _get_data(self) -> _AverageData: return (self.data, self.npoints, self.sum_f, self.sum_f_sq) - def _set_data(self, data: tuple[dict[int, Real], int, Real, Real]) -> None: + def _set_data(self, data: _AverageData) -> None: self.data, self.npoints, self.sum_f, self.sum_f_sq = data - def __getstate__(self): + def __getstate__(self) -> tuple[bytes, float, float, int, _AverageData]: return ( cloudpickle.dumps(self.function), self.atol, @@ -266,8 +281,11 @@ def __getstate__(self): self._get_data(), ) - def __setstate__(self, state): - function, atol, rtol, min_npoints, data = state - function = cloudpickle.loads(function) - self.__init__(function, atol, rtol, min_npoints) + def __setstate__( + self, state: tuple[bytes, float, float, int, _AverageData] + ) -> None: + pickled_function, atol, rtol, min_npoints, data = state + type(self).__init__( + self, cloudpickle.loads(pickled_function), atol, rtol, min_npoints + ) self._set_data(data) diff --git a/adaptive/learner/average_learner1D.py b/adaptive/learner/average_learner1D.py index 82c76f5d9..95df938ea 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -6,15 +6,22 @@ from collections.abc import Callable, Iterable, Sequence from copy import deepcopy from math import hypot +from typing import TYPE_CHECKING, Any, TypeAlias, cast import numpy as np import scipy.stats -from sortedcollections import ItemSortedDict -from sortedcontainers import SortedDict - -from adaptive.learner.learner1D import Learner1D, _get_intervals +from numpy.typing import NDArray + +from adaptive.learner._sorted_types import ItemSortedDict, SortedDict +from adaptive.learner.learner1D import ( + Learner1D, + _Bounds, + _get_intervals, + _IntervalLossCallback, + _SampleData, + _StoredData, +) from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Int, Real from adaptive.utils import assign_defaults, partial_function_from_dataframe try: @@ -25,8 +32,13 @@ except ModuleNotFoundError: with_pandas = False -Point = tuple[int, Real] -Points = list[Point] +if TYPE_CHECKING: + from holoviews.core import Overlay +else: + Overlay = Any + +Point: TypeAlias = tuple[int, float] +Points: TypeAlias = list[Point] __all__: list[str] = ["AverageLearner1D"] @@ -74,19 +86,24 @@ class AverageLearner1D(Learner1D): [self.data[x] - min_error, self.data[x] + min_error]. """ + # The public sampling interface uses (seed, x) rather than x, while + # the inherited interval calculations still use the real coordinate x. + if TYPE_CHECKING: + pending_points: set[Point] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] + data: dict[float, float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] + def __init__( self, - function: Callable[[tuple[int, Real]], Real], - bounds: tuple[Real, Real], - loss_per_interval: None - | (Callable[[Sequence[Real], Sequence[Real]], float]) = None, + function: Callable[[Point], Any], + bounds: _Bounds, + loss_per_interval: _IntervalLossCallback | None = None, delta: float = 0.2, alpha: float = 0.005, neighbor_sampling: float = 0.3, min_samples: int = 50, max_samples: int = sys.maxsize, min_error: float = 0, - ): + ) -> None: if not (0 < delta <= 1): raise ValueError("Learner requires 0 < delta <= 1.") if not (0 < alpha <= 1): @@ -98,7 +115,12 @@ def __init__( if min_samples > max_samples: raise ValueError("max_samples should be larger than min_samples.") - super().__init__(function, bounds, loss_per_interval) # type: ignore[arg-type] + # The shared initializer stores the callback without calling it. + super().__init__( + cast("Callable[[float], Any]", function), + bounds, + loss_per_interval, + ) self.delta = delta self.alpha = alpha @@ -109,28 +131,28 @@ def __init__( # Contains all samples f(x) for each # point x in the form {x0: {0: f_0(x0), 1: f_1(x0), ...}, ...} - self._data_samples: SortedDict[float, dict[int, Real]] = SortedDict() + self._data_samples: SortedDict[float, dict[int, float]] = SortedDict() # Contains the number of samples taken # at each point x in the form {x0: n0, x1: n1, ...} - self._number_samples = SortedDict() + self._number_samples: SortedDict[float, int] = SortedDict() # This set contains the points x that have less than min_samples # samples or less than a (neighbor_sampling*100)% of their neighbors - self._undersampled_points: set[Real] = set() + self._undersampled_points: set[float] = set() # Contains the error in the estimate of the # mean at each point x in the form {x0: error(x0), ...} - self.error: dict[Real, float] = decreasing_dict() + self.error = decreasing_dict() # Distance between two neighboring points in the # form {xi: ((xii-xi)^2 + (yii-yi)^2)^0.5, ...} - self._distances: dict[Real, float] = decreasing_dict() + self._distances = decreasing_dict() # {xii: error[xii]/min(_distances[xi], _distances[xii], ...} - self.rescaled_error: ItemSortedDict[Real, float] = decreasing_dict() + self.rescaled_error = decreasing_dict() def new(self) -> AverageLearner1D: """Create a copy of `~adaptive.AverageLearner1D` without the data.""" return AverageLearner1D( self.function, self.bounds, - self.loss_per_interval, # type: ignore[arg-type] + self.loss_per_interval, self.delta, self.alpha, self.neighbor_sampling, @@ -150,7 +172,7 @@ def min_samples_per_point(self) -> int: return 0 return min(self._number_samples.values()) - def to_numpy(self, mean: bool = False) -> np.ndarray: + def to_numpy(self, mean: bool = False) -> NDArray[Any]: if mean: return super().to_numpy() else: @@ -162,7 +184,7 @@ def to_numpy(self, mean: bool = False) -> np.ndarray: ] ) - def to_dataframe( # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, mean: bool = False, with_default_function_args: bool = True, @@ -199,11 +221,12 @@ def to_dataframe( # type: ignore[override] """ if not with_pandas: raise ImportError("pandas is not installed.") + data: list[tuple[float, float]] | list[tuple[int, float, float]] if mean: - data: list[tuple[Real, Real]] = sorted(self.data.items()) + data = sorted(self.data.items()) columns = [x_name, y_name] else: - data: list[tuple[int, Real, Real]] = [ # type: ignore[no-redef] + data = [ (seed, x, y) for x, seed_y in sorted(self._data_samples.items()) for seed, y in sorted(seed_y.items()) @@ -216,7 +239,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -224,7 +247,7 @@ def load_dataframe( # type: ignore[override] seed_name: str = "seed", x_name: str = "x", y_name: str = "y", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -250,13 +273,13 @@ def load_dataframe( # type: ignore[override] # Were using zip instead of df[[seed_name, x_name]].values because that will # make the seeds into floats seed_x = list(zip(df[seed_name].values.tolist(), df[x_name].values.tolist())) - self.tell_many(seed_x, df[y_name].values) + self.tell_many(seed_x, cast("Sequence[float]", df[y_name].values)) if with_default_function_args: self.function = partial_function_from_dataframe( self.function, df, function_prefix ) - def ask(self, n: int, tell_pending: bool = True) -> tuple[Points, list[float]]: # type: ignore[override] + def ask(self, n: int, tell_pending: bool = True) -> tuple[Points, list[float]]: # type: ignore[override] # ty: ignore[incompatible-method-override] """Return 'n' points that are expected to maximally reduce the loss.""" # If some point is undersampled, resample it if len(self._undersampled_points): @@ -285,15 +308,23 @@ def ask(self, n: int, tell_pending: bool = True) -> tuple[Points, list[float]]: return points, loss_improvements - def _ask_for_more_samples(self, x: Real, n: int) -> tuple[Points, list[float]]: + def _ask_for_more_samples(self, x: float, n: int) -> tuple[Points, list[float]]: """When asking for n points, the learner returns n times an existing point to be resampled, since in general n << min_samples and this point will need to be resampled many more times""" n_existing = self._number_samples.get(x, 0) points = [(seed + n_existing, x) for seed in range(n)] xl, xr = self.neighbors_combined[x] - loss_left = self.losses_combined.get((xl, x), float("inf")) - loss_right = self.losses_combined.get((x, xr), float("inf")) + loss_left = ( + float("inf") + if xl is None + else self.losses_combined.get((xl, x), float("inf")) + ) + loss_right = ( + float("inf") + if xr is None + else self.losses_combined.get((x, xr), float("inf")) + ) loss = (loss_left + loss_right) / 2 if math.isinf(loss): loss_improvement = float("inf") @@ -311,16 +342,16 @@ def _ask_for_new_point(self, n: int) -> tuple[Points, list[float]]: points, (loss_improvement,) = self._ask_points_without_adding(1) seed_points = list(zip(range(n), n * points)) loss_improvements = [loss_improvement / n] * n - return seed_points, loss_improvements # type: ignore[return-value] + return seed_points, loss_improvements - def tell_pending(self, seed_x: Point) -> None: # type: ignore[override] + def tell_pending(self, seed_x: Point) -> None: # type: ignore[override] # ty: ignore[incompatible-method-override] _, x = seed_x self.pending_points.add(seed_x) if x not in self.data: self._update_neighbors(x, self.neighbors_combined) self._update_losses(x, real=False) - def tell(self, seed_x: Point, y: Real) -> None: # type: ignore[override] + def tell(self, seed_x: Point, y: float) -> None: # type: ignore[override] # ty: ignore[incompatible-method-override] seed, x = seed_x if y is None: raise TypeError( @@ -336,7 +367,7 @@ def tell(self, seed_x: Point, y: Real) -> None: # type: ignore[override] self._update_data_structures(seed_x, y, "resampled") self.pending_points.discard(seed_x) - def _update_rescaled_error_in_mean(self, x: Real, point_type: str) -> None: + def _update_rescaled_error_in_mean(self, x: float, point_type: str) -> None: """Updates ``self.rescaled_error``. Parameters @@ -360,6 +391,7 @@ def _update_rescaled_error_in_mean(self, x: Real, point_type: str) -> None: self.rescaled_error[x_left] = self.error[x_left] / norm if x_right is None: + assert x_left is not None d_right = dists[x_left] else: d_right = dists[x] @@ -373,7 +405,7 @@ def _update_rescaled_error_in_mean(self, x: Real, point_type: str) -> None: norm = min(d_left, d_right) self.rescaled_error[x] = self.error[x] / norm - def _update_data(self, x: Real, y: Real, point_type: str) -> None: + def _update_data(self, x: float, y: float, point_type: str) -> None: if point_type == "new": self.data[x] = y elif point_type == "resampled": @@ -381,7 +413,7 @@ def _update_data(self, x: Real, y: Real, point_type: str) -> None: new_average = self.data[x] * n / (n + 1) + y / (n + 1) self.data[x] = new_average - def _update_data_structures(self, seed_x: Point, y: Real, point_type: str) -> None: + def _update_data_structures(self, seed_x: Point, y: float, point_type: str) -> None: seed, x = seed_x if point_type == "new": self._data_samples[x] = {seed: y} @@ -449,7 +481,7 @@ def _update_data_structures(self, seed_x: Point, y: Real, point_type: str) -> No self._update_interpolated_loss_in_interval(*interval) self._oldscale = deepcopy(self._scale) - def _update_distances(self, x: Real) -> None: + def _update_distances(self, x: float) -> None: x_left, x_right = self.neighbors[x] y = self.data[x] if x_left is not None: @@ -457,7 +489,7 @@ def _update_distances(self, x: Real) -> None: if x_right is not None: self._distances[x] = hypot((x_right - x), (self.data[x_right] - y)) - def _update_losses_resampling(self, x: Real, real=True) -> None: + def _update_losses_resampling(self, x: float, real: bool = True) -> None: """Update all losses that depend on x, whenever the new point is a re-sampled point.""" # (x_left, x_right) are the "real" neighbors of 'x'. x_left, x_right = self._find_neighbors(x, self.neighbors) @@ -471,6 +503,8 @@ def _update_losses_resampling(self, x: Real, real=True) -> None: elif x_left is not None and x_right is not None: # 'x' happens to be in between two real points, # so we can interpolate the losses. + # Combined neighbors exist when there are real neighbors. + assert a is not None and b is not None dx = x_right - x_left loss = self.losses[x_left, x_right] self.losses_combined[a, x] = (x - a) * loss / dx @@ -486,13 +520,13 @@ def _update_losses_resampling(self, x: Real, real=True) -> None: if (b is not None) and right_loss_is_unknown: self.losses_combined[x, b] = float("inf") - def _calc_error_in_mean(self, ys: Iterable[Real], y_avg: Real, n: int) -> float: + def _calc_error_in_mean(self, ys: Iterable[float], y_avg: float, n: int) -> float: variance_in_mean = sum((y - y_avg) ** 2 for y in ys) / (n - 1) t_student = scipy.stats.t.ppf(1 - self.alpha, df=n - 1) return t_student * (variance_in_mean / n) ** 0.5 - def tell_many( # type: ignore[override] - self, xs: Points | np.ndarray, ys: Sequence[Real] | np.ndarray + def tell_many( # type: ignore[override] # ty: ignore[incompatible-method-override] + self, xs: Sequence[Point] | NDArray[Any], ys: Sequence[float] | NDArray[Any] ) -> None: # Check that all x are within the bounds # TODO: remove this requirement, all other learners add the data @@ -502,10 +536,7 @@ def tell_many( # type: ignore[override] "x value out of bounds, remove x or enlarge the bounds of the learner" ) - # Create a mapping of points to a list of samples - mapping: defaultdict[Real, defaultdict[Int, Real]] = defaultdict( - lambda: defaultdict(dict) - ) + mapping: defaultdict[float, dict[int, float]] = defaultdict(dict) for (seed, x), y in zip(xs, ys): mapping[x][seed] = y @@ -519,7 +550,7 @@ def tell_many( # type: ignore[override] # simultaneously, before we move on to a new x self.tell_many_at_point(x, seed_y_mapping) - def tell_many_at_point(self, x: Real, seed_y_mapping: dict[int, Real]) -> None: + def tell_many_at_point(self, x: float, seed_y_mapping: dict[int, float]) -> None: """Tell the learner about many samples at a certain location x. Parameters @@ -574,15 +605,15 @@ def tell_many_at_point(self, x: Real, seed_y_mapping: dict[int, Real]) -> None: self._update_interpolated_loss_in_interval(*interval) self._oldscale = deepcopy(self._scale) - def _get_data(self) -> dict[Real, dict[Int, Real]]: # type: ignore[override] + def _get_data(self) -> _SampleData: return self._data_samples - def _set_data(self, data: dict[Real, dict[Int, Real]]) -> None: # type: ignore[override] + def _set_data(self, data: _StoredData) -> None: if data: - for x, samples in data.items(): + for x, samples in cast("_SampleData", data).items(): self.tell_many_at_point(x, samples) - def plot(self): + def plot(self) -> Overlay: # type: ignore[override] # ty: ignore[incompatible-method-override] """Returns a plot of the evaluated data with error bars. This is only implemented for scalar functions, i.e., it requires ``vdim=1``. @@ -612,10 +643,10 @@ def plot(self): return p.redim(x={"range": plot_bounds}) -def decreasing_dict() -> ItemSortedDict: +def decreasing_dict() -> ItemSortedDict[float, float]: """This initialization orders the dictionary from large to small values""" - def sorting_rule(key, value): + def sorting_rule(key: float, value: float) -> float: return -value return ItemSortedDict(sorting_rule, SortedDict()) diff --git a/adaptive/learner/balancing_learner.py b/adaptive/learner/balancing_learner.py index 32f48e3cf..e9aea93ff 100644 --- a/adaptive/learner/balancing_learner.py +++ b/adaptive/learner/balancing_learner.py @@ -6,13 +6,33 @@ from contextlib import suppress from functools import partial from operator import itemgetter -from typing import Any, Literal, TypeAlias, cast +from os import PathLike +from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, cast + +import numpy as np from adaptive.learner.base_learner import BaseLearner, LearnerType from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Int, Real from adaptive.utils import cache_latest, named_product, restore +if TYPE_CHECKING: + from typing import Protocol, SupportsIndex + + from holoviews.core import Dimensioned, DynamicMap, HoloMap + from pandas import DataFrame + + class _HasNSamples(Protocol): + @property + def nsamples(self) -> int: ... + + class _Plottable(Protocol): + def plot(self) -> Dimensioned: ... + +else: + # Plotting remains optional, including when resolving the annotations. + Dimensioned = DynamicMap = HoloMap = Any + + try: import pandas @@ -21,19 +41,27 @@ with_pandas = False -def dispatch(child_functions: list[Callable], arg: Any) -> Any: +if not TYPE_CHECKING: + DataFrame = pandas.DataFrame if with_pandas else Any + + +def dispatch(child_functions: list[Callable[..., Any]], arg: _PointInput) -> Any: index, x = arg return child_functions[index](x) STRATEGY_TYPE: TypeAlias = Literal["loss_improvements", "loss", "npoints", "cycle"] -CDIMS_TYPE: TypeAlias = ( - Sequence[dict[str, Any]] | tuple[Sequence[str], Sequence[tuple[Any, ...]]] | None -) +_Index: TypeAlias = int | np.integer[Any] +_Point: TypeAlias = tuple[int, Any] +_PointInput: TypeAlias = tuple[_Index, Any] +_NamedDimensions: TypeAlias = tuple[Sequence[str], Iterable[tuple[Any, ...]]] +CDIMS_TYPE: TypeAlias = Sequence[dict[str, Any]] | _NamedDimensions | None +_Filename: TypeAlias = str | PathLike[str] -class BalancingLearner(BaseLearner): + +class BalancingLearner(BaseLearner, Generic[LearnerType]): r"""Choose the optimal points from a set of learners. Parameters @@ -86,7 +114,7 @@ class BalancingLearner(BaseLearner): def __init__( self, - learners: list[BaseLearner], + learners: list[LearnerType], *, cdims: CDIMS_TYPE = None, strategy: STRATEGY_TYPE = "loss_improvements", @@ -96,11 +124,11 @@ def __init__( # Naively we would make 'function' a method, but this causes problems # when using executors from 'concurrent.futures' because we have to # pickle the whole learner. - self.function = partial(dispatch, [lrn.function for lrn in self.learners]) # type: ignore + self.function = partial(dispatch, [lrn.function for lrn in self.learners]) - self._ask_cache: dict[int, Any] = {} - self._loss: dict[int, float] = {} - self._pending_loss: dict[int, float] = {} + self._ask_cache: dict[_Index, tuple[list[Any], list[float]]] = {} + self._loss: dict[_Index, float] = {} + self._pending_loss: dict[_Index, float] = {} self._cdims_default = cdims if len({learner.__class__ for learner in self.learners}) > 1: @@ -108,7 +136,7 @@ def __init__( self.strategy: STRATEGY_TYPE = strategy - def new(self) -> BalancingLearner: + def new(self) -> BalancingLearner[BaseLearner]: """Create a new `BalancingLearner` with the same parameters.""" return BalancingLearner( [learner.new() for learner in self.learners], @@ -117,27 +145,27 @@ def new(self) -> BalancingLearner: ) @property - def data(self) -> dict[tuple[int, Any], Any]: # type: ignore[override] + def data(self) -> dict[_Point, Any]: # ty: ignore[incompatible-property-override] data = {} for i, lrn in enumerate(self.learners): data.update({(i, p): v for p, v in lrn.data.items()}) return data @property - def pending_points(self) -> set[tuple[int, Any]]: # type: ignore[override] - pending_points = set() + def pending_points(self) -> set[_Point]: # type: ignore[override] # ty: ignore[incompatible-property-override] + pending_points: set[_Point] = set() for i, lrn in enumerate(self.learners): pending_points.update({(i, p) for p in lrn.pending_points}) return pending_points @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] return sum(lrn.npoints for lrn in self.learners) @property - def nsamples(self): + def nsamples(self) -> int: if hasattr(self.learners[0], "nsamples"): - return sum(lrn.nsamples for lrn in self.learners) + return sum(cast("_HasNSamples", lrn).nsamples for lrn in self.learners) else: raise AttributeError( f"{type(self.learners[0])} as no attribute called `nsamples`." @@ -174,8 +202,8 @@ def strategy(self, strategy: STRATEGY_TYPE) -> None: def _ask_and_tell_based_on_loss_improvements( self, n: int - ) -> tuple[list[tuple[int, Any]], list[float]]: - selected = [] # tuples ((learner_index, point), loss_improvement) + ) -> tuple[list[_Point], list[float]]: + selected: list[tuple[_Point, float]] = [] total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners] for _ in range(n): to_select = [] @@ -203,12 +231,8 @@ def _ask_and_tell_based_on_loss_improvements( points, loss_improvements = map(list, zip(*selected)) return points, loss_improvements - def _ask_and_tell_based_on_loss( - self, n: int - ) -> tuple[list[tuple[int, Any]], list[float]]: - selected: list[ - tuple[tuple[int, Any], float] - ] = [] # tuples ((learner_index, point), loss_improvement) + def _ask_and_tell_based_on_loss(self, n: int) -> tuple[list[_Point], list[float]]: + selected: list[tuple[_Point, float]] = [] total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners] exhausted: set[int] = set() # learners that have no point to give now while len(selected) < n and len(exhausted) < len(self.learners): @@ -240,11 +264,9 @@ def _ask_and_tell_based_on_loss( return points, loss_improvements def _ask_and_tell_based_on_npoints( - self, n: Int - ) -> tuple[list[tuple[Int, Any]], list[float]]: - selected: list[ - tuple[tuple[Int, Any], float] - ] = [] # tuples ((learner_index, point), loss_improvement) + self, n: int + ) -> tuple[list[_Point], list[float]]: + selected: list[tuple[_Point, float]] = [] total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners] exhausted: set[int] = set() # learners that have no point to give now while len(selected) < n and len(exhausted) < len(self.learners): @@ -268,9 +290,7 @@ def _ask_and_tell_based_on_npoints( points, loss_improvements = map(list, zip(*selected)) return points, loss_improvements - def _ask_and_tell_based_on_cycle( - self, n: int - ) -> tuple[list[tuple[Int, Any]], list[float]]: + def _ask_and_tell_based_on_cycle(self, n: int) -> tuple[list[_Point], list[float]]: points, loss_improvements = [], [] for _ in range(n): # Skip learners that have no point to give now, at most one round. @@ -289,7 +309,7 @@ def _ask_and_tell_based_on_cycle( def ask( self, n: int, tell_pending: bool = True - ) -> tuple[list[tuple[Int, Any]], list[float]]: + ) -> tuple[list[_Point], list[float]]: """Chose points for learners.""" if n == 0: return [], [] @@ -303,14 +323,14 @@ def ask( else: return self._ask_and_tell(n) - def tell(self, x: tuple[Int, Any], y: Any) -> None: + def tell(self, x: _PointInput, y: Any) -> None: index, x_ = x self._ask_cache.pop(index, None) self._loss.pop(index, None) self._pending_loss.pop(index, None) self.learners[index].tell(x_, y) - def tell_pending(self, x: tuple[Int, Any]) -> None: + def tell_pending(self, x: _PointInput) -> None: index, x_ = x self._ask_cache.pop(index, None) self._loss.pop(index, None) @@ -341,9 +361,9 @@ def loss(self, real: bool = True) -> float: def plot( self, cdims: CDIMS_TYPE = None, - plotter: Callable[[BaseLearner], Any] | None = None, + plotter: Callable[[LearnerType], Dimensioned] | None = None, dynamic: bool = True, - ): + ) -> DynamicMap | HoloMap: """Returns a DynamicMap with sliders. Parameters @@ -383,26 +403,34 @@ def plot( hv = ensure_holoviews() cdims = cdims or self._cdims_default + dimensions: Sequence[dict[str, Any]] if cdims is None: - cdims = [{"i": i} for i in range(len(self.learners))] + dimensions = [{"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] - cdims = cast(list[dict[str, Real]], cdims) + keys, values_list = cast(_NamedDimensions, cdims) + dimensions = [dict(zip(keys, values)) for values in values_list] + else: + dimensions = cast(Sequence[dict[str, Any]], cdims) mapping = { - tuple(_cdims.values()): lrn for lrn, _cdims in zip(self.learners, cdims) + tuple(_cdims.values()): lrn + for lrn, _cdims in zip(self.learners, dimensions) } - d = defaultdict(list) - for _cdims in cdims: + d: defaultdict[str, list[Any]] = defaultdict(list) + for _cdims in dimensions: for k, v in _cdims.items(): d[k].append(v) - def plot_function(*args): + def plot_function(*args: Any) -> Dimensioned | None: with suppress(KeyError): learner = mapping[tuple(args)] - return learner.plot() if plotter is None else plotter(learner) + return ( + cast("_Plottable", learner).plot() + if plotter is None + else plotter(learner) + ) + return None dm = hv.DynamicMap(plot_function, kdims=list(d.keys())) dm = dm.redim.values(**d) @@ -427,11 +455,11 @@ def remove_unfinished(self) -> None: @classmethod def from_product( cls, - f, - learner_type: LearnerType, + f: Callable[..., Any], + learner_type: Callable[..., LearnerType], learner_kwargs: dict[str, Any], combos: dict[str, Sequence[Any]], - ) -> BalancingLearner: + ) -> BalancingLearner[LearnerType]: """Create a `BalancingLearner` with learners of all combinations of named variables’ values. The `cdims` will be set correctly, so calling `learner.plot` will be a `holoviews.core.HoloMap` with the correct labels. @@ -474,11 +502,13 @@ def from_product( learners = [] arguments = named_product(**combos) for combo in arguments: - learner = learner_type(function=partial(f, **combo), **learner_kwargs) # type: ignore[operator] + learner = learner_type(function=partial(f, **combo), **learner_kwargs) learners.append(learner) return cls(learners, cdims=arguments) - def to_dataframe(self, index_name: str = "learner_index", **kwargs): # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] + self, index_name: str = "learner_index", **kwargs: Any + ) -> DataFrame: """Return the data as a concatenated `pandas.DataFrame` from child learners. Parameters @@ -510,9 +540,9 @@ def to_dataframe(self, index_name: str = "learner_index", **kwargs): # type: ig df = pandas.concat(dfs, axis=0, ignore_index=True) return df - def load_dataframe( # type: ignore[override] - self, df: pandas.DataFrame, index_name: str = "learner_index", **kwargs - ): + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] + self, df: DataFrame, index_name: str = "learner_index", **kwargs: Any + ) -> None: """Load the data from a `pandas.DataFrame` into the child learners. Parameters @@ -525,11 +555,11 @@ def load_dataframe( # type: ignore[override] Keyword arguments passed to each ``child_learner.load_dataframe(**kwargs)``. """ for i, gr in df.groupby(index_name): - self.learners[i].load_dataframe(gr, **kwargs) + self.learners[cast("SupportsIndex", i)].load_dataframe(gr, **kwargs) def save( self, - fname: Callable[[BaseLearner], str] | Sequence[str], + fname: Callable[[LearnerType], _Filename] | Iterable[_Filename], compress: bool = True, ) -> None: """Save the data of the child learners into pickle files @@ -571,7 +601,7 @@ def save( def load( self, - fname: Callable[[BaseLearner], str] | Sequence[str], + fname: Callable[[LearnerType], _Filename] | Iterable[_Filename], compress: bool = True, ) -> None: """Load the data of the child learners from pickle files @@ -600,17 +630,19 @@ def load( def _get_data(self) -> list[Any]: return [lrn._get_data() for lrn in self.learners] - def _set_data(self, data: list[Any]): + def _set_data(self, data: list[Any]) -> None: for lrn, _data in zip(self.learners, data): lrn._set_data(_data) - def __getstate__(self) -> tuple[list[BaseLearner], CDIMS_TYPE, STRATEGY_TYPE]: + def __getstate__(self) -> tuple[list[LearnerType], CDIMS_TYPE, STRATEGY_TYPE]: return ( self.learners, self._cdims_default, self.strategy, ) - def __setstate__(self, state: tuple[list[BaseLearner], CDIMS_TYPE, STRATEGY_TYPE]): + def __setstate__( + self, state: tuple[list[LearnerType], CDIMS_TYPE, STRATEGY_TYPE] + ) -> None: learners, cdims, strategy = state - self.__init__(learners, cdims=cdims, strategy=strategy) # type: ignore[misc] + type(self).__init__(self, learners, cdims=cdims, strategy=strategy) diff --git a/adaptive/learner/base_learner.py b/adaptive/learner/base_learner.py index f5ef73eca..95a2bbd1a 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -3,9 +3,10 @@ import abc from collections.abc import Callable from contextlib import suppress -from typing import TYPE_CHECKING, Any, TypeVar +from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, TypeAlias, TypeVar, cast import cloudpickle +import numpy as np from adaptive.utils import load, save @@ -13,7 +14,19 @@ import pandas -def uses_nth_neighbors(n: int): +_P = ParamSpec("_P") +_R_co = TypeVar("_R_co", covariant=True) + + +class _NeighborLoss(Protocol[_P, _R_co]): + nth_neighbors: int + + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R_co: ... + + +def uses_nth_neighbors( + n: int, +) -> Callable[[Callable[_P, _R_co]], _NeighborLoss[_P, _R_co]]: """Decorator to specify how many neighboring intervals the loss function uses. Wraps loss functions to indicate that they expect intervals together @@ -60,14 +73,16 @@ def uses_nth_neighbors(n: int): ... return loss """ - def _wrapped(loss_per_interval): - loss_per_interval.nth_neighbors = n - return loss_per_interval + def _wrapped(loss_per_interval: Callable[_P, _R_co]) -> _NeighborLoss[_P, _R_co]: + loss = cast("_NeighborLoss[_P, _R_co]", loss_per_interval) + loss.nth_neighbors = n + return loss return _wrapped DataType = dict[Any, Any] +_Bound: TypeAlias = float | np.floating[Any] | np.integer[Any] class BaseLearner(abc.ABC): @@ -91,12 +106,15 @@ class BaseLearner(abc.ABC): and returns a holoviews plot. """ - data: DataType - npoints: int - pending_points: set + # Learners expose either a synchronous or an asynchronous callback. + # Its return type is independent of the evaluated values passed to tell(). function: Callable[..., Any] - def tell(self, x, y): + data: Any + pending_points: set[Any] + npoints: int + + def tell(self, x: Any, y: Any) -> None: """Tell the learner about a single value. Parameters @@ -106,7 +124,16 @@ def tell(self, x, y): """ self.tell_many([x], [y]) - def tell_many(self, xs, ys): + @abc.abstractmethod + def tell_pending(self, x: Any) -> None: + """Tell the learner that 'x' has been requested such + that it's not suggested again.""" + + @abc.abstractmethod + def _set_data(self, data: Any) -> None: + pass + + def tell_many(self, xs: Any, ys: Any) -> None: """Tell the learner about some values. Parameters @@ -118,16 +145,11 @@ def tell_many(self, xs, ys): self.tell(x, y) @abc.abstractmethod - def tell_pending(self, x): - """Tell the learner that 'x' has been requested such - that it's not suggested again.""" - - @abc.abstractmethod - def remove_unfinished(self): + def remove_unfinished(self) -> None: """Remove uncomputed data from the learner.""" @abc.abstractmethod - def loss(self, real=True): + def loss(self, real: bool = True) -> float: """Return the loss for the current state of the learner. Parameters @@ -139,7 +161,7 @@ def loss(self, real=True): """ @abc.abstractmethod - def ask(self, n, tell_pending=True): + def ask(self, n: int, tell_pending: bool = True) -> tuple[list[Any], list[float]]: """Choose the next 'n' points to evaluate. Parameters @@ -157,15 +179,11 @@ def _get_data(self) -> Any: pass @abc.abstractmethod - def _set_data(self, data: Any) -> None: - pass - - @abc.abstractmethod - def new(self): + def new(self) -> BaseLearner: """Return a new learner with the same function and parameters.""" pass - def copy_from(self, other): + def copy_from(self, other: BaseLearner) -> None: """Copy over the data from another learner. Parameters @@ -175,7 +193,7 @@ def copy_from(self, other): """ self._set_data(other._get_data()) - def save(self, fname, compress=True): + def save(self, fname: Any, compress: bool = True) -> None: """Save the data of the learner into a pickle file. Parameters @@ -189,7 +207,7 @@ def save(self, fname, compress=True): data = self._get_data() save(fname, data, compress) - def load(self, fname, compress=True): + def load(self, fname: Any, compress: bool = True) -> None: """Load the data of a learner from a pickle file. Parameters @@ -246,10 +264,10 @@ def load_dataframe( in the `pandas.DataFrame`. """ - def __getstate__(self): + def __getstate__(self) -> Any: return cloudpickle.dumps(self.__dict__) - def __setstate__(self, state): + def __setstate__(self, state: Any) -> None: self.__dict__ = cloudpickle.loads(state) diff --git a/adaptive/learner/data_saver.py b/adaptive/learner/data_saver.py index 44088e2cc..65d2fd326 100644 --- a/adaptive/learner/data_saver.py +++ b/adaptive/learner/data_saver.py @@ -3,7 +3,8 @@ import functools from collections import OrderedDict from collections.abc import Callable -from typing import Any +from os import PathLike +from typing import Any, Generic from adaptive.learner.base_learner import BaseLearner, LearnerType from adaptive.utils import copy_docstring_from @@ -17,11 +18,11 @@ with_pandas = False -def _to_key(x): +def _to_key(x: pandas.Series) -> Any: return tuple(x.values) if x.values.size > 1 else x.item() -class DataSaver(BaseLearner): +class DataSaver(BaseLearner, Generic[LearnerType]): """Save extra data associated with the values that need to be learned. Parameters @@ -41,26 +42,26 @@ class DataSaver(BaseLearner): >>> learner = DataSaver(_learner, arg_picker=itemgetter('y')) """ - def __init__(self, learner: LearnerType, arg_picker: Callable) -> None: + def __init__(self, learner: LearnerType, arg_picker: Callable[[Any], Any]) -> None: self.learner = learner self.extra_data: OrderedDict[Any, Any] = OrderedDict() self.function = learner.function self.arg_picker = arg_picker - def new(self) -> DataSaver: + def new(self) -> DataSaver[BaseLearner]: """Return a new `DataSaver` with the same `arg_picker` and `learner`.""" return DataSaver(self.learner.new(), self.arg_picker) @copy_docstring_from(BaseLearner.ask) - def ask(self, *args, **kwargs): + def ask(self, *args: Any, **kwargs: Any) -> tuple[list[Any], list[float]]: return self.learner.ask(*args, **kwargs) @copy_docstring_from(BaseLearner.loss) - def loss(self, *args, **kwargs): + def loss(self, *args: Any, **kwargs: Any) -> float: return self.learner.loss(*args, **kwargs) @copy_docstring_from(BaseLearner.remove_unfinished) - def remove_unfinished(self, *args, **kwargs): + def remove_unfinished(self, *args: Any, **kwargs: Any) -> None: return self.learner.remove_unfinished(*args, **kwargs) def __getattr__(self, attr: str) -> Any: @@ -76,7 +77,7 @@ def tell(self, x: Any, result: Any) -> None: def tell_pending(self, x: Any) -> None: self.learner.tell_pending(x) - def to_dataframe( # type: ignore[override] + def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -114,14 +115,14 @@ def to_dataframe( # type: ignore[override] ] return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, df: pandas.DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", extra_data_name: str = "extra_data", input_names: tuple[str, ...] = (), - **kwargs, + **kwargs: Any, ) -> None: """Load the data from a `pandas.DataFrame` into the learner. @@ -161,37 +162,44 @@ def _set_data( learner_data, self.extra_data = data self.learner._set_data(learner_data) - def __getstate__(self) -> tuple[LearnerType, Callable, OrderedDict]: - return ( # type: ignore[return-value] + def __getstate__( + self, + ) -> tuple[LearnerType, Callable[[Any], Any], OrderedDict[Any, Any]]: + return ( self.learner, self.arg_picker, self.extra_data, ) - def __setstate__(self, state: tuple[LearnerType, Callable, OrderedDict]) -> None: + def __setstate__( + self, state: tuple[LearnerType, Callable[[Any], Any], OrderedDict[Any, Any]] + ) -> None: learner, arg_picker, extra_data = state - self.__init__(learner, arg_picker) # type: ignore[misc] + type(self).__init__(self, learner, arg_picker) self.extra_data = extra_data @copy_docstring_from(BaseLearner.save) - def save(self, fname, compress=True) -> None: - # We copy this method because the 'DataSaver' is not a - # subclass of the 'BaseLearner'. + def save(self, fname: str | PathLike[str], compress: bool = True) -> None: BaseLearner.save(self, fname, compress) @copy_docstring_from(BaseLearner.load) - def load(self, fname, compress=True) -> None: - # We copy this method because the 'DataSaver' is not a - # subclass of the 'BaseLearner'. + def load(self, fname: str | PathLike[str], compress: bool = True) -> None: BaseLearner.load(self, fname, compress) -def _ds(learner_type, arg_picker, *args, **kwargs): +def _ds( + learner_type: Callable[..., LearnerType], + arg_picker: Callable[[Any], Any], + *args: Any, + **kwargs: Any, +) -> DataSaver[LearnerType]: args = args[2:] # functools.partial passes the first 2 arguments in 'args'! return DataSaver(learner_type(*args, **kwargs), arg_picker) -def make_datasaver(learner_type, arg_picker): +def make_datasaver( + learner_type: Callable[..., LearnerType], arg_picker: Callable[[Any], Any] +) -> functools.partial[DataSaver[LearnerType]]: """Create a `DataSaver` of a `learner_type` that can be instantiated with the `learner_type`'s key-word arguments. diff --git a/adaptive/learner/integrator_coeffs.py b/adaptive/learner/integrator_coeffs.py index 862f76eb0..f96654b05 100644 --- a/adaptive/learner/integrator_coeffs.py +++ b/adaptive/learner/integrator_coeffs.py @@ -4,9 +4,29 @@ from collections import defaultdict from fractions import Fraction from functools import cache +from typing import TYPE_CHECKING, cast import numpy as np import scipy.linalg +from numpy.typing import NDArray + +if TYPE_CHECKING: + # These module attributes are provided lazily by __getattr__. + eps: np.float64 + ns: tuple[int, int, int, int] + xi: list[NDArray[np.float64]] + V: list[NDArray[np.float64]] + V_inv: list[NDArray[np.float64]] + Vcond: list[float] + T_left: NDArray[np.float64] + T_right: NDArray[np.float64] + hint: float + min_sep: np.float64 + ndiv_max: int + k: NDArray[np.int_] + alpha: NDArray[np.float64] + gamma: NDArray[np.float64] + b_def: list[NDArray[np.float64]] def legendre(n: int) -> list[list[Fraction]]: @@ -30,7 +50,7 @@ def legendre(n: int) -> list[list[Fraction]]: return result -def newton(n: int) -> np.ndarray: +def newton(n: int) -> NDArray[np.float64]: """Compute the monomial coefficients of the Newton polynomial over the nodes of the n-point Clenshaw-Curtis quadrature rule. """ @@ -105,10 +125,11 @@ def scalar_product(a: list[Fraction], b: list[Fraction]) -> Fraction: c[i + j] += a[j] * bi # Calculate the definite integral from -1 to 1. - return 2 * sum(c[i] / (i + 1) for i in range(0, lc, 2)) # type: ignore[return-value] + # There is at least one term, so sum does not return its integer start value. + return cast(Fraction, 2 * sum(c[i] / (i + 1) for i in range(0, lc, 2))) -def calc_bdef(ns: tuple[int, int, int, int]) -> list[np.ndarray]: +def calc_bdef(ns: tuple[int, int, int, int]) -> list[NDArray[np.float64]]: """Calculate the decompositions of Newton polynomials (over the nodes of the n-point Clenshaw-Curtis quadrature rule) in terms of Legandre polynomials. @@ -134,7 +155,7 @@ def calc_bdef(ns: tuple[int, int, int, int]) -> list[np.ndarray]: return result -def calc_V(x: np.ndarray, n: int) -> np.ndarray: +def calc_V(x: NDArray[np.float64], n: int) -> NDArray[np.float64]: V = [np.ones(x.shape), x.copy()] for i in range(2, n): V.append((2 * i - 1) / i * x * V[-1] - (i - 1) / i * V[-2]) @@ -144,7 +165,7 @@ def calc_V(x: np.ndarray, n: int) -> np.ndarray: @cache -def _coefficients(): +def _coefficients() -> dict[str, object]: """Compute the coefficients on demand, in order to avoid doing linear algebra on import.""" eps = np.spacing(1) @@ -157,7 +178,7 @@ def _coefficients(): # Compute the Vandermonde-like matrix and its inverse. V = [calc_V(x, n) for x, n in zip(xi, ns)] - V_inv = list(map(scipy.linalg.inv, V)) + V_inv: list[NDArray[np.float64]] = list(map(scipy.linalg.inv, V)) Vcond = [ scipy.linalg.norm(a, 2) * scipy.linalg.norm(b, 2) for a, b in zip(V, V_inv) ] @@ -187,7 +208,7 @@ def _coefficients(): return locals() -def __getattr__(name): +def __getattr__(name: str) -> object: try: return _coefficients()[name] except KeyError: diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index d6ee9ef1d..824cfdda7 100644 --- a/adaptive/learner/integrator_learner.py +++ b/adaptive/learner/integrator_learner.py @@ -3,18 +3,19 @@ import sys from collections import defaultdict -from collections.abc import Callable +from collections.abc import Callable, Iterable, Iterator, Sequence from math import sqrt from operator import attrgetter -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, cast import cloudpickle import numpy as np +from numpy.typing import NDArray from scipy.linalg import norm from sortedcontainers import SortedSet from adaptive.learner import integrator_coeffs as coeff -from adaptive.learner.base_learner import BaseLearner +from adaptive.learner.base_learner import BaseLearner, _Bound from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import assign_defaults, cache_latest, restore @@ -26,8 +27,20 @@ except ModuleNotFoundError: with_pandas = False +if TYPE_CHECKING: + from holoviews.element import Path -def _downdate(c: np.ndarray, nans: list[int], depth: int) -> np.ndarray: + class _IntervalSet(Protocol): + def __iter__(self) -> Iterator[_Interval]: ... + def add(self, value: _Interval, /) -> None: ... + def update(self, values: Iterable[_Interval], /) -> None: ... +else: + Path = Any + + +def _downdate( + c: NDArray[np.float64], nans: list[int], depth: int +) -> NDArray[np.float64]: # This is algorithm 5 from the thesis of Pedro Gonnet. b = coeff.b_def[depth].copy() m = coeff.ns[depth] - 1 @@ -47,7 +60,7 @@ def _downdate(c: np.ndarray, nans: list[int], depth: int) -> np.ndarray: return c -def _zero_nans(fx: np.ndarray) -> list[int]: +def _zero_nans(fx: NDArray[np.float64]) -> list[int]: """Caution: this function modifies fx.""" nans = [] for i in range(len(fx)): @@ -57,7 +70,7 @@ def _zero_nans(fx: np.ndarray) -> list[int]: return nans -def _calc_coeffs(fx: np.ndarray, depth: int) -> np.ndarray: +def _calc_coeffs(fx: NDArray[np.float64], depth: int) -> NDArray[np.float64]: """Caution: this function modifies fx.""" nans = _zero_nans(fx) c_new = coeff.V_inv[depth] @ fx @@ -136,7 +149,7 @@ class _Interval: "removed", ] - def __init__(self, a: int | float, b: int | float, depth: int, rdepth: int) -> None: + def __init__(self, a: float, b: float, depth: int, rdepth: int) -> None: self.children: list[_Interval] = [] self.data: dict[float, float] = {} self.a = a @@ -150,10 +163,10 @@ def __init__(self, a: int | float, b: int | float, depth: int, rdepth: int) -> N self.ndiv: int self.parent: _Interval | None self.err: float - self.c: np.ndarray + self.c: NDArray[np.float64] @classmethod - def make_first(cls, a: int, b: int, depth: int = 2) -> _Interval: + def make_first(cls, a: float, b: float, depth: int = 2) -> _Interval: ival = _Interval(a, b, depth, rdepth=1) ival.ndiv = 0 ival.parent = None @@ -161,7 +174,7 @@ def make_first(cls, a: int, b: int, depth: int = 2) -> _Interval: return ival @property - def T(self) -> np.ndarray: + def T(self) -> NDArray[np.float64]: """Get the correct shift matrix. Should only be called on children of a split interval. @@ -178,7 +191,7 @@ def refinement_complete(self, depth: int) -> bool: return False return all(p in self.data for p in self.points(depth)) - def points(self, depth: int | None = None) -> np.ndarray: + def points(self, depth: int | None = None) -> NDArray[np.float64]: if depth is None: depth = self.depth a = self.a @@ -220,17 +233,17 @@ def update_heuristic_err(self, value: float) -> None: continue child.update_heuristic_err(value / 2) - def calc_err(self, c_old: np.ndarray) -> float: + def calc_err(self, c_old: NDArray[np.float64]) -> float: c_new = self.c c_diff = np.zeros(max(len(c_old), len(c_new))) c_diff[: len(c_old)] = c_old c_diff[: len(c_new)] -= c_new - c_diff = norm(c_diff) - self.err = (self.b - self.a) * c_diff + diff: float = norm(c_diff) + self.err = (self.b - self.a) * diff for child in self.children: if child.depth_complete is None: child.update_heuristic_err(self.err / 2) - return c_diff + return diff def calc_ndiv(self) -> None: assert self.parent is not None @@ -252,7 +265,7 @@ def update_ndiv_recursively(self) -> None: for child in self.children: child.update_ndiv_recursively() - def complete_process(self, depth: int) -> tuple[bool, bool] | tuple[bool, np.bool_]: + def complete_process(self, depth: int) -> tuple[bool | np.bool_, bool | np.bool_]: """Calculate the integral contribution and error from this interval, and update the done leaves of all ancestor intervals.""" assert self.depth_complete is None or self.depth_complete == depth - 1 @@ -260,7 +273,7 @@ def complete_process(self, depth: int) -> tuple[bool, bool] | tuple[bool, np.boo fx = [self.data[k] for k in self.points(depth)] self.fx = np.array(fx) - force_split = False # This may change when refining + force_split: bool | np.bool_ = False # This may change when refining first_ival = self.parent is None and depth == 2 @@ -307,11 +320,11 @@ def complete_process(self, depth: int) -> tuple[bool, bool] | tuple[bool, np.boo ival = self.parent old_leaves = set() while ival is not None: - unused_children = [ - child for child in ival.children if child.done_leaves is not None - ] - - if not all(len(child.done_leaves) for child in unused_children): # type: ignore[arg-type] + if not all( + child.done_leaves + for child in ival.children + if child.done_leaves is not None + ): break if ival.done_leaves is None: @@ -340,8 +353,29 @@ def __repr__(self) -> str: return " ".join(lst) +_Bounds: TypeAlias = Sequence[_Bound] | NDArray[Any] +_Data: TypeAlias = tuple[ + list[_Interval], + dict[float, float], + set[float], + list[float], + dict[float, set[_Interval]], + set[_Interval], + _Interval, +] +_State: TypeAlias = tuple[bytes, _Bounds, float, _Data] + + class IntegratorLearner(BaseLearner): - def __init__(self, function: Callable, bounds: tuple[int, int], tol: float) -> None: + data: dict[float, float] + pending_points: set[float] + + def __init__( + self, + function: Callable[[float], Any], + bounds: _Bounds, + tol: float, + ) -> None: """ Parameters ---------- @@ -375,7 +409,7 @@ def __init__(self, function: Callable, bounds: tuple[int, int], tol: float) -> N plot : hv.Scatter Plots all the points that are evaluated. """ - self.function = function # type: ignore + self.function: Callable[..., Any] = function self.bounds = bounds self.tol = tol self.max_ivals = 1000 @@ -383,16 +417,17 @@ def __init__(self, function: Callable, bounds: tuple[int, int], tol: float) -> N self.data = {} self.pending_points = set() self._stack: list[float] = [] - self.x_mapping: dict[float, SortedSet] = defaultdict( + self.x_mapping: defaultdict[float, _IntervalSet] = defaultdict( lambda: SortedSet([], key=attrgetter("rdepth")) ) self.ivals: set[_Interval] = set() - ival = _Interval.make_first(*self.bounds) + # Bounds are documented as a pair; preserve the original container. + ival = _Interval.make_first(*cast("tuple[float, float]", self.bounds)) self.add_ival(ival) self.first_ival = ival def new(self) -> IntegratorLearner: - """Create a copy of `~adaptive.Learner2D` without the data.""" + """Create a copy without the data.""" return IntegratorLearner(self.function, self.bounds, self.tol) @property @@ -433,11 +468,13 @@ def tell(self, point: float, value: float) -> None: assert ival in self.ivals self.priority_split.append(ival) - def tell_pending(self): + # The integrator tracks pending points itself; preserve this legacy no-op + # signature, which does not accept the base method's point argument. + def tell_pending(self) -> None: # type: ignore[override] # ty: ignore[incompatible-method-override] pass def propagate_removed(self, ival: _Interval) -> None: - def _propagate_removed_down(ival): + def _propagate_removed_down(ival: _Interval) -> None: ival.removed = True self.ivals.discard(ival) @@ -489,7 +526,7 @@ def pop_from_stack(self, n: int) -> tuple[list[float], list[float]]: ] return points, loss_improvements - def remove_unfinished(self): + def remove_unfinished(self) -> None: pass def _fill_stack(self) -> list[float]: @@ -528,7 +565,7 @@ def _fill_stack(self) -> list[float]: return self._stack @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] """Number of evaluated points.""" return len(self.data) @@ -546,7 +583,7 @@ def err(self) -> float: err = np.inf return err - def done(self): + def done(self) -> bool | np.bool_: err = self.err igral = self.igral err_excess = sum(i.err for i in self.approximating_intervals if i.removed) @@ -558,10 +595,10 @@ def done(self): ) @cache_latest - def loss(self, real=True): + def loss(self, real: bool = True) -> float: return abs(abs(self.igral) * self.tol - self.err) - def plot(self): + def plot(self) -> Path: hv = ensure_holoviews() ivals = sorted(self.ivals, key=attrgetter("a")) if not self.data: @@ -569,11 +606,11 @@ def plot(self): xs, ys = zip(*[(x, y) for ival in ivals for x, y in sorted(ival.data.items())]) return hv.Path((xs, ys)) - def to_numpy(self): + def to_numpy(self) -> NDArray[np.floating | np.integer]: """Data as NumPy array of size (npoints, 2).""" return np.array(sorted(self.data.items())) - def to_dataframe( # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -613,7 +650,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -642,7 +679,7 @@ def load_dataframe( # type: ignore[override] """ raise NotImplementedError - def _get_data(self): + def _get_data(self) -> _Data: # Change the defaultdict of SortedSets to a normal dict of sets. x_mapping = {k: set(v) for k, v in self.x_mapping.items()} @@ -656,7 +693,7 @@ def _get_data(self): self.first_ival, ) - def _set_data(self, data): + def _set_data(self, data: _Data) -> None: ( self.priority_split, self.data, @@ -678,7 +715,7 @@ def _set_data(self, data): for k, _set in x_mapping.items(): self.x_mapping[k].update(_set) - def __getstate__(self): + def __getstate__(self) -> _State: return ( cloudpickle.dumps(self.function), self.bounds, @@ -686,8 +723,9 @@ def __getstate__(self): self._get_data(), ) - def __setstate__(self, state): - function, bounds, tol, data = state - function = cloudpickle.loads(function) - self.__init__(function, bounds, tol) + def __setstate__(self, state: _State) -> None: + function_pickle, bounds, tol, data = state + function = cloudpickle.loads(function_pickle) + # Retain virtual dispatch for subclasses that reuse this pickle state. + type(self).__init__(self, function, bounds, tol) self._set_data(data) diff --git a/adaptive/learner/learner1D.py b/adaptive/learner/learner1D.py index dfc3f81c4..344e34683 100644 --- a/adaptive/learner/learner1D.py +++ b/adaptive/learner/learner1D.py @@ -3,20 +3,23 @@ import collections.abc import itertools import math -from collections.abc import Callable, Sequence +from collections.abc import Callable, Mapping, Sequence from copy import copy, deepcopy -from typing import Any, TypeAlias +from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar, cast import cloudpickle import numpy as np -from sortedcollections.recipes import ItemSortedDict -from sortedcontainers.sorteddict import SortedDict +from numpy.typing import NDArray -from adaptive.learner.base_learner import BaseLearner, uses_nth_neighbors +from adaptive.learner._sorted_types import ItemSortedDict, SortedDict +from adaptive.learner.base_learner import ( + BaseLearner, + _Bound, + uses_nth_neighbors, +) from adaptive.learner.learnerND import volume from adaptive.learner.triangulation_backend import simplex_volume_in_embedding from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Float, Int, Real from adaptive.utils import ( assign_defaults, cache_latest, @@ -32,21 +35,39 @@ with_pandas = False -# Commonly used types -Interval: TypeAlias = tuple[float, float] | tuple[float, float, int] +if TYPE_CHECKING: + from holoviews.core import Overlay +else: + Overlay = Any + +Interval: TypeAlias = tuple[float, float] +_Qual: TypeAlias = tuple[float, float, int] +_IntervalKey = TypeVar("_IntervalKey", bound=Interval | _Qual) NeighborsType: TypeAlias = SortedDict[float, list[float | None]] -# Types for loss_per_interval functions -XsType0: TypeAlias = tuple[float, float] -YsType0: TypeAlias = tuple[float, float] | tuple[np.ndarray, np.ndarray] -XsType1: TypeAlias = tuple[float | None, float | None, float | None, float | None] -YsType1: TypeAlias = ( - tuple[float | None, float | None, float | None, float | None] - | tuple[np.ndarray | None, np.ndarray | None, np.ndarray | None, np.ndarray | None] -) -XsTypeN: TypeAlias = tuple[float | None, ...] -YsTypeN: TypeAlias = tuple[float | None, ...] | tuple[np.ndarray | None, ...] +_ScaledValue: TypeAlias = float | NDArray[Any] +# The bulk tell path can store user-supplied sequences without conversion. +Value: TypeAlias = _ScaledValue | Sequence[float] +_Bounds: TypeAlias = Sequence[_Bound] | NDArray[Any] +# Callers may specialize the tuples for their configured neighbor count and +# scalar or vector output; the learner does not know either statically. +_IntervalLossCallback: TypeAlias = Callable[[Any, Any], float] +IntervalLoss: TypeAlias = Callable[[Sequence[float], Sequence[_ScaledValue]], float] +NeighborLoss: TypeAlias = Callable[ + [Sequence[float | None], Sequence[_ScaledValue | None]], float +] +# AverageLearner1D uses the same pickle layout with samples in the data slot. +_SampleData: TypeAlias = Mapping[float, dict[int, float]] +_StoredData: TypeAlias = Mapping[float, Value] | _SampleData +_PickleState: TypeAlias = tuple[ + bytes, + tuple[float, ...], + _IntervalLossCallback, + dict[Interval, float], + dict[Interval, float], + _StoredData, +] __all__ = [ "uniform_loss", @@ -60,7 +81,7 @@ @uses_nth_neighbors(0) -def uniform_loss(xs: XsType0, ys: YsType0) -> Float: +def uniform_loss(xs: Sequence[float], ys: Sequence[Value]) -> float: """Loss function that samples the domain uniformly. Works with `~adaptive.Learner1D` only. @@ -80,7 +101,7 @@ def uniform_loss(xs: XsType0, ys: YsType0) -> Float: @uses_nth_neighbors(0) -def default_loss(xs: XsType0, ys: YsType0) -> Float: +def default_loss(xs: Sequence[float], ys: Sequence[Value]) -> float: """Calculate loss on a single interval. Currently returns the rescaled length of the interval. If one of the @@ -89,42 +110,48 @@ def default_loss(xs: XsType0, ys: YsType0) -> Float: """ dx = xs[1] - xs[0] if isinstance(ys[0], collections.abc.Iterable): - dy_vec = np.array([abs(a - b) for a, b in zip(*ys)]) + vectors = cast("Sequence[Sequence[float]]", ys) + dy_vec = np.array([abs(a - b) for a, b in zip(*vectors)]) return np.hypot(dx, dy_vec).max() else: - dy = ys[1] - ys[0] + scalars = cast("Sequence[float]", ys) + dy = scalars[1] - scalars[0] return np.hypot(dx, dy) @uses_nth_neighbors(0) -def abs_min_log_loss(xs: XsType0, ys: YsType0) -> Float: +def abs_min_log_loss(xs: Sequence[float], ys: Sequence[Value]) -> float: """Calculate loss of a single interval that prioritizes the absolute minimum.""" - ys_log: YsType0 = tuple(np.log(np.abs(y).min()) for y in ys) # type: ignore[assignment] + ys_log = tuple(np.log(np.abs(y).min()) for y in ys) return default_loss(xs, ys_log) @uses_nth_neighbors(1) -def triangle_loss(xs: XsType1, ys: YsType1) -> Float: +def triangle_loss(xs: Sequence[float | None], ys: Sequence[Value | None]) -> float: assert len(xs) == 4 x = [x for x in xs if x is not None] y = [y for y in ys if y is not None] if len(x) == 2: # we do not have enough points for a triangle - return x[1] - x[0] # type: ignore[operator] + return x[1] - x[0] N = len(x) - 2 # number of constructed triangles + pts: list[tuple[float, ...]] + vol: Callable[[Sequence[tuple[float, ...]]], float] if isinstance(y[0], collections.abc.Iterable): - pts = [(x, *y) for x, y in zip(x, y)] # type: ignore[misc] + vectors = cast("Sequence[Sequence[float]]", y) + pts = [(x, *v) for x, v in zip(x, vectors)] vol = simplex_volume_in_embedding else: - pts = list(zip(x, y)) + scalars = cast("Sequence[float]", y) + pts = list(zip(x, scalars)) vol = volume return sum(vol(pts[i : i + 3]) for i in range(N)) / N def resolution_loss_function( - min_length: Real = 0, max_length: Real = 1 -) -> Callable[[XsType0, YsType0], Float]: + min_length: float = 0, max_length: float = 1 +) -> IntervalLoss: """Loss function that is similar to the `default_loss` function, but you can set the maximum and minimum size of an interval. @@ -147,7 +174,7 @@ def resolution_loss_function( """ @uses_nth_neighbors(0) - def resolution_loss(xs: XsType0, ys: YsType0) -> Float: + def resolution_loss(xs: Sequence[float], ys: Sequence[Value]) -> float: loss = uniform_loss(xs, ys) if loss < min_length: # Return zero such that this interval won't be chosen again @@ -162,17 +189,18 @@ def resolution_loss(xs: XsType0, ys: YsType0) -> Float: def curvature_loss_function( - area_factor: Real = 1, euclid_factor: Real = 0.02, horizontal_factor: Real = 0.02 -) -> Callable[[XsType1, YsType1], Float]: + area_factor: float = 1, euclid_factor: float = 0.02, horizontal_factor: float = 0.02 +) -> NeighborLoss: # XXX: add a doc-string @uses_nth_neighbors(1) - def curvature_loss(xs: XsType1, ys: YsType1) -> Float: - xs_middle = xs[1:3] - ys_middle = ys[1:3] + def curvature_loss(xs: Sequence[float | None], ys: Sequence[Value | None]) -> float: + # Only the outside neighbors can be missing. + xs_middle = cast("Sequence[float]", xs[1:3]) + ys_middle = cast("Sequence[Value]", ys[1:3]) triangle_loss_ = triangle_loss(xs, ys) default_loss_ = default_loss(xs_middle, ys_middle) - dx = xs_middle[1] - xs_middle[0] # type: ignore[operator] + dx = xs_middle[1] - xs_middle[0] return ( area_factor * (triangle_loss_**0.5) + euclid_factor * default_loss_ @@ -182,7 +210,7 @@ def curvature_loss(xs: XsType1, ys: YsType1) -> Float: return curvature_loss -def linspace(x_left: Real, x_right: Real, n: Int) -> list[Float]: +def linspace(x_left: float, x_right: float, n: int) -> list[float]: """This is equivalent to 'np.linspace(x_left, x_right, n, endpoint=False)[1:]', but it is 15-30 times faster for small 'n'.""" @@ -194,7 +222,7 @@ def linspace(x_left: Real, x_right: Real, n: Int) -> list[Float]: return [x_left + step * i for i in range(1, n)] -def _get_neighbors_from_array(xs: np.ndarray) -> NeighborsType: +def _get_neighbors_from_array(xs: NDArray[Any]) -> NeighborsType: xs = np.sort(xs) xs_left = np.roll(xs, 1).tolist() xs_right = np.roll(xs, -1).tolist() @@ -259,30 +287,31 @@ class Learner1D(BaseLearner): decorator for more information. """ + data: dict[float, Value] + pending_points: set[float] + def __init__( self, - function: Callable[[Real], Float | np.ndarray], - bounds: tuple[Real, Real], - loss_per_interval: Callable[[XsTypeN, YsTypeN], Float] | None = None, - ): - self.function = function # type: ignore - - if loss_per_interval is not None and hasattr( - loss_per_interval, "nth_neighbors" - ): - self.nth_neighbors = loss_per_interval.nth_neighbors - else: - self.nth_neighbors = 0 + function: Callable[[float], Any], + bounds: _Bounds, + loss_per_interval: _IntervalLossCallback | None = None, + ) -> None: + # NumPy bounds participate in the same arithmetic without coercion. + bounds = cast("Sequence[float]", bounds) + self.function: Callable[..., Any] = function + self.nth_neighbors: int = getattr(loss_per_interval, "nth_neighbors", 0) - self.loss_per_interval = loss_per_interval or default_loss + self.loss_per_interval: _IntervalLossCallback = ( + loss_per_interval or default_loss + ) # When the scale changes by a factor 2, the losses are # recomputed. This is tunable such that we can test # the learners behavior in the tests. self._recompute_losses_factor = 2 - self.data: dict[Real, Real] = {} - self.pending_points: set[Real] = set() + self.data = {} + self.pending_points = set() # A dict {x_n: [x_{n-1}, x_{n+1}]} for quick checking of local # properties. @@ -290,15 +319,17 @@ def __init__( self.neighbors_combined: NeighborsType = SortedDict() # Bounding box [[minx, maxx], [miny, maxy]]. - self._bbox = [list(bounds), [np.inf, -np.inf]] + self._bbox: list[list[_ScaledValue]] = [list(bounds), [np.inf, -np.inf]] # Data scale (maxx - minx), (maxy - miny) self._scale = [bounds[1] - bounds[0], 0] self._oldscale = deepcopy(self._scale) # A LossManager storing the loss function for each interval x_n. - self.losses = loss_manager(self._scale[0]) - self.losses_combined = loss_manager(self._scale[0]) + self.losses: ItemSortedDict[Interval, float] = loss_manager(self._scale[0]) + self.losses_combined: ItemSortedDict[Interval, float] = loss_manager( + self._scale[0] + ) # The precision in 'x' below which we set losses to 0. self._dx_eps = 2 * max(np.abs(bounds)) * np.finfo(float).eps @@ -332,13 +363,13 @@ def vdim(self) -> int: return 1 return self._vdim - def to_numpy(self): + def to_numpy(self) -> NDArray[Any]: """Data as NumPy array of size ``(npoints, 2)`` if ``learner.function`` returns a scalar and ``(npoints, 1+vdim)`` if ``learner.function`` returns a vector of length ``vdim``. """ return np.array([(x, *np.atleast_1d(y)) for x, y in sorted(self.data.items())]) - def to_dataframe( # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -380,7 +411,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -408,14 +439,17 @@ def load_dataframe( # type: ignore[override] y_name : str, optional The ``y_name`` used in ``to_dataframe``, by default "y" """ - self.tell_many(df[x_name].values, df[y_name].values) + self.tell_many( + cast("Sequence[float]", df[x_name].values), + cast("Sequence[Value]", df[y_name].values), + ) if with_default_function_args: self.function = partial_function_from_dataframe( self.function, df, function_prefix ) @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] """Number of evaluated points.""" return len(self.data) @@ -435,16 +469,18 @@ def loss(self, real: bool = True) -> float: max_interval, max_loss = losses.peekitem(0) return max_loss - def _scale_x(self, x: Float | None) -> Float | None: + def _scale_x(self, x: float | None) -> float | None: if x is None: return None return x / self._scale[0] - def _scale_y(self, y: Float | np.ndarray | None) -> Float | np.ndarray | None: + def _scale_y(self, y: Value | None) -> _ScaledValue | None: if y is None: return None y_scale = self._scale[1] or 1 - return y / y_scale + # The NumPy scale handles reflected division for raw sequences + # stored by tell_many; single tells already normalize them to arrays. + return cast("_ScaledValue", y) / y_scale def _get_point_by_index(self, ind: int) -> float | None: if ind < 0 or ind >= len(self.neighbors): @@ -463,16 +499,15 @@ def _get_loss_in_interval(self, x_left: float, x_right: float) -> float: end = i + nn + 2 xs = [self._get_point_by_index(i) for i in range(start, end)] - ys = [self.data.get(x, None) for x in xs] + ys = [self.data.get(x) if x is not None else None for x in xs] xs_scaled = tuple(self._scale_x(x) for x in xs) ys_scaled = tuple(self._scale_y(y) for y in ys) - # we need to compute the loss for this interval return self.loss_per_interval(xs_scaled, ys_scaled) def _update_interpolated_loss_in_interval( - self, x_left: float, x_right: float + self, x_left: float | None, x_right: float | None ) -> None: if x_left is None or x_right is None: return @@ -486,6 +521,7 @@ def _update_interpolated_loss_in_interval( dx = x_right - x_left while b != x_right: b = self.neighbors_combined[a][1] + assert b is not None self.losses_combined[a, b] = (b - a) * loss / dx a = b @@ -499,7 +535,8 @@ def _update_losses(self, x: float, real: bool = True) -> None: a, b = self._find_neighbors(x, self.neighbors_combined) # (a, b) is splitted into (a, x) and (x, b) so if (a, b) exists - self.losses_combined.pop((a, b), None) # we get rid of (a, b). + if a is not None and b is not None: + self.losses_combined.pop((a, b), None) if real: # We need to update all interpolated losses in the interval @@ -511,11 +548,14 @@ def _update_losses(self, x: float, real: bool = True) -> None: # Since 'x' is in between (x_left, x_right), # we get rid of the interval. - self.losses.pop((x_left, x_right), None) - self.losses_combined.pop((x_left, x_right), None) + if x_left is not None and x_right is not None: + self.losses.pop((x_left, x_right), None) + self.losses_combined.pop((x_left, x_right), None) elif x_left is not None and x_right is not None: # 'x' happens to be in between two real points, # so we can interpolate the losses. + # Combined neighbors exist when there are real neighbors. + assert a is not None and b is not None dx = x_right - x_left loss = self.losses[x_left, x_right] self.losses_combined[a, x] = (x - a) * loss / dx @@ -532,7 +572,7 @@ def _update_losses(self, x: float, real: bool = True) -> None: self.losses_combined[x, b] = float("inf") @staticmethod - def _find_neighbors(x: float, neighbors: NeighborsType) -> Any: + def _find_neighbors(x: float, neighbors: NeighborsType) -> Sequence[float | None]: if x in neighbors: return neighbors[x] pos = neighbors.bisect_left(x) @@ -545,10 +585,12 @@ def _update_neighbors(self, x: float, neighbors: NeighborsType) -> None: if x not in neighbors: # The point is new x_left, x_right = self._find_neighbors(x, neighbors) neighbors[x] = [x_left, x_right] - neighbors.get(x_left, [None, None])[1] = x - neighbors.get(x_right, [None, None])[0] = x + if x_left is not None: + neighbors[x_left][1] = x + if x_right is not None: + neighbors[x_right][0] = x - def _update_scale(self, x: float, y: Float | np.ndarray) -> None: + def _update_scale(self, x: float, y: _ScaledValue) -> None: """Update the scale with which the x and y-values are scaled. For a learner where the function returns a single scalar the scale @@ -557,11 +599,14 @@ def _update_scale(self, x: float, y: Float | np.ndarray) -> None: When the function returns a vector the learners y-scale is set by the level with the the largest peak-to-peak value. """ - self._bbox[0][0] = min(self._bbox[0][0], x) - self._bbox[0][1] = max(self._bbox[0][1], x) - self._scale[0] = self._bbox[0][1] - self._bbox[0][0] + x_bounds = cast("list[float]", self._bbox[0]) + x_bounds[0] = min(x_bounds[0], x) + x_bounds[1] = max(x_bounds[1], x) + self._scale[0] = x_bounds[1] - x_bounds[0] if y is not None: if self.vdim > 1: + y_min: _ScaledValue + y_max: _ScaledValue try: y_min = np.nanmin([self._bbox[1][0], y], axis=0) y_max = np.nanmax([self._bbox[1][1], y], axis=0) @@ -571,11 +616,14 @@ def _update_scale(self, x: float, y: Float | np.ndarray) -> None: self._bbox[1] = [y_min, y_max] self._scale[1] = np.max(y_max - y_min) else: - self._bbox[1][0] = min(self._bbox[1][0], y) - self._bbox[1][1] = max(self._bbox[1][1], y) - self._scale[1] = self._bbox[1][1] - self._bbox[1][0] - - def tell(self, x: float, y: Float | Sequence[Float] | np.ndarray) -> None: + # Zero-dimensional and length-one arrays act as scalars here. + y_bounds = cast("list[float]", self._bbox[1]) + scalar = cast(float, y) + y_bounds[0] = min(y_bounds[0], scalar) + y_bounds[1] = max(y_bounds[1], scalar) + self._scale[1] = y_bounds[1] - y_bounds[0] + + def tell(self, x: float, y: Value) -> None: if x in self.data: # The point is already evaluated before return @@ -620,13 +668,8 @@ def tell_pending(self, x: float) -> None: def tell_many( self, - xs: Sequence[Float] | np.ndarray, - ys: ( - Sequence[Float] - | Sequence[Sequence[Float]] - | Sequence[np.ndarray] - | np.ndarray - ), + xs: Sequence[float] | NDArray[Any], + ys: Sequence[Value] | NDArray[Any], *, force: bool = False, ) -> None: @@ -655,13 +698,14 @@ def tell_many( # Update scale self._bbox[0] = [points_combined.min(), points_combined.max()] self._bbox[1] = [values.min(axis=0), values.max(axis=0)] - self._scale[0] = self._bbox[0][1] - self._bbox[0][0] + x_bounds = cast("list[float]", self._bbox[0]) + self._scale[0] = x_bounds[1] - x_bounds[0] self._scale[1] = np.max(self._bbox[1][1] - self._bbox[1][0]) self._oldscale = deepcopy(self._scale) # Find the intervals for which the losses should be calculated. intervals, intervals_combined = ( - [(x_m, x_r) for x_m, (x_l, x_r) in neighbors.items()][:-1] + [(x_m, x_r) for x_m, (_, x_r) in neighbors.items() if x_r is not None] for neighbors in (self.neighbors, self.neighbors_combined) ) @@ -671,7 +715,7 @@ def tell_many( self.losses[ival] = self._get_loss_in_interval(*ival) # List with "real" intervals that have interpolated intervals inside - to_interpolate: list[tuple[Real, Real]] = [] + to_interpolate: list[Interval] = [] self.losses_combined = loss_manager(self._scale[0]) for ival in intervals_combined: @@ -685,7 +729,7 @@ def tell_many( self.losses_combined[ival] = np.inf x_left, x_right = ival a, b = to_interpolate[-1] if to_interpolate else (None, None) - if b == x_left and (a, b) not in self.losses: + if a is not None and b == x_left and (a, b) not in self.losses: # join (a, b) and (x_left, x_right) → (a, x_right) to_interpolate[-1] = (a, x_right) else: @@ -707,7 +751,7 @@ def ask(self, n: int, tell_pending: bool = True) -> tuple[list[float], list[floa return points, loss_improvements - def _missing_bounds(self) -> list[Real]: + def _missing_bounds(self) -> list[float]: missing_bounds = [] for b in copy(self.__missing_bounds): if b in self.data: @@ -741,7 +785,7 @@ def _ask_points_without_adding(self, n: int) -> tuple[list[float], list[float]]: a, b = self.bounds return np.linspace(a, b, n).tolist(), [np.inf] * n - quals = loss_manager(self._scale[0]) + quals: ItemSortedDict[_Qual, float] = loss_manager(self._scale[0]) if len(missing_bounds) > 0: # There is at least one point in between the bounds. all_points = list(self.data.keys()) + list(self.pending_points) @@ -772,8 +816,8 @@ def _ask_points_without_adding(self, n: int) -> tuple[list[float], list[float]]: quals[(ival[0], ival[1], 2)] = loss_ival / 2 else: quals.pop(qual, None) - *xs, n = qual - quals[(*xs, n + 1)] = loss_qual * n / (n + 1) + x_l, x_r, n = qual + quals[x_l, x_r, n + 1] = loss_qual * n / (n + 1) points = list( itertools.chain.from_iterable( @@ -794,12 +838,12 @@ def _ask_points_without_adding(self, n: int) -> tuple[list[float], list[float]]: return points, loss_improvements def _loss( - self, mapping: dict[Interval, float], ival: Interval - ) -> tuple[float, Interval]: + self, mapping: Mapping[_IntervalKey, float], ival: _IntervalKey + ) -> tuple[float, Interval | _Qual]: loss = mapping[ival] return finite_loss(ival, loss, self._scale[0]) - def plot(self, *, scatter_or_line: str = "scatter"): + def plot(self, *, scatter_or_line: str = "scatter") -> Overlay: """Returns a plot of the evaluated data. Parameters @@ -839,15 +883,17 @@ def remove_unfinished(self) -> None: self.losses_combined = deepcopy(self.losses) self.neighbors_combined = deepcopy(self.neighbors) - def _get_data(self) -> dict[float, float]: + def _get_data(self) -> _StoredData: return self.data - def _set_data(self, data: dict[float, float]) -> None: + def _set_data(self, data: _StoredData) -> None: if data: - xs, ys = zip(*data.items()) + # Each learner restores only its own representation of the data. + values = cast("Mapping[float, Value]", data) + xs, ys = zip(*values.items()) self.tell_many(xs, ys) - def __getstate__(self): + def __getstate__(self) -> _PickleState: return ( cloudpickle.dumps(self.function), tuple(self.bounds), @@ -857,25 +903,28 @@ def __getstate__(self): self._get_data(), ) - def __setstate__(self, state): - function, bounds, loss_per_interval, losses, losses_combined, data = state - function = cloudpickle.loads(function) - self.__init__(function, bounds, loss_per_interval) + def __setstate__(self, state: _PickleState) -> None: + function_bytes, bounds, loss_per_interval, losses, losses_combined, data = state + function = cloudpickle.loads(function_bytes) + # Retain virtual dispatch for AverageLearner1D and other subclasses. + type(self).__init__(self, function, bounds, loss_per_interval) self._set_data(data) self.losses.update(losses) self.losses_combined.update(losses_combined) -def loss_manager(x_scale: float) -> ItemSortedDict[Interval, float]: - def sort_key(ival, loss): - loss, ival = finite_loss(ival, loss, x_scale) - return -loss, ival +def loss_manager(x_scale: float) -> ItemSortedDict[_IntervalKey, float]: + def sort_key(ival: _IntervalKey, loss: float) -> tuple[float, Interval | _Qual]: + finite, key = finite_loss(ival, loss, x_scale) + return -finite, key sorted_dict = ItemSortedDict(sort_key) return sorted_dict -def finite_loss(ival: Interval, loss: float, x_scale: float) -> tuple[float, Interval]: +def finite_loss( + ival: Interval | _Qual, loss: float, x_scale: float +) -> tuple[float, Interval | _Qual]: """Get the so-called finite_loss of an interval in order to be able to sort intervals that have infinite loss.""" # If the loss is infinite we return the @@ -885,7 +934,7 @@ def finite_loss(ival: Interval, loss: float, x_scale: float) -> tuple[float, Int if len(ival) == 3: # Used when constructing quals. Last item is # the number of points inside the qual. - loss /= ival[2] # type: ignore[misc] + loss /= ival[2] # We round the loss to 12 digits such that losses # are equal up to numerical precision will be considered diff --git a/adaptive/learner/learner2D.py b/adaptive/learner/learner2D.py index 40c267a09..01cd8a776 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -3,19 +3,21 @@ import itertools import warnings from collections import OrderedDict -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Sequence, Sized from copy import copy from math import sqrt +from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, cast import cloudpickle import numpy as np +from numpy.typing import ArrayLike, NDArray from scipy import interpolate from scipy.interpolate import CloughTocher2DInterpolator, LinearNDInterpolator +from scipy.spatial import Delaunay from adaptive.learner.base_learner import BaseLearner from adaptive.learner.triangulation_backend import simplex_volume_in_embedding from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Bool, Float, Real from adaptive.utils import ( assign_defaults, cache_latest, @@ -30,10 +32,54 @@ except ModuleNotFoundError: with_pandas = False +_Point: TypeAlias = tuple[float, float] +_PointInput: TypeAlias = ( + Sequence[float | np.floating | np.integer] | NDArray[np.floating | np.integer] +) +_Value: TypeAlias = ( + float + | np.floating + | np.integer + | Iterable[float] + | NDArray[np.floating | np.integer] +) +_TriangleLoss: TypeAlias = Callable[ + [Any], NDArray[np.floating[Any] | np.integer[Any]] | Sequence[float] +] +_State: TypeAlias = tuple[ + bytes, + tuple[_Point, _Point], + _TriangleLoss, + OrderedDict[_Point, float], + dict[_Point, _Value], +] + +if TYPE_CHECKING: + from holoviews.core import HoloMap, Overlay + + # The SciPy interpolators expose these attributes at runtime but do not + # document them as part of their public interface. + class _TriangulationData(Protocol): + points: NDArray[np.float64] + simplices: NDArray[np.int32] + neighbors: NDArray[np.int32] + + class _LinearInterpolatorData(Protocol): + tri: _TriangulationData + values: NDArray[np.float64] + + def __call__(self, *coords: NDArray[np.float64]) -> NDArray[np.float64]: ... + + class _CloughTocherData(Protocol): + grad: NDArray[np.float64] + +else: + HoloMap = Overlay = Any + # Learner2D and helper functions. -def deviations(ip: LinearNDInterpolator) -> np.ndarray: +def deviations(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Returns the deviation of the linear estimate. Is useful when defining custom loss functions. @@ -47,11 +93,13 @@ def deviations(ip: LinearNDInterpolator) -> np.ndarray: deviations : numpy.ndarray The deviation per triangle. """ - values = ip.values / (np.ptp(ip.values, axis=0).max() or 1) - gradients = CloughTocher2DInterpolator(ip.tri, values, tol=1e-6).grad + interp = cast("_LinearInterpolatorData", ip) + values = interp.values / (np.max(np.ptp(interp.values, axis=0)) or 1) + cubic = CloughTocher2DInterpolator(cast(Delaunay, interp.tri), values, tol=1e-6) + gradients = cast("_CloughTocherData", cubic).grad - simplices = ip.tri.simplices - p = ip.tri.points[simplices] + simplices = interp.tri.simplices + p = interp.tri.points[simplices] vs = values[simplices] gs = gradients[simplices] @@ -65,7 +113,7 @@ def deviations(ip: LinearNDInterpolator) -> np.ndarray: return np.swapaxes(devs, 0, 1) -def areas(ip: LinearNDInterpolator) -> np.ndarray: +def areas(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Returns the area per triangle of the triangulation inside a `LinearNDInterpolator` instance. @@ -80,13 +128,14 @@ def areas(ip: LinearNDInterpolator) -> np.ndarray: areas : numpy.ndarray The area per triangle in ``ip.tri``. """ - p = ip.tri.points[ip.tri.simplices] + tri = cast("_LinearInterpolatorData", ip).tri + p = tri.points[tri.simplices] q = p[:, :-1, :] - p[:, -1, None, :] areas = abs(q[:, 0, 0] * q[:, 1, 1] - q[:, 0, 1] * q[:, 1, 0]) / 2 return areas -def uniform_loss(ip: LinearNDInterpolator) -> np.ndarray: +def uniform_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Loss function that samples the domain uniformly. Works with `~adaptive.Learner2D` only. @@ -119,7 +168,7 @@ def uniform_loss(ip: LinearNDInterpolator) -> np.ndarray: def resolution_loss_function( min_distance: float = 0, max_distance: float = 1 -) -> Callable[[LinearNDInterpolator], np.ndarray]: +) -> Callable[[LinearNDInterpolator], NDArray[np.float64]]: """Loss function that is similar to the `default_loss` function, but you can set the maximimum and minimum size of a triangle. @@ -142,7 +191,7 @@ def resolution_loss_function( >>> learner = adaptive.Learner2D(f, bounds=[(-1, -1), (1, 1)], loss_per_triangle=loss) """ - def resolution_loss(ip): + def resolution_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: loss = default_loss(ip) A = areas(ip) @@ -158,7 +207,7 @@ def resolution_loss(ip): return resolution_loss -def minimize_triangle_surface_loss(ip: LinearNDInterpolator) -> np.ndarray: +def minimize_triangle_surface_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Loss function that is similar to the distance loss function in the `~adaptive.Learner1D`. The loss is the area spanned by the 3D vectors of the vertices. @@ -185,12 +234,15 @@ def minimize_triangle_surface_loss(ip: LinearNDInterpolator) -> np.ndarray: ... loss_per_triangle=minimize_triangle_surface_loss) >>> """ - tri = ip.tri + interp = cast("_LinearInterpolatorData", ip) + tri = interp.tri points = tri.points[tri.simplices] - values = ip.values[tri.simplices] - values = values / (np.ptp(ip.values, axis=0).max() or 1) + values = interp.values[tri.simplices] + values = values / (np.max(np.ptp(interp.values, axis=0)) or 1) - def _get_vectors(points): + def _get_vectors( + points: NDArray[np.float64], + ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: delta = points - points[:, -1, :][:, None, :] vectors = delta[:, :2, :] return vectors[:, 0, :], vectors[:, 1, :] @@ -204,7 +256,7 @@ def _get_vectors(points): return np.linalg.norm(np.cross(a, b) / 2, axis=1) -def default_loss(ip: LinearNDInterpolator) -> np.ndarray: +def default_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Loss function that combines `deviations` and `areas` of the triangles. Works with `~adaptive.Learner2D` only. @@ -228,7 +280,7 @@ def thresholded_loss_function( lower_threshold: float | None = None, upper_threshold: float | None = None, priority_factor: float = 0.1, -) -> Callable[[LinearNDInterpolator], np.ndarray]: +) -> Callable[[LinearNDInterpolator], NDArray[np.float64]]: """ Factory function to create a custom loss function that deprioritizes values above an upper threshold and below a lower threshold. @@ -251,7 +303,7 @@ def thresholded_loss_function( A custom loss function that can be used with Learner2D. """ - def custom_loss(ip: LinearNDInterpolator) -> np.ndarray: + def custom_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Loss function that deprioritizes values outside an upper and lower threshold. Parameters @@ -266,8 +318,9 @@ def custom_loss(ip: LinearNDInterpolator) -> np.ndarray: losses = default_loss(ip) if lower_threshold is not None or upper_threshold is not None: - simplices = ip.tri.simplices - values = ip.values[simplices] + interp = cast("_LinearInterpolatorData", ip) + simplices = interp.tri.simplices + values = interp.values[simplices] if lower_threshold is not None: mask_lower = (values < lower_threshold).all(axis=(1, -1)) if mask_lower.any(): @@ -283,11 +336,15 @@ def custom_loss(ip: LinearNDInterpolator) -> np.ndarray: return custom_loss -def _cross_2d(x, y): +def _cross_2d( + x: NDArray[np.float64], y: NDArray[np.float64] +) -> NDArray[np.float64] | np.float64: return x[..., 0] * y[..., 1] - x[..., 1] * y[..., 0] -def choose_point_in_triangle(triangle: np.ndarray, max_badness: int) -> np.ndarray: +def choose_point_in_triangle( + triangle: NDArray[np.float64], max_badness: int +) -> NDArray[np.float64]: """Choose a new point in inside a triangle. If the ratio of the longest edge of the triangle squared @@ -313,7 +370,7 @@ def choose_point_in_triangle(triangle: np.ndarray, max_badness: int) -> np.ndarr area = 0.5 * _cross_2d(b - a, c - a) triangle_roll = np.roll(triangle, 1, axis=0) edge_lengths = np.linalg.norm(triangle - triangle_roll, axis=1) - i = edge_lengths.argmax() + i = np.argmax(edge_lengths) # We multiply by sqrt(3) / 4 such that a equilateral triangle has badness=1 badness = (edge_lengths[i] ** 2 / area) * (sqrt(3) / 4) @@ -324,7 +381,7 @@ def choose_point_in_triangle(triangle: np.ndarray, max_badness: int) -> np.ndarr return point -def triangle_loss(ip): +def triangle_loss(ip: LinearNDInterpolator) -> list[float]: r"""Computes the average of the volumes of the simplex combined with each neighbouring point. @@ -343,18 +400,19 @@ def triangle_loss(ip): same result as the `adaptive.LearnerND`\s `~adaptive.learner.learnerND.triangle_loss`. """ - tri = ip.tri + interp = cast("_LinearInterpolatorData", ip) + tri = interp.tri - def get_neighbors(i, ip): + def get_neighbors(i: int, ip: _LinearInterpolatorData) -> NDArray[np.float64]: n = np.array([tri.simplices[n] for n in tri.neighbors[i] if n != -1]) # remove the vertices that are in the simplex c = np.setdiff1d(n.reshape(-1), tri.simplices[i]) return np.concatenate((tri.points[c], ip.values[c]), axis=-1) simplices = np.concatenate( - [tri.points[tri.simplices], ip.values[tri.simplices]], axis=-1 + [tri.points[tri.simplices], interp.values[tri.simplices]], axis=-1 ) - neighbors = [get_neighbors(i, ip) for i in range(len(tri.simplices))] + neighbors = [get_neighbors(i, interp) for i in range(len(tri.simplices))] return [ sum(simplex_volume_in_embedding(np.vstack([simplex, n])) for n in neighbors[i]) @@ -371,9 +429,8 @@ class Learner2D(BaseLearner): 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. + bounds : sequence of pairs + Bounds ``[(a1, b1), (a2, b2)]``, one pair 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 @@ -426,11 +483,14 @@ class Learner2D(BaseLearner): over each triangle. """ + data: dict[_Point, _Value] + pending_points: set[_Point] + def __init__( self, - function: Callable, - bounds: tuple[tuple[Real, Real], tuple[Real, Real]], - loss_per_triangle: Callable | None = None, + function: Callable[[_Point], Any], + bounds: Sequence[Sequence[float | np.floating | np.integer]] | NDArray[Any], + loss_per_triangle: _TriangleLoss | None = None, ) -> None: self.ndim = len(bounds) self._vdim: int | None = None @@ -440,17 +500,18 @@ def __init__( (float(bounds[1][0]), float(bounds[1][1])), ) self.data = OrderedDict() - self._stack = OrderedDict() + self._stack: OrderedDict[_Point, float] = OrderedDict() self.pending_points = set() self.xy_mean = np.mean(self.bounds, axis=1) self._xy_scale = np.ptp(self.bounds, axis=1) - self.aspect_ratio = 1 + self.aspect_ratio: float = 1 - self._bounds_points = list(itertools.product(*bounds)) + self._bounds_points = cast(list[_Point], list(itertools.product(*bounds))) self._stack.update(dict.fromkeys(self._bounds_points, np.inf)) - self.function = function # type: ignore - self._ip = self._ip_combined = None + self.function: Callable[..., Any] = function + self._ip: LinearNDInterpolator | None = None + self._ip_combined: LinearNDInterpolator | None = None self.stack_size = 10 @@ -458,14 +519,14 @@ def new(self) -> Learner2D: return Learner2D(self.function, self.bounds, self.loss_per_triangle) @property - def xy_scale(self) -> np.ndarray: + def xy_scale(self) -> NDArray[np.float64]: xy_scale = self._xy_scale if self.aspect_ratio == 1: return xy_scale else: return np.array([xy_scale[0], xy_scale[1] / self.aspect_ratio]) - def to_numpy(self): + def to_numpy(self) -> NDArray[np.floating | np.integer]: """Data as NumPy array of size ``(npoints, 3)`` if ``learner.function`` returns a scalar and ``(npoints, 2+vdim)`` if ``learner.function`` returns a vector of length ``vdim``. """ @@ -473,7 +534,7 @@ def to_numpy(self): [(x, y, *np.atleast_1d(z)) for (x, y), z in sorted(self.data.items())] ) - def to_dataframe( # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -519,7 +580,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -527,7 +588,7 @@ def load_dataframe( # type: ignore[override] x_name: str = "x", y_name: str = "y", z_name: str = "z", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -551,22 +612,20 @@ def load_dataframe( # type: ignore[override] The ``z_name`` used in ``to_dataframe``, by default "z" """ data = df.set_index([x_name, y_name])[z_name].to_dict() - self._set_data(data) + self._set_data(cast("dict[_Point, _Value]", data)) if with_default_function_args: self.function = partial_function_from_dataframe( self.function, df, function_prefix ) - def _scale(self, points: list[tuple[float, float]] | np.ndarray) -> np.ndarray: - points = np.asarray(points, dtype=float) - return (points - self.xy_mean) / self.xy_scale + def _scale(self, points: ArrayLike) -> NDArray[np.float64]: + return (np.asarray(points, dtype=float) - self.xy_mean) / self.xy_scale - def _unscale(self, points: np.ndarray) -> np.ndarray: - points = np.asarray(points, dtype=float) - return points * self.xy_scale + self.xy_mean + def _unscale(self, points: ArrayLike) -> NDArray[np.float64]: + return np.asarray(points, dtype=float) * self.xy_scale + self.xy_mean @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] """Number of evaluated points.""" return len(self.data) @@ -581,7 +640,7 @@ def vdim(self) -> int: if self._vdim is None and self.data: try: value = next(iter(self.data.values())) - self._vdim = len(value) + self._vdim = len(cast(Sized, value)) except TypeError: self._vdim = 1 return self._vdim or 1 @@ -594,7 +653,7 @@ def bounds_are_done(self) -> bool: def interpolated_on_grid( self, n: int | None = None - ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + ) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]: """Get the interpolated data on a grid. Parameters @@ -613,7 +672,7 @@ def interpolated_on_grid( if n is None: # Calculate how many grid points are needed. # factor from A=√3/4 * a² (equilateral triangle) - n = int(0.658 / sqrt(areas(ip).min())) + n = int(0.658 / sqrt(np.min(areas(ip)))) n = max(n, 10) # The bounds of the linspace should be (-0.5, 0.5) but because of @@ -622,25 +681,32 @@ def interpolated_on_grid( # boundary would be outside of the domain. See #181. eps = 1e-13 xs = ys = np.linspace(-0.5 + eps, 0.5 - eps, n) - zs = ip(xs[:, None], ys[None, :] * self.aspect_ratio).squeeze() + interp = cast("_LinearInterpolatorData", ip) + zs = interp(xs[:, None], ys[None, :] * self.aspect_ratio).squeeze() xs, ys = self._unscale(np.vstack([xs, ys]).T).T return xs, ys, zs - def _data_in_bounds(self) -> tuple[np.ndarray, np.ndarray]: + def _data_in_bounds( + self, + ) -> tuple[NDArray[np.floating | np.integer], NDArray[np.float64]]: if self.data: points = np.array(list(self.data.keys())) values = np.array(list(self.data.values()), dtype=float) + ll: NDArray[np.float64] + ur: NDArray[np.float64] ll, ur = np.reshape(self.bounds, (2, 2)).T inds = np.all(np.logical_and(ll <= points, points <= ur), axis=1) return points[inds], values[inds].reshape(-1, self.vdim) return np.zeros((0, 2)), np.zeros((0, self.vdim), dtype=float) - def _data_interp(self) -> tuple[np.ndarray | list[tuple[float, float]], np.ndarray]: + def _data_interp( + self, + ) -> tuple[NDArray[np.float64] | list[_Point], NDArray[np.float64]]: if self.pending_points: points = list(self.pending_points) if self.bounds_are_done: ip = self.interpolator(scaled=True) - values = ip(self._scale(points)) + values = cast("_LinearInterpolatorData", ip)(self._scale(points)) else: # Without the bounds the interpolation cannot be done properly, # so we just set everything to zero. @@ -648,7 +714,9 @@ def _data_interp(self) -> tuple[np.ndarray | list[tuple[float, float]], np.ndarr return points, values return np.zeros((0, 2)), np.zeros((0, self.vdim), dtype=float) - def _data_combined(self) -> tuple[np.ndarray, np.ndarray]: + def _data_combined( + self, + ) -> tuple[NDArray[np.floating | np.integer], NDArray[np.float64]]: points, values = self._data_in_bounds() if not self.pending_points: return points, values @@ -708,32 +776,30 @@ def _interpolator_combined(self) -> LinearNDInterpolator: self._ip_combined = interpolate.LinearNDInterpolator(points, values) return self._ip_combined - def inside_bounds(self, xy: tuple[float, float]) -> Bool: + def inside_bounds(self, xy: _PointInput) -> bool | np.bool_: x, y = xy (xmin, xmax), (ymin, ymax) = self.bounds return xmin <= x <= xmax and ymin <= y <= ymax - def tell(self, point: tuple[float, float], value: float | Iterable[float]) -> None: - point = tuple(point) # type: ignore[assignment] - self.data[point] = value - if not self.inside_bounds(point): + def tell(self, point: _PointInput, value: _Value) -> None: + xy = cast(_Point, tuple(point)) + self.data[xy] = value + if not self.inside_bounds(xy): return - self.pending_points.discard(point) + self.pending_points.discard(xy) self._ip = None self._ip_combined = None - self._stack.pop(point, None) + self._stack.pop(xy, None) - def tell_pending(self, point: tuple[float, float]) -> None: - point = tuple(point) # type: ignore[assignment] - if not self.inside_bounds(point): + def tell_pending(self, point: _PointInput) -> None: + xy = cast(_Point, tuple(point)) + if not self.inside_bounds(xy): return - self.pending_points.add(point) + self.pending_points.add(xy) self._ip_combined = None - self._stack.pop(point, None) + self._stack.pop(xy, None) - def _fill_stack( - self, stack_till: int = 1 - ) -> tuple[list[tuple[float, float]], list[float]]: + def _fill_stack(self, stack_till: int = 1) -> tuple[list[_Point], list[float]]: if len(self.data) + len(self.pending_points) < self.ndim + 1: raise ValueError("too few points...") @@ -741,21 +807,31 @@ def _fill_stack( ip = self._interpolator_combined() losses = self.loss_per_triangle(ip) + # Point selection marks used triangles with -inf. Copy only results + # that cannot be updated in place. + if isinstance(losses, np.ndarray): + if losses.dtype.kind in "iu" or not losses.flags.writeable: + losses = losses.astype(float) + elif not isinstance(losses, list): + losses = list(losses) + interp = cast("_LinearInterpolatorData", ip) + + # np.clip results in numerical precision problems + # https://github.com/python-adaptive/adaptive/issues/7 + def clip(x: float, lo: float, up: float) -> float: + return max(lo, min(up, x)) points_new = [] losses_new = [] for _j, _ in enumerate(losses): - jsimplex = np.argmax(losses) - triangle = ip.tri.points[ip.tri.simplices[jsimplex]] - point_new = choose_point_in_triangle(triangle, max_badness=5) - point_new = tuple(self._unscale(point_new)) - - # np.clip results in numerical precision problems - # https://github.com/python-adaptive/adaptive/issues/7 - clip = lambda x, lo, up: max(lo, min(up, x)) # noqa: E731 + jsimplex = int(np.argmax(losses)) + tri = interp.tri + triangle = tri.points[tri.simplices[jsimplex]] + point = choose_point_in_triangle(triangle, max_badness=5) + xy = tuple(self._unscale(point)) point_new = ( - clip(point_new[0], *self.bounds[0]), - clip(point_new[1], *self.bounds[1]), + clip(xy[0], *self.bounds[0]), + clip(xy[1], *self.bounds[1]), ) loss_new = losses[jsimplex] @@ -774,7 +850,7 @@ def _fill_stack( def ask( self, n: int, tell_pending: bool = True - ) -> tuple[list[tuple[float, float] | np.ndarray], list[float]]: + ) -> tuple[list[_Point], list[float]]: # Even if tell_pending is False we add the point such that _fill_stack # will return new points, later we remove these points if needed. points = list(self._stack.keys()) @@ -810,7 +886,7 @@ def loss(self, real: bool = True) -> float: return np.inf ip = self.interpolator(scaled=True) if real else self._interpolator_combined() losses = self.loss_per_triangle(ip) - return losses.max() + return float(np.max(losses)) def remove_unfinished(self) -> None: self.pending_points = set() @@ -819,7 +895,7 @@ def remove_unfinished(self) -> None: if p not in self.data: self._stack[p] = np.inf - def plot(self, n=None, tri_alpha=0.0): + def plot(self, n: int | None = None, tri_alpha: float = 0.0) -> Overlay | HoloMap: r"""Plot the Learner2D's current state. This plot function interpolates the data on a regular grid. @@ -855,7 +931,7 @@ def plot(self, n=None, tri_alpha=0.0): if len(self.data) >= 4: ip = self.interpolator(scaled=True) - x, y, z = self.interpolated_on_grid(n) + _, _, z = self.interpolated_on_grid(n) if self.vdim > 1: ims = { @@ -867,7 +943,8 @@ def plot(self, n=None, tri_alpha=0.0): im = hv.Image(np.rot90(z), bounds=lbrt) if tri_alpha: - points = self._unscale(ip.tri.points[ip.tri.simplices]) + tri = cast("_LinearInterpolatorData", ip).tri + points = self._unscale(tri.points[tri.simplices]) points = np.pad( points[:, [0, 1, 2, 0], :], pad_width=((0, 0), (0, 1), (0, 0)), @@ -884,17 +961,17 @@ def plot(self, n=None, tri_alpha=0.0): line_width=0.5, alpha=tri_alpha, tools=[] ) - def _get_data(self) -> dict[tuple[float, float], Float | np.ndarray]: + def _get_data(self) -> dict[_Point, _Value]: return self.data - def _set_data(self, data: dict[tuple[float, float], Float | np.ndarray]) -> None: + def _set_data(self, data: dict[_Point, _Value]) -> None: self.data = data # Remove points from stack if they already exist for point in copy(self._stack): if point in self.data: self._stack.pop(point) - def __getstate__(self): + def __getstate__(self) -> _State: return ( cloudpickle.dumps(self.function), self.bounds, @@ -903,9 +980,10 @@ def __getstate__(self): self._get_data().copy(), ) - def __setstate__(self, state): - function, bounds, loss_per_triangle, _stack, data = state - function = cloudpickle.loads(function) - self.__init__(function, bounds, loss_per_triangle) + def __setstate__(self, state: _State) -> None: + function_pickle, bounds, loss_per_triangle, _stack, data = state + function = cloudpickle.loads(function_pickle) + # Retain virtual dispatch for subclasses that reuse this pickle state. + type(self).__init__(self, function, bounds, loss_per_triangle) self._set_data(data) self._stack = _stack diff --git a/adaptive/learner/learnerND.py b/adaptive/learner/learnerND.py index e8a5b5f02..d9501c6f7 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -5,18 +5,43 @@ import math import random from collections import OrderedDict -from collections.abc import Iterable +from collections.abc import Callable, Iterable, Mapping, Sequence, Sized from copy import deepcopy +from typing import ( + TYPE_CHECKING, + Any, + Literal, + Protocol, + SupportsFloat, + TypeAlias, + TypeVar, + cast, +) import numpy as np +import numpy.typing as npt import scipy.spatial from scipy import interpolate from sortedcontainers import SortedKeyList -from adaptive.learner.base_learner import BaseLearner, uses_nth_neighbors -from adaptive.learner.triangulation import fast_det +from adaptive.learner.base_learner import ( + BaseLearner, + _Bound, + uses_nth_neighbors, +) +from adaptive.learner.triangulation import ( + _Point, + _PointLike, + _PointsLike, + _Simplex, + _SimplexSet, + fast_det, +) from adaptive.learner.triangulation_backend import ( Triangulation, + _BatchedTriangulation, + _LearnerTriangulation, + _SimplicesProxy, circumsphere, point_in_simplex, resolve_triangulation_class, @@ -31,6 +56,13 @@ restore, ) +if TYPE_CHECKING: + from holoviews.core import Overlay + from holoviews.element import Image, Path + from plotly.graph_objects import Figure, Mesh3d +else: + Overlay = Image = Path = Figure = Mesh3d = Any + try: import pandas @@ -40,13 +72,58 @@ with_pandas = False -def to_list(inp): +_Array: TypeAlias = npt.NDArray[Any] +_Value: TypeAlias = float | Sequence[float] | _Array +_Values: TypeAlias = Sequence[_Value] | _Array +_Loss: TypeAlias = Callable[[_Array, _Array, float], SupportsFloat | _Array] +_NeighborLoss: TypeAlias = Callable[ + [_Array, _Array, float, list[_Array | None], list[_Value | None]], SupportsFloat +] +# The user can specialize the simplex and neighbor types for their function. +_SimplexLossCallback: TypeAlias = ( + Callable[[Any, Any, float], SupportsFloat | _Array] + | Callable[[Any, Any, float, Any, Any], SupportsFloat] +) +_Bounds: TypeAlias = Sequence[Sequence[_Bound]] | _Array | scipy.spatial.ConvexHull +_QueueItem: TypeAlias = tuple[float, _Simplex, _Simplex | None] +_T = TypeVar("_T") + + +class _NeighborMetadata(Protocol): + nth_neighbors: int + + +class _CurvatureLoss(_NeighborMetadata, Protocol): + def __call__( + self, + simplex: _PointsLike, + values: _Values, + value_scale: float, + neighbors: Sequence[_PointLike | None], + neighbor_values: Sequence[_Value | None], + ) -> float: ... + + +class _SliceInterpolator(Protocol): + # SciPy supports multiple broadcastable coordinate arguments. + def __call__(self, *coords: float | _Array) -> _Array: ... + + +class _SimplexQueue(Protocol): + """The subset of the untyped SortedKeyList interface used here.""" + + def add(self, value: _QueueItem, /) -> None: ... + def pop(self, index: int = -1, /) -> _QueueItem: ... + def __len__(self) -> int: ... + + +def to_list(inp: _T | Iterable[_T]) -> list[_T]: if isinstance(inp, Iterable): return list(inp) return [inp] -def volume(simplex, ys=None): +def volume(simplex: _PointsLike, ys: object = None) -> float: # Notice the parameter ys is there so you can use this volume method as # as loss function matrix = np.subtract(simplex[:-1], simplex[-1], dtype=float) @@ -57,14 +134,14 @@ def volume(simplex, ys=None): return vol -def orientation(simplex): +def orientation(simplex: _PointsLike) -> float: matrix = np.subtract(simplex[:-1], simplex[-1]) # See https://www.jstor.org/stable/2315353 sign, _logdet = np.linalg.slogdet(matrix) return sign -def uniform_loss(simplex, values, value_scale): +def uniform_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> float: """ Uniform loss. @@ -84,7 +161,7 @@ def uniform_loss(simplex, values, value_scale): return volume(simplex) -def std_loss(simplex, values, value_scale): +def std_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> _Array: """ Computes the loss of the simplex based on the standard deviation. @@ -99,10 +176,12 @@ def std_loss(simplex, values, value_scale): Returns ------- - loss : float + loss : numpy.ndarray """ - r = np.linalg.norm(np.std(values, axis=0)) + # NumPy accepts sequences of array rows at runtime, too. + array_like = cast("Sequence[float] | Sequence[Sequence[float]] | _Array", values) + r = np.linalg.norm(np.std(array_like, axis=0)) vol = volume(simplex) dim = len(simplex) - 1 @@ -110,7 +189,7 @@ def std_loss(simplex, values, value_scale): return r.flat * np.power(vol, 1.0 / dim) + vol -def default_loss(simplex, values, value_scale): +def default_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> float: """ Computes the average of the volumes of the simplex. @@ -128,14 +207,21 @@ def default_loss(simplex, values, value_scale): loss : float """ if isinstance(values[0], Iterable): - pts = [(*x, *y) for x, y in zip(simplex, values)] + vectors = cast("Sequence[_PointLike]", values) + pts = [(*x, *y) for x, y in zip(simplex, vectors)] else: - pts = [(*x, y) for x, y in zip(simplex, values)] + pts = [(*x, y) for x, y in zip(simplex, cast("Sequence[float]", values))] return simplex_volume_in_embedding(pts) @uses_nth_neighbors(1) -def triangle_loss(simplex, values, value_scale, neighbors, neighbor_values): +def triangle_loss( + simplex: _PointsLike, + values: _Values, + value_scale: float, + neighbors: Sequence[_PointLike | None], + neighbor_values: Sequence[_Value | None], +) -> float: """ Computes the average of the volumes of the simplex combined with each neighbouring point. @@ -159,23 +245,29 @@ def triangle_loss(simplex, values, value_scale, neighbors, neighbor_values): loss : float """ - neighbors = [n for n in neighbors if n is not None] - neighbor_values = [v for v in neighbor_values if v is not None] - if len(neighbors) == 0: + known_neighbors = [n for n in neighbors if n is not None] + known_neighbor_values = [v for v in neighbor_values if v is not None] + if len(known_neighbors) == 0: return 0 s = [(*x, *to_list(y)) for x, y in zip(simplex, values)] - n = [(*x, *to_list(y)) for x, y in zip(neighbors, neighbor_values)] + n = [(*x, *to_list(y)) for x, y in zip(known_neighbors, known_neighbor_values)] return sum(simplex_volume_in_embedding([*s, neighbor]) for neighbor in n) / len( - neighbors + known_neighbors ) -def curvature_loss_function(exploration=0.05): +def curvature_loss_function(exploration: float = 0.05) -> _CurvatureLoss: # XXX: add doc-string! @uses_nth_neighbors(1) - def curvature_loss(simplex, values, value_scale, neighbors, neighbor_values): + def curvature_loss( + simplex: _PointsLike, + values: _Values, + value_scale: float, + neighbors: Sequence[_PointLike | None], + neighbor_values: Sequence[_Value | None], + ) -> float: """Compute the curvature loss of a simplex. Parameters @@ -209,7 +301,9 @@ def curvature_loss(simplex, values, value_scale, neighbors, neighbor_values): return curvature_loss -def choose_point_in_simplex(simplex, transform=None): +def choose_point_in_simplex( + simplex: _PointsLike, transform: _Array | None = None +) -> _Array: """Choose a new point in inside a simplex. Pick the center of the simplex if the shape is nice (that is, the @@ -237,12 +331,13 @@ def choose_point_in_simplex(simplex, transform=None): # otherwise: the center the longest edge center, _radius = circumsphere(simplex) if point_in_simplex(center, simplex): - point = np.average(simplex, axis=0) + point = np.average(cast("Sequence[Sequence[float]] | _Array", simplex), axis=0) else: distances = scipy.spatial.distance.pdist(simplex) distance_matrix = scipy.spatial.distance.squareform(distances) i, j = np.unravel_index(np.argmax(distance_matrix), distance_matrix.shape) - point = (simplex[i, :] + simplex[j, :]) / 2 + vertices = cast("_Array", simplex) + point = (vertices[i, :] + vertices[j, :]) / 2 if transform is not None: point = np.linalg.solve(transform.T, point) # undo the transform @@ -250,7 +345,9 @@ def choose_point_in_simplex(simplex, transform=None): return point -def _simplex_evaluation_priority(key): +def _simplex_evaluation_priority( + key: _QueueItem, +) -> tuple[float, _Simplex, _Simplex]: # We round the loss to 8 digits such that losses # are equal up to numerical precision will be considered # to be equal. This is needed because we want the learner @@ -324,32 +421,39 @@ class LearnerND(BaseLearner): # Class-level fallback so that learners restored from pickles made # before `triangulation_backend` existed keep working. - _triangulation_class = Triangulation + _triangulation_class = cast("type[_LearnerTriangulation]", Triangulation) + + data: OrderedDict[_Point, _Value] + pending_points: set[_Point] def __init__( self, - func, - bounds, - loss_per_simplex=None, + func: Callable[[Any], Any], + bounds: _Bounds, + loss_per_simplex: _SimplexLossCallback | None = None, *, - anisotropic=False, - triangulation_backend="auto", - ): - self._triangulation_class = resolve_triangulation_class(triangulation_backend) - self._vdim = None + anisotropic: bool = False, + triangulation_backend: str | type[Any] = "auto", + ) -> None: + self._triangulation_class = cast( + "type[_LearnerTriangulation]", + resolve_triangulation_class(triangulation_backend), + ) + self._vdim: int | None = 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: + loss_with_metadata = cast(_NeighborMetadata, self.loss_per_simplex) + if loss_with_metadata.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 + self.nth_neighbors = loss_with_metadata.nth_neighbors else: self.nth_neighbors = 0 @@ -357,6 +461,8 @@ def __init__( self.pending_points = set() self.bounds = bounds + self._bounds_points: list[_Point] + self._interior: scipy.spatial.Delaunay | None if isinstance(bounds, scipy.spatial.ConvexHull): hull_points = bounds.points[bounds.vertices] self._bounds_points = sorted(map(tuple, hull_points)) @@ -364,7 +470,9 @@ def __init__( 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._bbox = tuple( + cast("tuple[float, float]", tuple(map(float, b))) for b in bounds + ) self._interior = None self.ndim = len(self._bbox) @@ -377,23 +485,23 @@ def __init__( f"LearnerND only supports dim >= 2 (got ndim={self.ndim})." ) - self.function = func - self._tri = None - self._losses = {} + self.function: Callable[..., Any] = func + self._tri: _LearnerTriangulation | None = None + self._losses: dict[_Simplex, float] = {} - self._pending_to_simplex = {} # vertex → simplex + self._pending_to_simplex: dict[_Point, _Simplex] = {} # vertex → simplex # triangulation of the pending points inside a specific simplex - self._subtriangulations = {} # simplex → triangulation + self._subtriangulations: dict[_Simplex, _LearnerTriangulation] = {} # 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 = ( + self._min_value: float | None = None + self._max_value: float | None = None + self._old_scale: float | None = None + self._output_multiplier: float = ( 1 # If we do not know anything, do not scale the values ) self._recompute_losses_factor = 1.1 @@ -413,7 +521,9 @@ def __init__( # 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) + self._simplex_queue: _SimplexQueue = SortedKeyList( + key=_simplex_evaluation_priority + ) def new(self) -> LearnerND: """Create a new learner with the same function and bounds.""" @@ -426,12 +536,12 @@ def new(self) -> LearnerND: ) @property - def npoints(self): + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] """Number of evaluated points.""" return len(self.data) @property - def vdim(self): + def vdim(self) -> int: """Length of the output of ``learner.function``. If the output is unsized (when it's a scalar) then `vdim = 1`. @@ -441,12 +551,12 @@ def vdim(self): if self._vdim is None and self.data: try: value = next(iter(self.data.values())) - self._vdim = len(value) + self._vdim = len(cast(Sized, value)) except TypeError: self._vdim = 1 return self._vdim if self._vdim is not None else 1 - def to_numpy(self): + def to_numpy(self) -> _Array: """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``.""" @@ -457,7 +567,7 @@ def _default_point_names(self) -> tuple[str, ...]: return ("x", "y", "z")[: self.ndim] return tuple(f"x{i}" for i in range(self.ndim)) - def to_dataframe( # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -507,14 +617,14 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", point_names: tuple[str, ...] | None = None, value_name: str = "value", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -545,17 +655,17 @@ def load_dataframe( # type: ignore[override] ) @property - def bounds_are_done(self): + def bounds_are_done(self) -> bool: return all(p in self.data for p in self._bounds_points) - def _ip(self): + def _ip(self) -> interpolate.LinearNDInterpolator: """A `scipy.interpolate.LinearNDInterpolator` instance containing the learner's data.""" # XXX: take our own triangulation into account when generating the _ip return interpolate.LinearNDInterpolator(self.points, self.values) @property - def tri(self): + def tri(self) -> _LearnerTriangulation | None: """An `adaptive.learner.triangulation.Triangulation` instance with all the points of the learner.""" if self._tri is not None: @@ -572,17 +682,22 @@ def tri(self): self._update_losses(set(), self._tri.simplices) return self._tri + def _require_tri(self) -> _LearnerTriangulation: + tri = self.tri + assert tri is not None + return tri + @property - def values(self): + def values(self) -> npt.NDArray[np.float64]: """Get the values from `data` as a numpy array.""" return np.array(list(self.data.values()), dtype=float) @property - def points(self): + def points(self) -> npt.NDArray[np.float64]: """Get the points from `data` as a numpy array.""" return np.array(list(self.data.keys()), dtype=float) - def tell(self, point, value): + def tell(self, point: Iterable[float], value: _Value | None) -> None: point = tuple(point) if point in self.data: return # we already know about the point @@ -608,13 +723,13 @@ def tell(self, point, value): to_delete, to_add = tri.add_point(point, simplex, transform=self._transform) self._update_losses(to_delete, to_add) - def get_local_transform_matrix(self, simplex): + def get_local_transform_matrix(self, simplex: _Simplex | None) -> _Array: scale = self._transform - if simplex is None or self.tri is None or not self.anisotropic: + if simplex is None or (tri := self.tri) is None or not self.anisotropic: return scale - neighbors = set.union(*[self.tri.vertex_to_simplices[i] for i in simplex]) + neighbors = set.union(*[tri.vertex_to_simplices[i] for i in simplex]) indices = set.union(set(), *neighbors) points = np.array([self.points[i] for i in indices]) @@ -650,11 +765,11 @@ def get_local_transform_matrix(self, simplex): m = np.dot(scale_along_gradient, scale) return m.T - def _simplex_exists(self, simplex): + def _simplex_exists(self, simplex: Iterable[int]) -> bool: simplex = tuple(sorted(simplex)) - return simplex in self.tri.simplices + return simplex in self._require_tri().simplices - def inside_bounds(self, point): + def inside_bounds(self, point: _PointLike) -> bool | np.bool_: """Check whether a point is inside the bounds.""" if self._interior is not None: return self._interior.find_simplex(point, tol=1e-8) >= 0 @@ -664,7 +779,9 @@ def inside_bounds(self, point): (mn - eps) <= p <= (mx + eps) for p, (mn, mx) in zip(point, self._bbox) ) - def tell_pending(self, point, *, simplex=None): + def tell_pending( + self, point: Iterable[float], *, simplex: _Simplex | None = None + ) -> None: point = tuple(point) if not self.inside_bounds(point): return @@ -680,54 +797,67 @@ def tell_pending(self, point, *, simplex=None): continue self._update_subsimplex_losses(simpl, to_add) - def _simplices_containing_point(self, point, simplex=None): + def _simplices_containing_point( + self, point: _Point, simplex: _Simplex | None = None + ) -> list[_Simplex]: """All simplices of the triangulation containing `point`, found from the `simplex` hint when given.""" - if hasattr(self.tri, "simplices_containing"): + tri = self._require_tri() + if hasattr(tri, "simplices_containing"): # Rust backend: one call instead of a point_in_simplex loop. - return self.tri.simplices_containing(point, simplex=simplex) + return cast(_BatchedTriangulation, tri).simplices_containing( + point, simplex=simplex + ) - simplex = tuple(simplex or self.tri.locate_point(point)) + simplex = tuple(simplex or tri.locate_point(point)) if not simplex: return [] # Simplex is empty if the pending point is outside the # triangulation, then you do not have subtriangles - simplices = [self.tri.vertex_to_simplices[i] for i in simplex] + simplices = [tri.vertex_to_simplices[i] for i in simplex] neighbors = set.union(*simplices) # Neighbours also includes the simplex itself - return [s for s in neighbors if self.tri.point_in_simplex(point, s)] + return [s for s in neighbors if tri.point_in_simplex(point, s)] - def _add_pending_point_to_simplex(self, point, simplex): + def _add_pending_point_to_simplex( + self, point: _Point, simplex: _Simplex + ) -> tuple[_SimplexSet, _SimplexSet]: """Insert `point` into the subtriangulation of `simplex`, which must contain the point.""" if simplex not in self._subtriangulations: - vertices = self.tri.get_vertices(simplex) + vertices = self._require_tri().get_vertices(simplex) self._subtriangulations[simplex] = self._triangulation_class(vertices) self._pending_to_simplex[point] = simplex return self._subtriangulations[simplex].add_point(point) - def _try_adding_pending_point_to_simplex(self, point, simplex): + def _try_adding_pending_point_to_simplex( + self, point: _Point, simplex: _Simplex + ) -> tuple[_SimplexSet, _SimplexSet] | tuple[None, None]: # try to insert it - if not self.tri.point_in_simplex(point, simplex): + if not self._require_tri().point_in_simplex(point, simplex): return None, None return self._add_pending_point_to_simplex(point, simplex) - def _update_subsimplex_losses(self, simplex, new_subsimplices): + def _update_subsimplex_losses( + self, simplex: _Simplex, new_subsimplices: Iterable[_Simplex] + ) -> None: loss = self._losses[simplex] - loss_density = loss / self.tri.volume(simplex) + loss_density = loss / self._require_tri().volume(simplex) subtriangulation = self._subtriangulations[simplex] for subsimplex in new_subsimplices: subloss = subtriangulation.volume(subsimplex) * loss_density self._simplex_queue.add((subloss, simplex, subsimplex)) - def _ask_and_tell_pending(self, n=1): + def _ask_and_tell_pending(self, n: int = 1) -> tuple[list[_Point], list[float]]: xs, losses = zip(*(self._ask() for _ in range(n))) return list(xs), list(losses) - def ask(self, n, tell_pending=True): + def ask( + self, n: int, tell_pending: bool = True + ) -> tuple[list[_Point], list[float]]: """Chose points for learners.""" if not tell_pending: with restore(self): @@ -735,7 +865,7 @@ def ask(self, n, tell_pending=True): else: return self._ask_and_tell_pending(n) - def _ask_bound_point(self): + def _ask_bound_point(self) -> tuple[_Point, float]: # get the next bound point that is still available new_point = next( p @@ -745,7 +875,7 @@ def _ask_bound_point(self): self.tell_pending(new_point) return new_point, np.inf - def _ask_point_without_known_simplices(self): + def _ask_point_without_known_simplices(self) -> tuple[_Point, float]: assert not self._bounds_available # pick a random point inside the bounds # XXX: change this into picking a point based on volume loss @@ -754,13 +884,12 @@ def _ask_point_without_known_simplices(self): p = None while p is None or not self.inside_bounds(p): r = np.array([self._random.random() for _ in range(self.ndim)]) - p = r * a + b - p = tuple(p) + p = tuple(r * a + b) self.tell_pending(p) return p, np.inf - def _pop_highest_existing_simplex(self): + def _pop_highest_existing_simplex(self) -> _QueueItem: # find the simplex with the highest loss, we do need to check that the # simplex hasn't been deleted yet while len(self._simplex_queue): @@ -768,14 +897,14 @@ def _pop_highest_existing_simplex(self): loss, simplex, subsimplex = self._simplex_queue.pop(0) if ( subsimplex is None - and simplex in self.tri.simplices + and simplex in self._require_tri().simplices and simplex not in self._subtriangulations ): return abs(loss), simplex, subsimplex if ( subsimplex is not None and simplex in self._subtriangulations - and simplex in self.tri.simplices + and simplex in self._require_tri().simplices and subsimplex in self._subtriangulations[simplex].simplices ): return abs(loss), simplex, subsimplex @@ -787,15 +916,16 @@ def _pop_highest_existing_simplex(self): " be a simplex available if LearnerND.tri() is not None." ) - def _ask_best_point(self): - assert self.tri is not None + def _ask_best_point(self) -> tuple[_Point, float]: + tri = self.tri + assert tri is not None while True: loss, simplex, subsimplex = self._pop_highest_existing_simplex() if subsimplex is None: # We found a real simplex and want to subdivide it - points = self.tri.get_vertices(simplex) + points = tri.get_vertices(simplex) else: # We found a pending simplex and want to subdivide it subtri = self._subtriangulations[simplex] @@ -815,13 +945,13 @@ def _ask_best_point(self): return point_new, loss @property - def _bounds_available(self): + def _bounds_available(self) -> bool: return any( (p not in self.pending_points and p not in self.data) for p in self._bounds_points ) - def _ask(self): + def _ask(self) -> tuple[_Point, float]: if self._bounds_available: return self._ask_bound_point() # O(1) @@ -833,49 +963,61 @@ def _ask(self): return self._ask_best_point() # O(log N) - def _compute_loss(self, simplex): + def _compute_loss(self, simplex: _Simplex) -> float: # get the loss - vertices = self.tri.get_vertices(simplex) + tri = self._require_tri() + vertices = tri.get_vertices(simplex) values = [self.data[tuple(v)] for v in vertices] # scale them to a cube with sides 1 - vertices = vertices @ self._transform - values = self._output_multiplier * np.array(values) + scaled_vertices = vertices @ self._transform + scaled_values = self._output_multiplier * np.array(values) if self.nth_neighbors == 0: # compute the loss on the scaled simplex - loss = self.loss_per_simplex(vertices, values, self._output_multiplier) + loss_function = cast("_Loss", self.loss_per_simplex) + loss = loss_function( + scaled_vertices, scaled_values, self._output_multiplier + ) if isinstance(loss, np.ndarray): return float(loss.item()) return float(loss) # We do need the neighbors - neighbors = self.tri.get_opposing_vertices(simplex) - - neighbor_points = self.tri.get_vertices(neighbors) - neighbor_values = [self.data.get(x, None) for x in neighbor_points] + neighbors = tri.get_opposing_vertices(simplex) - for i, point in enumerate(neighbor_points): - if point is not None: - neighbor_points[i] = point @ self._transform + neighbor_vertices = tri.get_vertices(neighbors) + neighbor_values = [ + self.data.get(x) if x is not None else None for x in neighbor_vertices + ] + neighbor_points = [ + point @ self._transform if point is not None else None + for point in neighbor_vertices + ] for i, value in enumerate(neighbor_values): if value is not None: - neighbor_values[i] = self._output_multiplier * value + # NumPy's scalar multiplication also handles sequence outputs. + neighbor_values[i] = self._output_multiplier * cast( + "float | _Array", value + ) + neighbor_loss_function = cast("_NeighborLoss", self.loss_per_simplex) return float( - self.loss_per_simplex( - vertices, - values, + neighbor_loss_function( + scaled_vertices, + scaled_values, self._output_multiplier, neighbor_points, neighbor_values, ) ) - def _update_losses(self, to_delete: set, to_add: set): + def _update_losses( + self, to_delete: _SimplexSet, to_add: _SimplexSet | _SimplicesProxy + ) -> None: # XXX: add the points outside the triangulation to this as well - pending_points_unbound = set() + pending_points_unbound: set[_Point] = set() for simplex in to_delete: loss = self._losses.pop(simplex, None) @@ -903,9 +1045,9 @@ def _update_losses(self, to_delete: set, to_add: set): if self.nth_neighbors: points_of_added_simplices = set.union(*[set(s) for s in to_add]) + tri = self._require_tri() neighbors = ( - self.tri.get_simplices_attached_to_points(points_of_added_simplices) - - to_add + tri.get_simplices_attached_to_points(points_of_added_simplices) - to_add ) for simplex in neighbors: loss = self._compute_loss(simplex) @@ -919,7 +1061,7 @@ def _update_losses(self, to_delete: set, to_add: set): simplex, self._subtriangulations[simplex].simplices ) - def _recompute_all_losses(self): + def _recompute_all_losses(self) -> None: """Recompute all losses and pending losses.""" # amortized O(N) complexity if self.tri is None: @@ -943,11 +1085,12 @@ def _recompute_all_losses(self): ) @property - def _scale(self): + def _scale(self) -> float: # get the output scale + assert self._max_value is not None and self._min_value is not None return self._max_value - self._min_value - def _update_range(self, new_output): + def _update_range(self, new_output: _Value) -> bool: if self._min_value is None or self._max_value is None: # this is the first point, nothing to do, just set the range self._min_value = np.min(new_output) @@ -974,6 +1117,7 @@ def _update_range(self, new_output): self._output_multiplier = scale_multiplier + assert self._old_scale is not None if self._old_scale == 0: scale_factor = math.inf if self._scale > 0 else 1 else: @@ -985,7 +1129,7 @@ def _update_range(self, new_output): return False @cache_latest - def loss(self, real=True): + def loss(self, real: bool = True) -> float: # As in Learner1D, real loss checks bounds_are_done so a parallel # runner's loss goal cannot stop it while bound points are pending. # Expected loss checks _bounds_available so pending bounds don't force @@ -998,7 +1142,7 @@ def loss(self, real=True): losses = self._losses if self.tri is not None else {} return max(losses.values()) if losses else float("inf") - def remove_unfinished(self): + def remove_unfinished(self) -> None: # XXX: implement this method self.pending_points = set() self._subtriangulations = {} @@ -1008,7 +1152,7 @@ def remove_unfinished(self): # Plotting related stuff # ########################## - def plot(self, n=None, tri_alpha=0): + def plot(self, n: int | None = None, tri_alpha: float = 0) -> Overlay: """Plot the function we want to learn, only works in 2D. Parameters @@ -1036,7 +1180,8 @@ def plot(self, n=None, tri_alpha=0): # Calculate how many grid points are needed. # factor from A=√3/4 * a² (equilateral triangle) scale_factor = np.prod(np.diag(self._transform)) - a_sq = np.sqrt(np.min(self.tri.volumes()) * scale_factor) + tri = self._require_tri() + a_sq = np.sqrt(np.min(tri.volumes()) * scale_factor) n = max(10, int(0.658 / a_sq)) xs = ys = np.linspace(0, 1, n) @@ -1047,9 +1192,8 @@ def plot(self, n=None, tri_alpha=0): 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] - ) + tri = self._require_tri() + points = np.array([tri.get_vertices(s) for s in tri.simplices]) points = np.pad( points[:, [0, 1, 2, 0], :], pad_width=((0, 0), (0, 1), (0, 0)), @@ -1066,7 +1210,9 @@ def plot(self, n=None, tri_alpha=0): line_width=0.5, alpha=tri_alpha, tools=[] ) - def plot_slice(self, cut_mapping, n=None): + def plot_slice( + self, cut_mapping: Mapping[int, float], n: int | None = None + ) -> Image | Overlay | Path: """Plot a 1D or 2D interpolated slice of a N-dimensional function. Parameters @@ -1093,8 +1239,8 @@ def plot_slice(self, cut_mapping, n=None): 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) + x = cast("_Array", values[ind]) + y = cast(_SliceInterpolator, self._ip())(*values) p = hv.Path((x, y)) # Plot with 5% margins such that the boundary points are visible @@ -1111,7 +1257,8 @@ def plot_slice(self, cut_mapping, n=None): # Calculate how many grid points are needed. # factor from A=√3/4 * a² (equilateral triangle) scale_factor = np.prod(np.diag(self._transform)) - a_sq = np.sqrt(np.min(self.tri.volumes()) * scale_factor) + tri = self._require_tri() + a_sq = np.sqrt(np.min(tri.volumes()) * scale_factor) n = max(10, int(0.658 / a_sq)) xs = ys = np.linspace(0, 1, n) @@ -1129,7 +1276,7 @@ def plot_slice(self, cut_mapping, n=None): lbrt = np.reshape(lbrt, (2, 2)).T.flatten().tolist() if len(self.data) >= 4: - z = self._ip()(*values).squeeze() + z = cast(_SliceInterpolator, self._ip())(*values).squeeze() im = hv.Image(np.rot90(z), bounds=lbrt) else: im = hv.Image([], bounds=lbrt) @@ -1138,7 +1285,9 @@ def plot_slice(self, cut_mapping, n=None): else: raise ValueError("Only 1 or 2-dimensional plots can be generated.") - def plot_3D(self, with_triangulation=False, return_fig=False): + def plot_3D( + self, with_triangulation: bool = False, return_fig: bool = False + ) -> Figure | None: """Plot the learner's data in 3D using plotly. Does *not* work with the @@ -1161,10 +1310,13 @@ def plot_3D(self, with_triangulation=False, return_fig=False): plots = [] - vertices = self.tri.vertices + tri = self._require_tri() + vertices = tri.vertices if with_triangulation: - Xe, Ye, Ze = [], [], [] - for simplex in self.tri.simplices: + Xe: list[float | None] = [] + Ye: list[float | None] = [] + Ze: list[float | None] = [] + for simplex in 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] @@ -1182,7 +1334,7 @@ def plot_3D(self, with_triangulation=False, return_fig=False): ) Xn, Yn, Zn = zip(*vertices) - colors = [self.data[p] for p in self.tri.vertices] + colors = [self.data[p] for p in vertices] marker = { "symbol": "circle", "size": 3, @@ -1223,7 +1375,9 @@ def plot_3D(self, with_triangulation=False, return_fig=False): return fig if return_fig else plotly.offline.iplot(fig) - def _get_iso(self, level=0.0, which="surface"): + def _get_iso( + self, level: float = 0.0, which: Literal["line", "surface"] = "surface" + ) -> tuple[list[_Array], list[list[int]]]: if which == "surface": if self.ndim != 3 or self.vdim != 1: raise Exception( @@ -1239,15 +1393,17 @@ def _get_iso(self, level=0.0, which="surface"): get_surface = False get_line = True - vertices = [] # index -> (x,y,z) - faces_or_lines = [] # tuple of indices of the corner points + vertices: list[_Array] = [] # index -> (x,y,z) + faces_or_lines: list[list[int]] = [] # indices of the corner points + tri = self._require_tri() + data = cast("Mapping[_Point, float]", self.data) # scalar output checked above @functools.lru_cache - def _get_vertex_index(a, b): - vertex_a = self.tri.vertices[a] - vertex_b = self.tri.vertices[b] - value_a = self.data[vertex_a] - value_b = self.data[vertex_b] + def _get_vertex_index(a: int, b: int) -> int: + vertex_a = tri.vertices[a] + vertex_b = tri.vertices[b] + value_a = data[vertex_a] + value_b = data[vertex_b] da = abs(value_a - level) db = abs(value_b - level) @@ -1259,11 +1415,11 @@ def _get_vertex_index(a, b): vertices.append(new_pt) return new_index - for simplex in self.tri.simplices: - plane_or_line = [] + for simplex in tri.simplices: + plane_or_line: list[int] = [] for a, b in itertools.combinations(simplex, 2): - va = self.data[self.tri.vertices[a]] - vb = self.data[self.tri.vertices[b]] + va = data[tri.vertices[a]] + vb = data[tri.vertices[b]] if min(va, vb) < level <= max(va, vb): vi = _get_vertex_index(a, b) should_add = True @@ -1282,8 +1438,8 @@ def _get_vertex_index(a, b): faces_or_lines.append(plane_or_line) if len(faces_or_lines) == 0: - r_min = min(self.data[v] for v in self.tri.vertices) - r_max = max(self.data[v] for v in self.tri.vertices) + r_min = min(data[v] for v in tri.vertices) + r_max = max(data[v] for v in tri.vertices) raise ValueError( f"Could not draw isosurface for level={level}, as" @@ -1293,7 +1449,12 @@ def _get_vertex_index(a, b): return vertices, faces_or_lines - def plot_isoline(self, level=0.0, n=None, tri_alpha=0): + def plot_isoline( + self, + level: float | Iterable[float] = 0.0, + n: int | None = None, + tri_alpha: float = 0, + ) -> Overlay | Path: """Plot the isoline at a specific level, only works in 2D. Parameters @@ -1330,7 +1491,7 @@ def plot_isoline(self, level=0.0, n=None, tri_alpha=0): contour = hv.Path(paths).opts(color="black") return plot * contour - def plot_isosurface(self, level=0.0, hull_opacity=0.2): + def plot_isosurface(self, level: float = 0.0, hull_opacity: float = 0.2) -> None: """Plots a linearly interpolated isosurface. This is the 3D analog of an isoline. Does *not* work with the @@ -1374,21 +1535,20 @@ def plot_isosurface(self, level=0.0, hull_opacity=0.2): hull_mesh = self._get_hull_mesh(opacity=hull_opacity) return plotly.offline.iplot([isosurface, hull_mesh]) - def _get_hull_mesh(self, opacity=0.2): + def _get_hull_mesh(self, opacity: float = 0.2) -> Mesh3d: plotly = ensure_plotly() hull = scipy.spatial.ConvexHull(self._bounds_points) # Find the colors of each plane, giving triangles which are coplanar # the same color, such that a square face has the same color. - color_dict = {} + color_dict: dict[_Simplex, tuple[int, ...]] = {} - def _get_plane_color(simplex): + def _get_plane_color(simplex: Iterable[int]) -> tuple[int, ...]: simplex = tuple(simplex) # If the volume of the two triangles combined is zero then they # belong to the same plane. for simplex_key, color in color_dict.items(): - points = [hull.points[i] for i in set(simplex_key + simplex)] - points = np.array(points) + points = np.array([hull.points[i] for i in set(simplex_key + simplex)]) if np.linalg.matrix_rank(points[1:] - points[0]) < 3: return color if scipy.spatial.ConvexHull(points).volume < 1e-5: @@ -1419,9 +1579,9 @@ def _get_plane_color(simplex): lighting=lighting, ) - def _get_data(self): + def _get_data(self) -> dict[str, Any]: return deepcopy(self.__dict__) - def _set_data(self, state): + def _set_data(self, state: Mapping[str, Any]) -> None: for k, v in state.items(): setattr(self, k, v) diff --git a/adaptive/learner/sequence_learner.py b/adaptive/learner/sequence_learner.py index 2209ff875..cae7833eb 100644 --- a/adaptive/learner/sequence_learner.py +++ b/adaptive/learner/sequence_learner.py @@ -1,13 +1,14 @@ from __future__ import annotations +from collections.abc import Callable, Sequence from copy import copy -from typing import TYPE_CHECKING, Any, TypeAlias +from typing import TYPE_CHECKING, Any, TypeAlias, cast import cloudpickle +import numpy as np from sortedcontainers import SortedDict, SortedSet from adaptive.learner.base_learner import BaseLearner -from adaptive.types import Int from adaptive.utils import ( assign_defaults, cache_latest, @@ -15,7 +16,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable, Sequence + from collections.abc import MutableSet try: import pandas @@ -26,7 +27,15 @@ with_pandas = False -PointType: TypeAlias = tuple[Int, Any] +# DataFrames can supply NumPy integer indices even though Sequence specifies int. +_Index: TypeAlias = int | np.integer[Any] +PointType: TypeAlias = tuple[_Index, Any] + +if TYPE_CHECKING: + + class _IndexedSequence(Sequence[Any]): + # Built-in sequences accept NumPy integers through __index__. + def __getitem__(self, index: _Index | slice, /) -> Any: ... class _IgnoreFirstArgument: @@ -39,18 +48,18 @@ class _IgnoreFirstArgument: pickable. """ - def __init__(self, function): + def __init__(self, function: Callable[..., Any]) -> None: self.function = function - def __call__(self, index_point: PointType, *args, **kwargs): + def __call__(self, index_point: PointType, *args: Any, **kwargs: Any) -> Any: index, point = index_point return self.function(point, *args, **kwargs) - def __getstate__(self): + def __getstate__(self) -> Callable[..., Any]: return self.function - def __setstate__(self, function): - self.__init__(function) + def __setstate__(self, function: Callable[..., Any]) -> None: + type(self).__init__(self, function) class SequenceLearner(BaseLearner): @@ -80,19 +89,22 @@ class SequenceLearner(BaseLearner): the added benefit of having results in the local kernel already. """ + data: dict[_Index, Any] + pending_points: set[_Index] + def __init__( self, function: Callable[[Any], Any], sequence: Sequence[Any], - ): + ) -> None: self._original_function = function - self.function = _IgnoreFirstArgument(function) + self.function: Callable[..., Any] = _IgnoreFirstArgument(function) # prefer range(len(...)) over enumerate to avoid slowdowns # when passing lazy sequences indices = range(len(sequence)) - self._to_do_indices = SortedSet(indices) + self._to_do_indices: MutableSet[_Index] = SortedSet(indices) self._ntotal = len(sequence) - self.sequence = copy(sequence) + self.sequence = cast("_IndexedSequence", copy(sequence)) self.data = SortedDict() self.pending_points = set() @@ -154,10 +166,10 @@ def result(self) -> list[Any]: return list(self.data.values()) @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] return len(self.data) - def to_dataframe( # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -200,12 +212,14 @@ def to_dataframe( # type: ignore[override] raise ImportError("pandas is not installed.") import pandas as pd + indices: Sequence[_Index] + ys: Sequence[Any] if full_sequence: indices = list(range(len(self.sequence))) sequence = list(self.sequence) ys = [self.data.get(i, pd.NA) for i in indices] else: - indices, ys = zip(*self.data.items()) if self.data else ([], []) # type: ignore[assignment] + indices, ys = zip(*self.data.items()) if self.data else ([], []) sequence = [self.sequence[i] for i in indices] df = pandas.DataFrame(indices, columns=[index_name]) @@ -217,7 +231,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self._original_function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -227,7 +241,7 @@ def load_dataframe( # type: ignore[override] y_name: str = "y", *, full_sequence: bool = False, - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -273,25 +287,26 @@ def load_dataframe( # type: ignore[override] self._original_function, df, function_prefix ) - def _get_data(self) -> dict[int, Any]: + def _get_data(self) -> dict[_Index, Any]: return self.data - def _set_data(self, data: dict[int, Any]) -> None: + def _set_data(self, data: dict[_Index, Any]) -> None: if data: indices, values = zip(*data.items()) # the points aren't used by tell, so we can safely pass None points = [(i, None) for i in indices] self.tell_many(points, values) - def __getstate__(self): + def __getstate__(self) -> tuple[bytes, Sequence[Any], dict[_Index, Any]]: return ( cloudpickle.dumps(self._original_function), self.sequence, self._get_data(), ) - def __setstate__(self, state): - function, sequence, data = state - function = cloudpickle.loads(function) - self.__init__(function, sequence) + def __setstate__( + self, state: tuple[bytes, Sequence[Any], dict[_Index, Any]] + ) -> None: + pickled_function, sequence, data = state + type(self).__init__(self, cloudpickle.loads(pickled_function), sequence) self._set_data(data) diff --git a/adaptive/learner/triangulation.py b/adaptive/learner/triangulation.py index 8cf377248..559df2358 100644 --- a/adaptive/learner/triangulation.py +++ b/adaptive/learner/triangulation.py @@ -1,9 +1,13 @@ +from __future__ import annotations + from collections import Counter -from collections.abc import Iterable, Sized +from collections.abc import Iterable, Iterator, Sequence, Sized from itertools import chain, combinations from math import factorial, sqrt +from typing import Any, TypeAlias, overload import numpy as np +import numpy.typing as npt import scipy.spatial from numpy import abs as np_abs from numpy import ( @@ -23,8 +27,16 @@ from numpy.linalg import det as ndet from numpy.linalg import matrix_rank, norm, slogdet, solve +_Point: TypeAlias = tuple[float, ...] +_PointLike: TypeAlias = Sequence[float] | npt.NDArray[Any] +_PointsLike: TypeAlias = Sequence[_PointLike] | npt.NDArray[Any] +_Simplex: TypeAlias = tuple[int, ...] +_SimplexSet: TypeAlias = set[_Simplex] +_SimplexLike: TypeAlias = Sequence[int] | npt.NDArray[np.integer[Any]] +_Circle: TypeAlias = tuple[_Point, float] + -def fast_norm(v): +def fast_norm(v: _PointLike) -> float: """Take the vector norm for len 2, 3 vectors. Defaults to a square root of the dot product for larger vectors. @@ -42,7 +54,9 @@ def fast_norm(v): return sqrt(dot(v, v)) -def fast_2d_point_in_simplex(point, simplex, eps=1e-8): +def fast_2d_point_in_simplex( + point: _PointLike, simplex: _PointsLike, eps: float = 1e-8 +) -> bool | np.bool_: (p0x, p0y), (p1x, p1y), (p2x, p2y) = simplex px, py = point @@ -56,7 +70,9 @@ def fast_2d_point_in_simplex(point, simplex, eps=1e-8): return (t >= -eps) and (s + t <= 1 + eps) -def point_in_simplex(point, simplex, eps=1e-8): +def point_in_simplex( + point: _PointLike, simplex: _PointsLike, eps: float = 1e-8 +) -> bool | np.bool_: if len(point) == 2: return fast_2d_point_in_simplex(point, simplex, eps) @@ -67,7 +83,7 @@ def point_in_simplex(point, simplex, eps=1e-8): return all(alpha > -eps) and sum(alpha) < 1 + eps -def fast_2d_circumcircle(points): +def fast_2d_circumcircle(points: _PointsLike) -> _Circle: """Compute the center and radius of the circumscribed circle of a triangle Parameters @@ -103,7 +119,7 @@ def fast_2d_circumcircle(points): return (x + points[0][0], y + points[0][1]), radius -def fast_3d_circumcircle(points): +def fast_3d_circumcircle(points: _PointsLike) -> _Circle: """Compute the center and radius of the circumscribed sphere of a simplex. Parameters @@ -143,7 +159,7 @@ def fast_3d_circumcircle(points): return center, radius -def fast_det(matrix): +def fast_det(matrix: _PointsLike) -> float: matrix = asarray(matrix, dtype=float) if matrix.shape == (2, 2): return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1] @@ -154,7 +170,7 @@ def fast_det(matrix): return ndet(matrix) -def circumsphere(pts): +def circumsphere(pts: _PointsLike) -> _Circle: """Compute the center and radius of a N dimension sphere which touches each point in pts. Parameters @@ -202,7 +218,7 @@ def circumsphere(pts): return tuple(center), radius -def orientation(face, origin): +def orientation(face: _PointsLike, origin: _PointLike) -> float: """Compute the orientation of the face with respect to a point, origin. Parameters @@ -228,11 +244,11 @@ def orientation(face, origin): return sign -def is_iterable_and_sized(obj): +def is_iterable_and_sized(obj: object) -> bool: return isinstance(obj, Iterable) and isinstance(obj, Sized) -def simplex_volume_in_embedding(vertices) -> float: +def simplex_volume_in_embedding(vertices: _PointsLike) -> float: """Calculate the volume of a simplex in a higher dimensional embedding. That is: dim > len(vertices) - 1. For example if you would like to know the surface area of a triangle in a 3d space. @@ -315,7 +331,7 @@ class Triangulation: or more simplices in the """ - def __init__(self, coords): + def __init__(self, coords: _PointsLike) -> None: if not is_iterable_and_sized(coords): raise TypeError("Please provide a 2-dimensional list of points") coords = list(coords) @@ -335,45 +351,61 @@ def __init__(self, coords): if len(coords) < dim + 1: raise ValueError("Please provide at least one simplex") - coords = list(map(tuple, coords)) - vectors = subtract(coords[1:], coords[0]) + points = list(map(tuple, coords)) + vectors = subtract(points[1:], points[0]) if matrix_rank(vectors) < dim: raise ValueError( "Initial simplex has zero volumes (the points are linearly dependent)" ) - self.vertices = list(coords) - self.simplices = set() + self.vertices: list[_Point] = list(points) + self.simplices: _SimplexSet = set() # initialise empty set for each vertex - self.vertex_to_simplices = [set() for _ in coords] + self.vertex_to_simplices: list[_SimplexSet] = [set() for _ in points] # find a Delaunay triangulation to start with, then we will throw it # away and continue with our own algorithm - initial_tri = scipy.spatial.Delaunay(coords) + initial_tri = scipy.spatial.Delaunay(points) for simplex in initial_tri.simplices: self.add_simplex(simplex) - def delete_simplex(self, simplex): + def delete_simplex(self, simplex: Iterable[int]) -> None: simplex = tuple(sorted(simplex)) self.simplices.remove(simplex) for vertex in simplex: self.vertex_to_simplices[vertex].remove(simplex) - def add_simplex(self, simplex): + def add_simplex(self, simplex: Iterable[int]) -> None: simplex = tuple(sorted(simplex)) self.simplices.add(simplex) for vertex in simplex: self.vertex_to_simplices[vertex].add(simplex) - def get_vertices(self, indices): + @overload + def get_vertices(self, indices: Iterable[int]) -> list[_Point]: ... + + @overload + def get_vertices(self, indices: Iterable[int | None]) -> list[_Point | None]: ... + + def get_vertices( + self, indices: Iterable[int | None] + ) -> list[_Point] | list[_Point | None]: return [self.get_vertex(i) for i in indices] - def get_vertex(self, index): + @overload + def get_vertex(self, index: int) -> _Point: ... + + @overload + def get_vertex(self, index: None) -> None: ... + + def get_vertex(self, index: int | None) -> _Point | None: if index is None: return None return self.vertices[index] - def get_reduced_simplex(self, point, simplex, eps=1e-8) -> list: + def get_reduced_simplex( + self, point: _PointLike, simplex: _SimplexLike, eps: float = 1e-8 + ) -> list[int]: """Check whether vertex lies within a simplex. Returns @@ -398,11 +430,13 @@ def get_reduced_simplex(self, point, simplex, eps=1e-8) -> list: return [simplex[i] for i in result] - def point_in_simplex(self, point, simplex, eps=1e-8): + def point_in_simplex( + self, point: _PointLike, simplex: Iterable[int], eps: float = 1e-8 + ) -> bool | np.bool_: vertices = self.get_vertices(simplex) return point_in_simplex(point, vertices, eps) - def locate_point(self, point): + def locate_point(self, point: _PointLike) -> _Simplex: """Find to which simplex the point belongs. Return indices of the simplex containing the point. @@ -414,10 +448,15 @@ def locate_point(self, point): return () @property - def dim(self): + def dim(self) -> int: return len(self.vertices[0]) - def faces(self, dim=None, simplices=None, vertices=None): + def faces( + self, + dim: int | None = None, + simplices: Iterable[Iterable[int]] | None = None, + vertices: Iterable[int] | None = None, + ) -> Iterator[_Simplex]: """Iterator over faces of a simplex or vertex sequence.""" if dim is None: dim = self.dim @@ -438,11 +477,11 @@ def faces(self, dim=None, simplices=None, vertices=None): else: return faces - def containing(self, face): + def containing(self, face: Iterable[int]) -> _SimplexSet: """Simplices containing a face.""" return set.intersection(*(self.vertex_to_simplices[i] for i in face)) - def _extend_hull(self, new_vertex, eps=1e-8): + def _extend_hull(self, new_vertex: _Point, eps: float = 1e-8) -> _SimplexSet: # count multiplicities in order to get all hull faces multiplicities = Counter(face for face in self.faces()) hull_faces = [face for face, count in multiplicities.items() if count == 1] @@ -482,7 +521,9 @@ def _extend_hull(self, new_vertex, eps=1e-8): return new_simplices - def circumscribed_circle(self, simplex, transform): + def circumscribed_circle( + self, simplex: Iterable[int], transform: _PointsLike + ) -> _Circle: """Compute the center and radius of the circumscribed circle of a simplex. Parameters @@ -498,7 +539,9 @@ def circumscribed_circle(self, simplex, transform): pts = dot(self.get_vertices(simplex), transform) return circumsphere(pts) - def point_in_cicumcircle(self, pt_index, simplex, transform): + def point_in_cicumcircle( + self, pt_index: int, simplex: Iterable[int], transform: _PointsLike + ) -> bool | np.bool_: # return self.fast_point_in_circumcircle(pt_index, simplex, transform) eps = 1e-8 @@ -508,10 +551,15 @@ def point_in_cicumcircle(self, pt_index, simplex, transform): return norm(center - pt) < (radius * (1 + eps)) @property - def default_transform(self): + def default_transform(self) -> npt.NDArray[np.float64]: return eye(self.dim) - def bowyer_watson(self, pt_index, containing_simplex=None, transform=None): + def bowyer_watson( + self, + pt_index: int, + containing_simplex: _Simplex | None = None, + transform: _PointsLike | None = None, + ) -> tuple[_SimplexSet, _SimplexSet]: """Modified Bowyer-Watson point adding algorithm. Create a hole in the triangulation around the new point, @@ -529,8 +577,8 @@ def bowyer_watson(self, pt_index, containing_simplex=None, transform=None): new_simplices : set of tuples Simplices that have been added """ - queue = set() - done_simplices = set() + queue: _SimplexSet = set() + done_simplices: _SimplexSet = set() transform = self.default_transform if transform is None else transform @@ -578,10 +626,10 @@ def bowyer_watson(self, pt_index, containing_simplex=None, transform=None): return deleted_simplices, new_simplices - def _simplex_is_almost_flat(self, simplex): + def _simplex_is_almost_flat(self, simplex: Iterable[int]) -> bool | np.bool_: return self._relative_volume(simplex) < 1e-8 - def _relative_volume(self, simplex): + def _relative_volume(self, simplex: Iterable[int]) -> float: """Compute the volume of a simplex divided by the average (Manhattan) distance of its vertices. The advantage of this is that the relative volume is only dependent on the shape of the simplex and not on the @@ -592,7 +640,12 @@ def _relative_volume(self, simplex): average_edge_length = mean(np_abs(vectors)) return self.volume(simplex) / (average_edge_length**self.dim) - def add_point(self, point, simplex=None, transform=None): + def add_point( + self, + point: _PointLike, + simplex: _Simplex | None = None, + transform: _PointsLike | None = None, + ) -> tuple[_SimplexSet, _SimplexSet]: """Add a new vertex and create simplices as appropriate. Parameters @@ -630,10 +683,8 @@ def add_point(self, point, simplex=None, transform=None): if not reduced_simplex: self.vertex_to_simplices.pop() # revert adding vertex raise ValueError("Point lies outside of the specified simplex.") - else: - simplex = reduced_simplex - if len(simplex) == 1: + if len(reduced_simplex) == 1: self.vertex_to_simplices.pop() # revert adding vertex raise ValueError("Point already in triangulation.") else: @@ -641,16 +692,16 @@ def add_point(self, point, simplex=None, transform=None): self.vertices.append(point) return self.bowyer_watson(pt_index, actual_simplex, transform) - def volume(self, simplex): + def volume(self, simplex: Iterable[int]) -> float: prefactor = factorial(self.dim) vertices = array(self.get_vertices(simplex)) vectors = vertices[1:] - vertices[0] return float(abs(fast_det(vectors)) / prefactor) - def volumes(self): + def volumes(self) -> list[float]: return [self.volume(sim) for sim in self.simplices] - def reference_invariant(self): + def reference_invariant(self) -> bool: """vertex_to_simplices and simplices are compatible.""" for vertex in range(len(self.vertices)): if any(vertex not in tri for tri in self.vertex_to_simplices[vertex]): @@ -660,30 +711,32 @@ def reference_invariant(self): return False return True - def vertex_invariant(self, vertex): + def vertex_invariant(self, vertex: int) -> bool: """Simplices originating from a vertex don't overlap.""" raise NotImplementedError - def get_neighbors_from_vertices(self, simplex): + def get_neighbors_from_vertices(self, simplex: Iterable[int]) -> _SimplexSet: return set.union(*[self.vertex_to_simplices[p] for p in simplex]) - def get_face_sharing_neighbors(self, neighbors, simplex): + def get_face_sharing_neighbors( + self, neighbors: Iterable[_Simplex], simplex: Iterable[int] + ) -> _SimplexSet: """Keep only the simplices sharing a whole face with simplex.""" return { simpl for simpl in neighbors if len(set(simpl) & set(simplex)) == self.dim } # they share a face - def get_simplices_attached_to_points(self, indices): + def get_simplices_attached_to_points(self, indices: Iterable[int]) -> _SimplexSet: # Get all simplices that share at least a point with the simplex neighbors = self.get_neighbors_from_vertices(indices) return self.get_face_sharing_neighbors(neighbors, indices) - def get_opposing_vertices(self, simplex): + def get_opposing_vertices(self, simplex: _Simplex) -> tuple[int | None, ...]: if simplex not in self.simplices: raise ValueError("Provided simplex is not part of the triangulation") neighbors = self.get_simplices_attached_to_points(simplex) - def find_opposing_vertex(vertex): + def find_opposing_vertex(vertex: int) -> int | None: # find the simplex: simp = next((x for x in neighbors if vertex not in x), None) if simp is None: @@ -696,7 +749,7 @@ def find_opposing_vertex(vertex): return result @property - def hull(self): + def hull(self) -> set[int]: """Compute hull from triangulation. Parameters @@ -720,13 +773,15 @@ def hull(self): hull = {point for face, count in counts.items() if count == 1 for point in face} return hull - def convex_invariant(self, vertex): + def convex_invariant(self, vertex: int) -> bool: """Hull is convex.""" raise NotImplementedError class FakeDelaunay(scipy.spatial.Delaunay): - def __init__(self, vertices, simplices): + def __init__( + self, vertices: _PointsLike, simplices: Sequence[_Simplex] | _SimplexSet + ) -> None: """ Throw in a Triangulation object, and receive a brandnew scipy.spatial.Delaunay @@ -754,7 +809,7 @@ def __init__(self, vertices, simplices): # now the hard part: finding the neighbours self.neighbors = -np.ones_like(self.simplices) # set all to -1 - faces_dict = {} + faces_dict: dict[_Simplex, tuple[int, int]] = {} for n, simplex in enumerate(self.simplices): simplex = tuple(simplex) for i, _point in enumerate(simplex): diff --git a/adaptive/learner/triangulation_backend.py b/adaptive/learner/triangulation_backend.py index 1ceae0f35..344503e58 100644 --- a/adaptive/learner/triangulation_backend.py +++ b/adaptive/learner/triangulation_backend.py @@ -19,12 +19,105 @@ Note that the pure-Python implementation in `adaptive.learner.triangulation` is always importable under its own name, regardless of the selected backend, -so pickles that reference it keep working. +so pickles that reference it keep working. Use ``Triangulation`` to construct +an instance of the selected backend, and ``TriangulationProtocol`` to annotate +instances from either backend. """ from __future__ import annotations import os +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, TypeVar, overload + +import numpy as np +import numpy.typing as npt + +from adaptive.learner.triangulation import ( + _Point, + _PointLike, + _PointsLike, + _Simplex, + _SimplexSet, +) + +_T_co = TypeVar("_T_co", covariant=True) + + +class _Indexable(Protocol[_T_co]): + """A read-only view of a Python list or a Rust vertex proxy.""" + + def __getitem__(self, index: int, /) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __len__(self) -> int: ... + + +class _SimplexCollection(Protocol): + def __contains__(self, simplex: _Simplex, /) -> bool: ... + def __iter__(self) -> Iterator[_Simplex]: ... + def __len__(self) -> int: ... + + +class _SimplicesProxy(_SimplexCollection, Protocol): + def __rsub__(self, other: _SimplexSet, /) -> _SimplexSet: ... + + +class TriangulationProtocol(Protocol): + """The common instance interface, including Rust's read-only views.""" + + def __init__(self, coords: _PointsLike) -> None: ... + + @property + def vertices(self) -> _Indexable[_Point]: ... + @property + def simplices(self) -> _SimplexCollection: ... + @property + def vertex_to_simplices(self) -> _Indexable[_SimplexSet]: ... + @property + def dim(self) -> int: ... + @property + def hull(self) -> set[int]: ... + + def get_vertices(self, indices: Sequence[int]) -> list[_Point]: ... + def locate_point(self, point: _PointLike) -> _Simplex: ... + def point_in_simplex( + self, point: _PointLike, simplex: Sequence[int], eps: float = 1e-8 + ) -> bool | np.bool_: ... + def add_point( + self, + point: _PointLike, + simplex: _Simplex | None = None, + transform: _PointsLike | None = None, + ) -> tuple[_SimplexSet, _SimplexSet]: ... + def volume(self, simplex: Sequence[int]) -> float: ... + def volumes(self) -> list[float]: ... + + +class _LearnerTriangulation(TriangulationProtocol, Protocol): + # These operations work at runtime but are absent from the Rust 0.3.1 stubs. + @property + def simplices(self) -> _SimplexSet | _SimplicesProxy: ... + + @overload + def get_vertices(self, indices: Iterable[int]) -> list[_Point]: ... + @overload + def get_vertices(self, indices: Iterable[int | None]) -> list[_Point | None]: ... + def get_opposing_vertices(self, simplex: _Simplex) -> tuple[int | None, ...]: ... + def get_simplices_attached_to_points( + self, indices: Iterable[int] + ) -> _SimplexSet: ... + + +class _BatchedTriangulation(_LearnerTriangulation, Protocol): + """Optional accelerated query; callers must first check for it.""" + + def simplices_containing( + self, point: _PointLike, /, simplex: _Simplex | None = None + ) -> list[_Simplex]: ... + + +_TriangulationClass: TypeAlias = type[TriangulationProtocol] +_TriangulationType = TypeVar("_TriangulationType") # Minimal version that is a complete drop-in for the learners: includes the # degenerate-simplex fix for curvature losses, plus the batched @@ -43,7 +136,7 @@ def _rust_version() -> tuple[int, ...] | None: return tuple(int(part) for part in version.split(".")[:3] if part.isdigit()) -def _import_rust_triangulation(): +def _import_rust_triangulation() -> _TriangulationClass: """Import the Rust `Triangulation`, raising a helpful `ImportError`.""" version = _rust_version() if version is None: @@ -81,7 +174,19 @@ def _select_backend() -> str: return backend -def resolve_triangulation_class(backend="auto"): +@overload +def resolve_triangulation_class( + backend: type[_TriangulationType], +) -> type[_TriangulationType]: ... + + +@overload +def resolve_triangulation_class(backend: str = "auto") -> _TriangulationClass: ... + + +def resolve_triangulation_class( + backend: str | type[Any] = "auto", +) -> type[Any]: """Return the `Triangulation` class to use for *backend*. Parameters @@ -109,9 +214,11 @@ def resolve_triangulation_class(backend="auto"): TRIANGULATION_BACKEND: str = _select_backend() -if TRIANGULATION_BACKEND == "rust": - from adaptive_triangulation import ( - Triangulation, +rust_default_loss: Callable[[npt.NDArray[Any], npt.NDArray[Any], float], float] | None + +if TYPE_CHECKING or TRIANGULATION_BACKEND != "rust": + # Both backends implement these geometric operations. + from adaptive.learner.triangulation import ( circumsphere, fast_2d_circumcircle, fast_2d_point_in_simplex, @@ -122,14 +229,8 @@ def resolve_triangulation_class(backend="auto"): simplex_volume_in_embedding, ) - # The Rust implementation of `adaptive.learner.learnerND.default_loss`, - # which `LearnerND` prefers when no loss is given. Defined here (rather - # than re-exporting the Python one) to avoid a circular import with - # `learnerND`; ``None`` means "use the pure-Python default". - from adaptive_triangulation import default_loss as rust_default_loss else: - from adaptive.learner.triangulation import ( - Triangulation, + from adaptive_triangulation import ( circumsphere, fast_2d_circumcircle, fast_2d_point_in_simplex, @@ -140,11 +241,28 @@ def resolve_triangulation_class(backend="auto"): simplex_volume_in_embedding, ) +if TYPE_CHECKING: + # The runtime binding is one of two concrete classes, not the protocol. + Triangulation: _TriangulationClass +elif TRIANGULATION_BACKEND == "rust": + from adaptive_triangulation import Triangulation + + # The Rust implementation of `adaptive.learner.learnerND.default_loss`, + # which `LearnerND` prefers when no loss is given. Defined here (rather + # than re-exporting the Python one) to avoid a circular import with + # `learnerND`; ``None`` means "use the pure-Python default". + from adaptive_triangulation import default_loss as _rust_default_loss + + rust_default_loss = _rust_default_loss +else: + from adaptive.learner.triangulation import Triangulation + rust_default_loss = None __all__ = [ "TRIANGULATION_BACKEND", "Triangulation", + "TriangulationProtocol", "resolve_triangulation_class", "circumsphere", "fast_2d_circumcircle", diff --git a/adaptive/notebook_integration.py b/adaptive/notebook_integration.py index 5eb5c6d25..c8f3def10 100644 --- a/adaptive/notebook_integration.py +++ b/adaptive/notebook_integration.py @@ -5,14 +5,45 @@ import importlib import random import warnings +from collections.abc import Callable, Hashable from contextlib import suppress +from types import ModuleType +from typing import TYPE_CHECKING, Any, cast + +import adaptive +from adaptive.learner.base_learner import LearnerType + +if TYPE_CHECKING: + from collections.abc import Iterator, Mapping + from typing import Protocol + + from holoviews.core import Dimensioned, DynamicMap + from ipywidgets import HTML + + # IPython supplies this as a builtin; it is absent outside IPython. + get_ipython: Callable[[], object] + + class _Plottable(Protocol): + def plot(self) -> Dimensioned: ... + + class _HasSamples(Protocol): + @property + def nsamples(self) -> int: ... + + class _HasLossCache(Protocol): + @property + def _cache(self) -> Mapping[str, float]: ... + +else: + DynamicMap = Dimensioned = HTML = Any + _holoviews_enabled = False _ipywidgets_enabled = False _plotly_enabled = False -def notebook_extension(*, _inline_js=True): +def notebook_extension(*, _inline_js: bool = True) -> None: """Enable ipywidgets, holoviews, and asyncio notebook integration.""" if not in_ipynb(): raise RuntimeError( @@ -50,7 +81,7 @@ def notebook_extension(*, _inline_js=True): ) -def ensure_holoviews(): +def ensure_holoviews() -> ModuleType: try: return importlib.import_module("holoviews") except ModuleNotFoundError: @@ -59,7 +90,7 @@ def ensure_holoviews(): ) from None -def ensure_plotly(): +def ensure_plotly() -> ModuleType: global _plotly_enabled try: import plotly @@ -80,17 +111,24 @@ def ensure_plotly(): def in_ipynb() -> bool: try: # If we are running in IPython, then `get_ipython()` is always a global - return get_ipython().__class__.__name__ == "ZMQInteractiveShell" # type: ignore[name-defined] + return get_ipython().__class__.__name__ == "ZMQInteractiveShell" except NameError: return False # Fancy displays in the Jupyter notebook -active_plotting_tasks: dict[str, asyncio.Task] = {} +active_plotting_tasks: dict[Hashable, asyncio.Task[None]] = {} -def live_plot(runner, *, plotter=None, update_interval=2, name=None, normalize=True): +def live_plot( + runner: adaptive.AsyncRunner[LearnerType], + *, + plotter: Callable[[LearnerType], Dimensioned] | None = None, + update_interval: float = 2, + name: Hashable = None, + normalize: bool = True, +) -> DynamicMap: """Live plotting of the learner's data. Parameters @@ -101,7 +139,7 @@ def live_plot(runner, *, plotter=None, update_interval=2, name=None, normalize=T holoviews object. By default ``learner.plot()`` will be called. update_interval : int Number of second between the updates of the plot. - name : hasable + name : hashable Name for the `live_plot` task in `adaptive.active_plotting_tasks`. By default the name is None and if another task with the same name already exists that other `live_plot` is canceled. @@ -125,10 +163,10 @@ def live_plot(runner, *, plotter=None, update_interval=2, name=None, normalize=T if name in active_plotting_tasks: active_plotting_tasks[name].cancel() - def plot_generator(): + def plot_generator() -> Iterator[Dimensioned]: while True: if not plotter: - yield runner.learner.plot() + yield cast("_Plottable", runner.learner).plot() else: yield plotter(runner.learner) @@ -148,7 +186,7 @@ def plot_generator(): # Could have used dm.periodic in the following, but this would either spin # off a thread (and learner is not threadsafe) or block the kernel. - async def updater(): + async def updater() -> None: event = lambda: hv.streams.Stream.trigger( # noqa: E731 dm.streams ) # XXX: used to be dm.event() @@ -163,7 +201,7 @@ async def updater(): active_plotting_tasks.pop(name, None) cancel_button.layout.display = "none" # remove cancel button - def cancel(_): + def cancel(_: object) -> None: with suppress(KeyError): active_plotting_tasks[name].cancel() @@ -174,7 +212,7 @@ def cancel(_): return dm -def should_update(status): +def should_update(status: HTML) -> bool: try: # Get the length of the write buffer size buffer_size = len(status.comm.kernel.iopub_thread._events) @@ -192,7 +230,9 @@ def should_update(status): return True -def live_info(runner, *, update_interval=0.5): +def live_info( + runner: adaptive.AsyncRunner[LearnerType], *, update_interval: float = 0.5 +) -> None: """Display live information about the runner. Returns an interactive ipywidget that can be @@ -213,7 +253,7 @@ def live_info(runner, *, update_interval=0.5): ) cancel.on_click(lambda _: runner.cancel()) - async def update(): + async def update() -> None: while not runner.task.done(): await asyncio.sleep(update_interval) @@ -230,7 +270,7 @@ async def update(): display(ipywidgets.VBox((status, cancel))) -def _table_row(i, key, value): +def _table_row(i: int, key: str, value: object) -> str: """Style the rows of a table. Based on the default Jupyterlab table style.""" style = "text-align: right; padding: 0.5em 0.5em; line-height: 1.0;" if i % 2 == 1: @@ -238,7 +278,7 @@ def _table_row(i, key, value): return f'