From d5716058cc8f24c2097a1bc548e569ff46223a2d Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 20:16:40 -0800 Subject: [PATCH 1/7] Ship py.typed and remove typeguard Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- .github/workflows/typeguard.yml | 20 -------------------- adaptive/_types.py | 24 ------------------------ adaptive/py.typed | 0 adaptive/runner.py | 8 +++++++- noxfile.py | 8 -------- pyproject.toml | 4 +++- 6 files changed, 10 insertions(+), 54 deletions(-) delete mode 100644 .github/workflows/typeguard.yml delete mode 100644 adaptive/_types.py create mode 100644 adaptive/py.typed 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/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/py.typed b/adaptive/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/adaptive/runner.py b/adaptive/runner.py index 99f1f4e45..aee4a6514 100644 --- a/adaptive/runner.py +++ b/adaptive/runner.py @@ -25,9 +25,15 @@ FutureTypes: TypeAlias = concurrent.Future | asyncio.Future if TYPE_CHECKING: + import distributed import holoviews + import ipyparallel - from ._types import ExecutorTypes + ExecutorTypes: TypeAlias = ( + concurrent.Executor | distributed.Client | ipyparallel.Client + ) +else: + ExecutorTypes = concurrent.Executor with_ipyparallel = find_spec("ipyparallel") is not None diff --git a/noxfile.py b/noxfile.py index 17c663d7c..b2e121fc6 100644 --- a/noxfile.py +++ b/noxfile.py @@ -35,14 +35,6 @@ def pytest_rust_backend(session: nox.Session) -> None: session.run("pytest", *xdist, env={"ADAPTIVE_TRIANGULATION_BACKEND": "rust"}) -@nox.session(python="3.13") -def pytest_typeguard(session: nox.Session) -> None: - """Run pytest with typeguard.""" - session.install(".[test,other]") - session.run("coverage", "erase") - session.run("pytest", "--typeguard-packages=adaptive", *xdist) - - @nox.session(python="3.13") def coverage(session: nox.Session) -> None: """Generate coverage report.""" diff --git a/pyproject.toml b/pyproject.toml index 470ec746a..4c71f831f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,7 +57,6 @@ test = [ "pytest-timeout", "pytest-xdist", "pre_commit", - "typeguard", "coverage", ] dev = ["adaptive[test,nox,notebook,other]"] @@ -92,6 +91,9 @@ docs = [ [tool.setuptools.packages.find] include = ["adaptive.*", "adaptive"] +[tool.setuptools.package-data] +adaptive = ["py.typed"] + [tool.pytest.ini_options] testpaths = ["adaptive"] addopts = "--durations=5 --cov --cov-append --cov-fail-under=70 -vvv --cov-report=" From e65421c76db375d145a77e7e7543142ac84979aa Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 20:26:13 -0800 Subject: [PATCH 2/7] Make learner and runner types useful with one mypy check Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- .github/workflows/typecheck.yml | 17 +++ .pre-commit-config.yaml | 7 +- adaptive/__init__.py | 5 +- adaptive/learner/average_learner.py | 33 +++--- adaptive/learner/average_learner1D.py | 75 ++++++------- adaptive/learner/balancing_learner.py | 67 +++++++----- adaptive/learner/base_learner.py | 48 +++++---- adaptive/learner/data_saver.py | 26 ++--- adaptive/learner/integrator_coeffs.py | 5 +- adaptive/learner/integrator_learner.py | 14 +-- adaptive/learner/learner1D.py | 144 +++++++++++-------------- adaptive/learner/learner2D.py | 88 +++++++-------- adaptive/learner/learnerND.py | 125 ++++++++++++--------- adaptive/learner/sequence_learner.py | 23 ++-- adaptive/learner/triangulation.py | 4 +- adaptive/notebook_integration.py | 6 +- adaptive/runner.py | 87 ++++++++------- adaptive/tests/algorithm_4.py | 18 ++-- adaptive/tests/test_learners.py | 6 +- adaptive/types.py | 2 + adaptive/utils.py | 50 +++++---- pyproject.toml | 9 +- 22 files changed, 457 insertions(+), 402 deletions(-) create mode 100644 .github/workflows/typecheck.yml diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml new file mode 100644 index 000000000..2144f7c8f --- /dev/null +++ b/.github/workflows/typecheck.yml @@ -0,0 +1,17 @@ +name: Type check + +on: + pull_request: + push: + branches: [main] + +jobs: + mypy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - uses: astral-sh/setup-uv@v6 + - run: uv run --no-default-groups --extra test --with mypy==2.4.1 mypy adaptive diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e41c84989..1244d2fa5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -23,7 +23,10 @@ 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/ + additional_dependencies: [numpy] + args: [adaptive] + pass_filenames: false diff --git a/adaptive/__init__.py b/adaptive/__init__.py index 34f75d9ac..945a337ce 100644 --- a/adaptive/__init__.py +++ b/adaptive/__init__.py @@ -1,3 +1,4 @@ +from adaptive import types as types from adaptive._version import __version__ from adaptive.learner import ( AverageLearner, @@ -19,7 +20,7 @@ ) from adaptive.runner import AsyncRunner, BlockingRunner, Runner -from adaptive import learner, runner, utils # isort:skip +from adaptive import learner, notebook_integration, runner, utils # isort:skip __all__ = [ "learner", @@ -46,4 +47,4 @@ ] # to avoid confusion with `notebook_extension` -del notebook_integration # type: ignore[name-defined] # noqa: F821 +del notebook_integration diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index 2ee309924..de8d082f6 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -6,9 +6,8 @@ import cloudpickle import numpy as np -from adaptive.learner.base_learner import BaseLearner +from adaptive.learner.base_learner import BaseLearner, DataFrame from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Float, Int, Real from adaptive.utils import ( assign_defaults, cache_latest, @@ -51,7 +50,7 @@ class AverageLearner(BaseLearner): def __init__( self, - function: Callable[[int], Real], + function: Callable[[int], float], atol: float | None = None, rtol: float | None = None, min_npoints: int = 2, @@ -65,14 +64,14 @@ def __init__( self.data = {} self.pending_points = set() - self.function = function # type: ignore + self.function = 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: float = 0.0 + self.sum_f_sq: float = 0.0 def new(self) -> AverageLearner: """Create a copy of `~adaptive.AverageLearner` without the data.""" @@ -92,7 +91,7 @@ def to_dataframe( # type: ignore[override] function_prefix: str = "function.", seed_name: str = "seed", y_name: str = "y", - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a `pandas.DataFrame`. Parameters @@ -128,7 +127,7 @@ def to_dataframe( # type: ignore[override] def load_dataframe( # type: ignore[override] self, - df: pandas.DataFrame, + df: DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", seed_name: str = "seed", @@ -160,7 +159,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 +176,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: int, value: float) -> None: if n in self.data: # The point has already been added before. return @@ -192,12 +191,12 @@ def tell_pending(self, n: int) -> 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 @property - def std(self) -> Float: + def std(self) -> float: """The corrected sample standard deviation of the values in `data`.""" n = self.npoints @@ -210,7 +209,7 @@ 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=None) -> float: if n is None: n = self.npoints if real else self.n_requested else: @@ -225,7 +224,7 @@ 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) @@ -251,10 +250,10 @@ 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) -> tuple[dict[int, float], int, float, float]: 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: tuple[dict[int, float], int, float, float]) -> None: self.data, self.npoints, self.sum_f, self.sum_f_sq = data def __getstate__(self): @@ -269,5 +268,5 @@ def __getstate__(self): def __setstate__(self, state): function, atol, rtol, min_npoints, data = state function = cloudpickle.loads(function) - self.__init__(function, atol, rtol, min_npoints) + type(self).__init__(self, 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..48e164ea4 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -6,15 +6,16 @@ from collections.abc import Callable, Iterable, Sequence from copy import deepcopy from math import hypot +from typing import Any import numpy as np import scipy.stats from sortedcollections import ItemSortedDict from sortedcontainers import SortedDict +from adaptive.learner.base_learner import DataFrame from adaptive.learner.learner1D import Learner1D, _get_intervals 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,7 +26,7 @@ except ModuleNotFoundError: with_pandas = False -Point = tuple[int, Real] +Point = tuple[int, float] Points = list[Point] __all__: list[str] = ["AverageLearner1D"] @@ -76,17 +77,16 @@ class AverageLearner1D(Learner1D): 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[[tuple[int, float]], Any], + bounds: Sequence[float | np.floating | np.integer] | np.ndarray, + loss_per_interval: Callable[..., float] | 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 +98,7 @@ 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] + super().__init__(function, bounds, loss_per_interval) self.delta = delta self.alpha = alpha @@ -109,28 +109,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 = SortedDict() # Contains the number of samples taken # at each point x in the form {x0: n0, x1: n1, ...} self._number_samples = 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: dict[float, float] = 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: dict[float, float] = decreasing_dict() # {xii: error[xii]/min(_distances[xi], _distances[xii], ...} - self.rescaled_error: ItemSortedDict[Real, float] = decreasing_dict() + self.rescaled_error: ItemSortedDict = 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, @@ -170,7 +170,7 @@ def to_dataframe( # type: ignore[override] seed_name: str = "seed", x_name: str = "x", y_name: str = "y", - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a `pandas.DataFrame`. Parameters @@ -199,11 +199,12 @@ def to_dataframe( # type: ignore[override] """ if not with_pandas: raise ImportError("pandas is not installed.") + data: Sequence[tuple[float | np.ndarray, ...]] 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()) @@ -218,7 +219,7 @@ def to_dataframe( # type: ignore[override] def load_dataframe( # type: ignore[override] self, - df: pandas.DataFrame, + df: DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", seed_name: str = "seed", @@ -285,7 +286,7 @@ 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""" @@ -311,7 +312,7 @@ 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] _, x = seed_x @@ -320,7 +321,7 @@ def tell_pending(self, seed_x: Point) -> None: # type: ignore[override] 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] seed, x = seed_x if y is None: raise TypeError( @@ -336,7 +337,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 @@ -373,7 +374,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 +382,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 +450,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 +458,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=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) @@ -486,13 +487,17 @@ 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 | np.ndarray, 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 + self, + xs: Sequence[Point] | np.ndarray, + ys: Sequence[float] | np.ndarray, # type: ignore[override] ) -> None: # Check that all x are within the bounds # TODO: remove this requirement, all other learners add the data @@ -503,9 +508,7 @@ def tell_many( # type: ignore[override] ) # 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,14 +522,14 @@ 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 ---------- x : float Value from the function domain. - seed_y_mapping : Dict[int, Real] + seed_y_mapping : Dict[int, float] Dictionary of ``seed`` -> ``y`` at ``x``. """ # Check x is within the bounds @@ -574,15 +577,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) -> dict[float, dict[int, float]]: return self._data_samples - def _set_data(self, data: dict[Real, dict[Int, Real]]) -> None: # type: ignore[override] + def _set_data(self, data: dict[float, dict[int, float]]) -> None: if data: for x, samples in data.items(): self.tell_many_at_point(x, samples) - def plot(self): + def plot(self): # type: ignore[override] """Returns a plot of the evaluated data with error bars. This is only implemented for scalar functions, i.e., it requires ``vdim=1``. diff --git a/adaptive/learner/balancing_learner.py b/adaptive/learner/balancing_learner.py index 32f48e3cf..168cf70fa 100644 --- a/adaptive/learner/balancing_learner.py +++ b/adaptive/learner/balancing_learner.py @@ -6,11 +6,11 @@ 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 Any, Generic, Literal, TypeAlias, TypeVar, cast -from adaptive.learner.base_learner import BaseLearner, LearnerType +from adaptive.learner.base_learner import BaseLearner, DataFrame, LearnerType from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Int, Real from adaptive.utils import cache_latest, named_product, restore try: @@ -33,7 +33,10 @@ def dispatch(child_functions: list[Callable], arg: Any) -> Any: ) -class BalancingLearner(BaseLearner): +ProductLearner = TypeVar("ProductLearner", bound=BaseLearner) + + +class BalancingLearner(BaseLearner, Generic[LearnerType]): r"""Choose the optimal points from a set of learners. Parameters @@ -86,7 +89,7 @@ class BalancingLearner(BaseLearner): def __init__( self, - learners: list[BaseLearner], + learners: list[LearnerType], *, cdims: CDIMS_TYPE = None, strategy: STRATEGY_TYPE = "loss_improvements", @@ -96,7 +99,7 @@ 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] = {} @@ -108,7 +111,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], @@ -137,7 +140,7 @@ def npoints(self) -> int: # type: ignore[override] @property def nsamples(self): if hasattr(self.learners[0], "nsamples"): - return sum(lrn.nsamples for lrn in self.learners) + return sum(getattr(lrn, "nsamples") for lrn in self.learners) # noqa: B009 else: raise AttributeError( f"{type(self.learners[0])} as no attribute called `nsamples`." @@ -240,10 +243,10 @@ 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]]: + self, n: int + ) -> tuple[list[tuple[int, Any]], list[float]]: selected: list[ - tuple[tuple[Int, Any], float] + tuple[tuple[int, Any], float] ] = [] # tuples ((learner_index, point), loss_improvement) 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 @@ -270,7 +273,7 @@ def _ask_and_tell_based_on_npoints( def _ask_and_tell_based_on_cycle( self, n: int - ) -> tuple[list[tuple[Int, Any]], list[float]]: + ) -> tuple[list[tuple[int, Any]], list[float]]: points, loss_improvements = [], [] for _ in range(n): # Skip learners that have no point to give now, at most one round. @@ -289,7 +292,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[tuple[int, Any]], list[float]]: """Chose points for learners.""" if n == 0: return [], [] @@ -303,14 +306,14 @@ def ask( else: return self._ask_and_tell(n) - def tell(self, x: tuple[Int, Any], y: Any) -> None: + def tell(self, x: tuple[int, Any], 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: tuple[int, Any]) -> None: index, x_ = x self._ask_cache.pop(index, None) self._loss.pop(index, None) @@ -389,7 +392,7 @@ def plot( # Normalize the format keys, values_list = cdims cdims = [dict(zip(keys, values)) for values in values_list] - cdims = cast(list[dict[str, Real]], cdims) + cdims = cast(list[dict[str, float]], cdims) mapping = { tuple(_cdims.values()): lrn for lrn, _cdims in zip(self.learners, cdims) } @@ -402,7 +405,9 @@ def plot( def plot_function(*args): with suppress(KeyError): learner = mapping[tuple(args)] - return learner.plot() if plotter is None else plotter(learner) + if plotter is None: + return getattr(learner, "plot")() # noqa: B009 + return plotter(learner) dm = hv.DynamicMap(plot_function, kdims=list(d.keys())) dm = dm.redim.values(**d) @@ -426,12 +431,12 @@ def remove_unfinished(self) -> None: @classmethod def from_product( - cls, + cls: type[BalancingLearner[Any]], f, - learner_type: LearnerType, + learner_type: Callable[..., ProductLearner], learner_kwargs: dict[str, Any], combos: dict[str, Sequence[Any]], - ) -> BalancingLearner: + ) -> BalancingLearner[ProductLearner]: """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 +479,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] + self, index_name: str = "learner_index", **kwargs: Any + ) -> DataFrame: """Return the data as a concatenated `pandas.DataFrame` from child learners. Parameters @@ -511,8 +518,8 @@ def to_dataframe(self, index_name: str = "learner_index", **kwargs): # type: ig return df def load_dataframe( # type: ignore[override] - self, df: pandas.DataFrame, index_name: str = "learner_index", **kwargs - ): + self, df: DataFrame, index_name: str = "learner_index", **kwargs: Any + ) -> None: """Load the data from a `pandas.DataFrame` into the child learners. Parameters @@ -529,7 +536,8 @@ def load_dataframe( # type: ignore[override] def save( self, - fname: Callable[[BaseLearner], str] | Sequence[str], + fname: Callable[[LearnerType], str | PathLike[str]] # type: ignore[override] + | Sequence[str | PathLike[str]], compress: bool = True, ) -> None: """Save the data of the child learners into pickle files @@ -571,7 +579,8 @@ def save( def load( self, - fname: Callable[[BaseLearner], str] | Sequence[str], + fname: Callable[[LearnerType], str | PathLike[str]] # type: ignore[override] + | Sequence[str | PathLike[str]], compress: bool = True, ) -> None: """Load the data of the child learners from pickle files @@ -604,13 +613,13 @@ def _set_data(self, data: list[Any]): 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]): 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..10a2bd8d8 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -1,8 +1,9 @@ from __future__ import annotations import abc -from collections.abc import Callable +from collections.abc import Callable, Iterable from contextlib import suppress +from os import PathLike from typing import TYPE_CHECKING, Any, TypeVar import cloudpickle @@ -10,10 +11,15 @@ from adaptive.utils import load, save if TYPE_CHECKING: - import pandas + from pandas import DataFrame +else: + DataFrame = Any -def uses_nth_neighbors(n: int): +LossFunction = TypeVar("LossFunction", bound=Callable[..., Any]) + + +def uses_nth_neighbors(n: int) -> Callable[[LossFunction], LossFunction]: """Decorator to specify how many neighboring intervals the loss function uses. Wraps loss functions to indicate that they expect intervals together @@ -60,16 +66,13 @@ def uses_nth_neighbors(n: int): ... return loss """ - def _wrapped(loss_per_interval): - loss_per_interval.nth_neighbors = n + def _wrapped(loss_per_interval: LossFunction) -> LossFunction: + setattr(loss_per_interval, "nth_neighbors", n) # noqa: B010 return loss_per_interval return _wrapped -DataType = dict[Any, Any] - - class BaseLearner(abc.ABC): """Base class for algorithms for learning a function 'f: X → Y'. @@ -91,12 +94,12 @@ class BaseLearner(abc.ABC): and returns a holoviews plot. """ - data: DataType + data: dict[Any, Any] npoints: int - pending_points: set + pending_points: set[Any] function: Callable[..., Any] - def tell(self, x, y): + def tell(self, x: Any, y: Any) -> None: """Tell the learner about a single value. Parameters @@ -106,7 +109,7 @@ def tell(self, x, y): """ self.tell_many([x], [y]) - def tell_many(self, xs, ys): + def tell_many(self, xs: Iterable[Any], ys: Iterable[Any]) -> None: """Tell the learner about some values. Parameters @@ -118,16 +121,16 @@ def tell_many(self, xs, ys): self.tell(x, y) @abc.abstractmethod - def tell_pending(self, x): + 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 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 +142,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 @@ -161,11 +164,11 @@ 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 +178,7 @@ def copy_from(self, other): """ self._set_data(other._get_data()) - def save(self, fname, compress=True): + def save(self, fname: str | PathLike[str], compress: bool = True) -> None: """Save the data of the learner into a pickle file. Parameters @@ -189,7 +192,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: str | PathLike[str], compress: bool = True) -> None: """Load the data of a learner from a pickle file. Parameters @@ -204,13 +207,14 @@ def load(self, fname, compress=True): data = load(fname, compress) self._set_data(data) + # Column options differ across learners; keep each concrete signature. @abc.abstractmethod def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", **kwargs: Any, - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a `pandas.DataFrame`. Parameters @@ -234,7 +238,7 @@ def to_dataframe( @abc.abstractmethod def load_dataframe( self, - df: pandas.DataFrame, + df: DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", **kwargs: Any, diff --git a/adaptive/learner/data_saver.py b/adaptive/learner/data_saver.py index 44088e2cc..f68a34c35 100644 --- a/adaptive/learner/data_saver.py +++ b/adaptive/learner/data_saver.py @@ -3,13 +3,13 @@ import functools from collections import OrderedDict from collections.abc import Callable -from typing import Any +from typing import Any, Generic -from adaptive.learner.base_learner import BaseLearner, LearnerType +from adaptive.learner.base_learner import BaseLearner, DataFrame, LearnerType from adaptive.utils import copy_docstring_from try: - import pandas + import pandas # noqa: F401 with_pandas = True @@ -21,7 +21,7 @@ def _to_key(x): 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 @@ -47,16 +47,16 @@ def __init__(self, learner: LearnerType, arg_picker: Callable) -> None: 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) @@ -76,13 +76,13 @@ 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.", extra_data_name: str = "extra_data", **kwargs: Any, - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a concatenated `pandas.DataFrame` from child learners. Parameters @@ -114,9 +114,9 @@ def to_dataframe( # type: ignore[override] ] return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, - df: pandas.DataFrame, + df: DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", extra_data_name: str = "extra_data", @@ -162,7 +162,7 @@ def _set_data( self.learner._set_data(learner_data) def __getstate__(self) -> tuple[LearnerType, Callable, OrderedDict]: - return ( # type: ignore[return-value] + return ( self.learner, self.arg_picker, self.extra_data, @@ -170,7 +170,7 @@ def __getstate__(self) -> tuple[LearnerType, Callable, OrderedDict]: def __setstate__(self, state: tuple[LearnerType, Callable, OrderedDict]) -> 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) diff --git a/adaptive/learner/integrator_coeffs.py b/adaptive/learner/integrator_coeffs.py index 862f76eb0..93a15bf66 100644 --- a/adaptive/learner/integrator_coeffs.py +++ b/adaptive/learner/integrator_coeffs.py @@ -97,7 +97,8 @@ def scalar_product(a: list[Fraction], b: list[Fraction]) -> Fraction: lc = len(b) + la + 1 # Compute the even coefficients of the product of a and b. - c = lc * [a[0].__class__()] + zero = type(a[0])() + c = [zero] * lc for i, bi in enumerate(b): if bi == 0: continue @@ -105,7 +106,7 @@ 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] + return 2 * sum((c[i] / (i + 1) for i in range(0, lc, 2)), start=zero) def calc_bdef(ns: tuple[int, int, int, int]) -> list[np.ndarray]: diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index d6ee9ef1d..fc9d4d8c0 100644 --- a/adaptive/learner/integrator_learner.py +++ b/adaptive/learner/integrator_learner.py @@ -14,7 +14,7 @@ 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, DataFrame from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import assign_defaults, cache_latest, restore @@ -311,7 +311,7 @@ def complete_process(self, depth: int) -> tuple[bool, bool] | tuple[bool, np.boo 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 unused_children): break if ival.done_leaves is None: @@ -375,7 +375,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 = function self.bounds = bounds self.tol = tol self.max_ivals = 1000 @@ -433,7 +433,7 @@ def tell(self, point: float, value: float) -> None: assert ival in self.ivals self.priority_split.append(ival) - def tell_pending(self): + def tell_pending(self) -> None: # type: ignore[override] pass def propagate_removed(self, ival: _Interval) -> None: @@ -579,7 +579,7 @@ def to_dataframe( # type: ignore[override] function_prefix: str = "function.", x_name: str = "x", y_name: str = "y", - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a `pandas.DataFrame`. Parameters @@ -615,7 +615,7 @@ def to_dataframe( # type: ignore[override] def load_dataframe( # type: ignore[override] self, - df: pandas.DataFrame, + df: DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", x_name: str = "x", @@ -689,5 +689,5 @@ def __getstate__(self): def __setstate__(self, state): function, bounds, tol, data = state function = cloudpickle.loads(function) - self.__init__(function, bounds, tol) + 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..093d78f1e 100644 --- a/adaptive/learner/learner1D.py +++ b/adaptive/learner/learner1D.py @@ -12,11 +12,10 @@ from sortedcollections.recipes import ItemSortedDict from sortedcontainers.sorteddict import SortedDict -from adaptive.learner.base_learner import BaseLearner, uses_nth_neighbors +from adaptive.learner.base_learner import BaseLearner, DataFrame, 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,20 +31,7 @@ with_pandas = False -# Commonly used types Interval: TypeAlias = tuple[float, float] | tuple[float, float, int] -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, ...] __all__ = [ @@ -60,7 +46,7 @@ @uses_nth_neighbors(0) -def uniform_loss(xs: XsType0, ys: YsType0) -> Float: +def uniform_loss(xs: Sequence[float], ys: Sequence[Any]) -> float: """Loss function that samples the domain uniformly. Works with `~adaptive.Learner1D` only. @@ -80,7 +66,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[Any]) -> float: """Calculate loss on a single interval. Currently returns the rescaled length of the interval. If one of the @@ -97,24 +83,24 @@ def default_loss(xs: XsType0, ys: YsType0) -> Float: @uses_nth_neighbors(0) -def abs_min_log_loss(xs: XsType0, ys: YsType0) -> Float: +def abs_min_log_loss(xs: Sequence[float], ys: Sequence[Any]) -> 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[Any]) -> 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 if isinstance(y[0], collections.abc.Iterable): - pts = [(x, *y) for x, y in zip(x, y)] # type: ignore[misc] + pts = [(x, *y) for x, y in zip(x, y)] vol = simplex_volume_in_embedding else: pts = list(zip(x, y)) @@ -123,8 +109,8 @@ def triangle_loss(xs: XsType1, ys: YsType1) -> Float: def resolution_loss_function( - min_length: Real = 0, max_length: Real = 1 -) -> Callable[[XsType0, YsType0], Float]: + min_length: float = 0, max_length: float = 1 +) -> Callable[..., float]: """Loss function that is similar to the `default_loss` function, but you can set the maximum and minimum size of an interval. @@ -147,7 +133,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[Any]) -> float: loss = uniform_loss(xs, ys) if loss < min_length: # Return zero such that this interval won't be chosen again @@ -162,17 +148,16 @@ 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 +) -> Callable[..., float]: # 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[Any]) -> float: + left, right = xs[1:3] + assert left is not None and right is not None triangle_loss_ = triangle_loss(xs, ys) - default_loss_ = default_loss(xs_middle, ys_middle) - dx = xs_middle[1] - xs_middle[0] # type: ignore[operator] + default_loss_ = default_loss((left, right), ys[1:3]) + dx = right - left return ( area_factor * (triangle_loss_**0.5) + euclid_factor * default_loss_ @@ -182,7 +167,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 +179,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: np.ndarray) -> SortedDict: xs = np.sort(xs) xs_left = np.roll(xs, 1).tolist() xs_right = np.roll(xs, -1).tolist() @@ -205,7 +190,7 @@ def _get_neighbors_from_array(xs: np.ndarray) -> NeighborsType: def _get_intervals( - x: float, neighbors: NeighborsType, nth_neighbors: int + x: float, neighbors: SortedDict, nth_neighbors: int ) -> list[tuple[float, float]]: nn = nth_neighbors i = neighbors.index(x) @@ -261,39 +246,34 @@ class Learner1D(BaseLearner): 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[..., Any], + bounds: Sequence[float | np.floating | np.integer] | np.ndarray, + loss_per_interval: Callable[..., float] | None = None, + ) -> None: + self.function: Callable[..., Any] = function + + self.nth_neighbors = getattr(loss_per_interval, "nth_neighbors", 0) - self.loss_per_interval = loss_per_interval or default_loss + self.loss_per_interval: Callable[..., float] = 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: dict[float, float | np.ndarray] = {} + self.pending_points = set() # A dict {x_n: [x_{n-1}, x_{n+1}]} for quick checking of local # properties. - self.neighbors: NeighborsType = SortedDict() - self.neighbors_combined: NeighborsType = SortedDict() + self.neighbors: SortedDict = SortedDict() + self.neighbors_combined: SortedDict = SortedDict() # Bounding box [[minx, maxx], [miny, maxy]]. - self._bbox = [list(bounds), [np.inf, -np.inf]] + self._bbox: list[list[Any]] = [list(bounds), [np.inf, -np.inf]] # Data scale (maxx - minx), (maxy - miny) - self._scale = [bounds[1] - bounds[0], 0] + self._scale: list[Any] = [bounds[1] - bounds[0], 0] self._oldscale = deepcopy(self._scale) # A LossManager storing the loss function for each interval x_n. @@ -344,7 +324,7 @@ def to_dataframe( # type: ignore[override] function_prefix: str = "function.", x_name: str = "x", y_name: str = "y", - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a `pandas.DataFrame`. Parameters @@ -382,7 +362,7 @@ def to_dataframe( # type: ignore[override] def load_dataframe( # type: ignore[override] self, - df: pandas.DataFrame, + df: DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", x_name: str = "x", @@ -435,12 +415,12 @@ 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: float | np.ndarray | None) -> float | np.ndarray | None: if y is None: return None y_scale = self._scale[1] or 1 @@ -463,7 +443,7 @@ 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) @@ -532,7 +512,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: SortedDict) -> Any: if x in neighbors: return neighbors[x] pos = neighbors.bisect_left(x) @@ -541,14 +521,14 @@ def _find_neighbors(x: float, neighbors: NeighborsType) -> Any: x_right = keys[pos] if pos != len(neighbors) else None return x_left, x_right - def _update_neighbors(self, x: float, neighbors: NeighborsType) -> None: + def _update_neighbors(self, x: float, neighbors: SortedDict) -> 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 - def _update_scale(self, x: float, y: Float | np.ndarray) -> None: + def _update_scale(self, x: float, y: float | np.ndarray) -> 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 @@ -562,6 +542,8 @@ def _update_scale(self, x: float, y: Float | np.ndarray) -> None: self._scale[0] = self._bbox[0][1] - self._bbox[0][0] if y is not None: if self.vdim > 1: + y_min: float | np.ndarray + y_max: float | np.ndarray try: y_min = np.nanmin([self._bbox[1][0], y], axis=0) y_max = np.nanmax([self._bbox[1][1], y], axis=0) @@ -575,7 +557,7 @@ def _update_scale(self, x: float, y: Float | np.ndarray) -> None: 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: + def tell(self, x: float, y: float | Sequence[float] | np.ndarray) -> None: if x in self.data: # The point is already evaluated before return @@ -618,15 +600,10 @@ def tell_pending(self, x: float) -> None: self._update_neighbors(x, self.neighbors_combined) self._update_losses(x, real=False) - def tell_many( + def tell_many( # type: ignore[override] self, - xs: Sequence[Float] | np.ndarray, - ys: ( - Sequence[Float] - | Sequence[Sequence[Float]] - | Sequence[np.ndarray] - | np.ndarray - ), + xs: Sequence[float] | np.ndarray, + ys: Sequence[Any] | np.ndarray, *, force: bool = False, ) -> None: @@ -671,7 +648,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[tuple[float, float]] = [] self.losses_combined = loss_manager(self._scale[0]) for ival in intervals_combined: @@ -685,7 +662,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 +684,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: @@ -839,10 +816,10 @@ 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) -> Any: return self.data - def _set_data(self, data: dict[float, float]) -> None: + def _set_data(self, data: Any) -> None: if data: xs, ys = zip(*data.items()) self.tell_many(xs, ys) @@ -860,19 +837,18 @@ def __getstate__(self): 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) + 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 loss_manager(x_scale: float) -> ItemSortedDict: def sort_key(ival, loss): loss, ival = finite_loss(ival, loss, x_scale) return -loss, ival - sorted_dict = ItemSortedDict(sort_key) - return sorted_dict + return ItemSortedDict(sort_key) def finite_loss(ival: Interval, loss: float, x_scale: float) -> tuple[float, Interval]: @@ -883,9 +859,9 @@ def finite_loss(ival: Interval, loss: float, x_scale: float) -> tuple[float, Int if math.isinf(loss) or math.isnan(loss): loss = (ival[1] - ival[0]) / x_scale if len(ival) == 3: - # Used when constructing quals. Last item is - # the number of points inside the qual. - loss /= ival[2] # type: ignore[misc] + # When sorting quals, divide by the number of points. + _, _, n = ival + loss /= n # 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..acf938cd5 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -3,19 +3,19 @@ import itertools import warnings from collections import OrderedDict -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Sequence from copy import copy from math import sqrt +from typing import Any import cloudpickle import numpy as np from scipy import interpolate from scipy.interpolate import CloughTocher2DInterpolator, LinearNDInterpolator -from adaptive.learner.base_learner import BaseLearner +from adaptive.learner.base_learner import BaseLearner, DataFrame 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, @@ -61,8 +61,7 @@ def deviations(ip: LinearNDInterpolator) -> np.ndarray: p_diff_scaled = p_diff * gs[:, :, None] vest = vs[:, :, None] + p_diff_scaled.sum(axis=-1) devs = np.sum(np.max(np.abs(vest - vs[:, None]), axis=2), axis=1) - - return np.swapaxes(devs, 0, 1) + return devs.T def areas(ip: LinearNDInterpolator) -> np.ndarray: @@ -82,8 +81,7 @@ def areas(ip: LinearNDInterpolator) -> np.ndarray: """ p = ip.tri.points[ip.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 + return abs(q[:, 0, 0] * q[:, 1, 1] - q[:, 0, 1] * q[:, 1, 0]) / 2 def uniform_loss(ip: LinearNDInterpolator) -> np.ndarray: @@ -324,7 +322,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. @@ -345,7 +343,7 @@ def triangle_loss(ip): """ tri = ip.tri - def get_neighbors(i, ip): + def get_neighbors(i): 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]) @@ -354,7 +352,7 @@ def get_neighbors(i, ip): simplices = np.concatenate( [tri.points[tri.simplices], ip.values[tri.simplices]], axis=-1 ) - neighbors = [get_neighbors(i, ip) for i in range(len(tri.simplices))] + neighbors = [get_neighbors(i) for i in range(len(tri.simplices))] return [ sum(simplex_volume_in_embedding(np.vstack([simplex, n])) for n in neighbors[i]) @@ -428,9 +426,10 @@ class Learner2D(BaseLearner): def __init__( self, - function: Callable, - bounds: tuple[tuple[Real, Real], tuple[Real, Real]], - loss_per_triangle: Callable | None = None, + function: Callable[[tuple[float, float]], Any], + bounds: Sequence[Sequence[float | np.floating | np.integer]] | np.ndarray, + loss_per_triangle: Callable[[LinearNDInterpolator], list[float] | np.ndarray] + | None = None, ) -> None: self.ndim = len(bounds) self._vdim: int | None = None @@ -449,7 +448,7 @@ def __init__( self._bounds_points = list(itertools.product(*bounds)) self._stack.update(dict.fromkeys(self._bounds_points, np.inf)) - self.function = function # type: ignore + self.function = function self._ip = self._ip_combined = None self.stack_size = 10 @@ -459,11 +458,10 @@ def new(self) -> Learner2D: @property def xy_scale(self) -> np.ndarray: - 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]) + return self._xy_scale + x, y = self._xy_scale + return np.array([x, y / self.aspect_ratio]) def to_numpy(self): """Data as NumPy array of size ``(npoints, 3)`` if ``learner.function`` returns a scalar @@ -480,7 +478,7 @@ def to_dataframe( # type: ignore[override] x_name: str = "x", y_name: str = "y", z_name: str = "z", - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a `pandas.DataFrame`. Parameters @@ -521,13 +519,13 @@ def to_dataframe( # type: ignore[override] def load_dataframe( # type: ignore[override] self, - df: pandas.DataFrame, + df: DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", x_name: str = "x", y_name: str = "y", z_name: str = "z", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -653,9 +651,7 @@ def _data_combined(self) -> tuple[np.ndarray, np.ndarray]: if not self.pending_points: return points, values points_interp, values_interp = self._data_interp() - points_combined = np.vstack([points, points_interp]) - values_combined = np.vstack([values, values_interp]) - return points_combined, values_combined + return np.vstack([points, points_interp]), np.vstack([values, values_interp]) def ip(self) -> LinearNDInterpolator: """Deprecated, use `self.interpolator(scaled=True)`""" @@ -708,13 +704,18 @@ 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: tuple[float, float]) -> 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] + def tell( + self, + point: Iterable[float] | np.ndarray, + value: float | Iterable[float] | np.ndarray, + ) -> None: + x, y = point + point = (x, y) self.data[point] = value if not self.inside_bounds(point): return @@ -723,8 +724,9 @@ def tell(self, point: tuple[float, float], value: float | Iterable[float]) -> No self._ip_combined = None self._stack.pop(point, None) - def tell_pending(self, point: tuple[float, float]) -> None: - point = tuple(point) # type: ignore[assignment] + def tell_pending(self, point: Iterable[float] | np.ndarray) -> None: + x, y = point + point = (x, y) if not self.inside_bounds(point): return self.pending_points.add(point) @@ -744,22 +746,20 @@ def _fill_stack( points_new = [] losses_new = [] - for _j, _ in enumerate(losses): + for _ in 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)) + x, y = self._unscale(choose_point_in_triangle(triangle, max_badness=5)) # 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 point_new = ( - clip(point_new[0], *self.bounds[0]), - clip(point_new[1], *self.bounds[1]), + clip(x, *self.bounds[0]), + clip(y, *self.bounds[1]), ) loss_new = losses[jsimplex] - points_new.append(point_new) losses_new.append(loss_new) @@ -774,7 +774,7 @@ def _fill_stack( def ask( self, n: int, tell_pending: bool = True - ) -> tuple[list[tuple[float, float] | np.ndarray], list[float]]: + ) -> tuple[list[tuple[float, float]], 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 +810,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 +819,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) -> Any: r"""Plot the Learner2D's current state. This plot function interpolates the data on a regular grid. @@ -850,12 +850,12 @@ def plot(self, n=None, tri_alpha=0.0): vector *cannot* be used with the live_plotting functionality. """ hv = ensure_holoviews() - x, y = self.bounds - lbrt = x[0], y[0], x[1], y[1] + (xmin, xmax), (ymin, ymax) = self.bounds + lbrt = xmin, ymin, xmax, ymax 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 = { @@ -884,10 +884,10 @@ 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): return self.data - def _set_data(self, data: dict[tuple[float, float], Float | np.ndarray]) -> None: + def _set_data(self, data) -> None: self.data = data # Remove points from stack if they already exist for point in copy(self._stack): @@ -906,6 +906,6 @@ def __getstate__(self): def __setstate__(self, state): function, bounds, loss_per_triangle, _stack, data = state function = cloudpickle.loads(function) - self.__init__(function, bounds, loss_per_triangle) + 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..3a097fd83 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -5,15 +5,16 @@ import math import random from collections import OrderedDict -from collections.abc import Iterable +from collections.abc import Callable, Iterable, Mapping, Sequence from copy import deepcopy +from typing import Any, Literal, TypeAlias import numpy as np import scipy.spatial from scipy import interpolate from sortedcontainers import SortedKeyList -from adaptive.learner.base_learner import BaseLearner, uses_nth_neighbors +from adaptive.learner.base_learner import BaseLearner, DataFrame, uses_nth_neighbors from adaptive.learner.triangulation import fast_det from adaptive.learner.triangulation_backend import ( Triangulation, @@ -46,7 +47,10 @@ def to_list(inp): return [inp] -def volume(simplex, ys=None): +Simplex: TypeAlias = Sequence[Sequence[float]] | np.ndarray + + +def volume(simplex: Simplex, ys: Any = 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) @@ -64,7 +68,9 @@ def orientation(simplex): return sign -def uniform_loss(simplex, values, value_scale): +def uniform_loss( + simplex: Simplex, values: Sequence[Any] | np.ndarray, value_scale: float +) -> float: """ Uniform loss. @@ -84,7 +90,9 @@ def uniform_loss(simplex, values, value_scale): return volume(simplex) -def std_loss(simplex, values, value_scale): +def std_loss( + simplex: Simplex, values: Sequence[Any] | np.ndarray, value_scale: float +) -> float: """ Computes the loss of the simplex based on the standard deviation. @@ -110,7 +118,9 @@ 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: Simplex, values: Sequence[Any] | np.ndarray, value_scale: float +) -> float: """ Computes the average of the volumes of the simplex. @@ -172,7 +182,7 @@ def triangle_loss(simplex, values, value_scale, neighbors, neighbor_values): ) -def curvature_loss_function(exploration=0.05): +def curvature_loss_function(exploration: float = 0.05) -> Callable[..., float]: # XXX: add doc-string! @uses_nth_neighbors(1) def curvature_loss(simplex, values, value_scale, neighbors, neighbor_values): @@ -328,18 +338,22 @@ class LearnerND(BaseLearner): def __init__( self, - func, - bounds, - loss_per_simplex=None, + func: Callable[[Any], Any], + bounds: Sequence[Sequence[float | np.floating | np.integer]] + | np.ndarray + | scipy.spatial.ConvexHull, + loss_per_simplex: Callable[..., float] | None = None, *, - anisotropic=False, - triangulation_backend="auto", - ): + anisotropic: bool = False, + triangulation_backend: Literal["auto", "python", "rust"] | type = "auto", + ) -> None: self._triangulation_class = resolve_triangulation_class(triangulation_backend) - self._vdim = None + 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 + self.loss_per_simplex: Callable[..., float] = ( + 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: @@ -357,6 +371,7 @@ def __init__( self.pending_points = set() self.bounds = bounds + self._bbox: tuple[tuple[float, ...], ...] if isinstance(bounds, scipy.spatial.ConvexHull): hull_points = bounds.points[bounds.vertices] self._bounds_points = sorted(map(tuple, hull_points)) @@ -378,22 +393,24 @@ def __init__( ) self.function = func - self._tri = None - self._losses = {} + self._tri: Any = None + self._losses: dict[tuple[int, ...], float] = {} - self._pending_to_simplex = {} # vertex → simplex + self._pending_to_simplex: dict[tuple[float, ...], tuple[int, ...]] = {} # triangulation of the pending points inside a specific simplex - self._subtriangulations = {} # simplex → triangulation + self._subtriangulations: dict[ + tuple[int, ...], Any + ] = {} # simplex → triangulation # scale to unit hypercube # for the input self._transform = np.linalg.inv(np.diag(np.diff(self._bbox).flat)) # for the output - self._min_value = None - self._max_value = None + self._min_value: Any = None + self._max_value: Any = None self._old_scale = None - self._output_multiplier = ( + self._output_multiplier: float = ( 1 # If we do not know anything, do not scale the values ) self._recompute_losses_factor = 1.1 @@ -426,7 +443,7 @@ def new(self) -> LearnerND: ) @property - def npoints(self): + def npoints(self) -> int: # type: ignore[override] """Number of evaluated points.""" return len(self.data) @@ -463,7 +480,7 @@ def to_dataframe( # type: ignore[override] function_prefix: str = "function.", point_names: tuple[str, ...] | None = None, value_name: str = "value", - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a `pandas.DataFrame`. Parameters @@ -509,12 +526,12 @@ def to_dataframe( # type: ignore[override] def load_dataframe( # type: ignore[override] self, - df: pandas.DataFrame, + df: 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 @@ -582,13 +599,18 @@ def points(self): """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] | np.ndarray, + value: float | Sequence[float] | np.ndarray | None, + ) -> None: point = tuple(point) if point in self.data: return # we already know about the point if value is None: - return self.tell_pending(point) + self.tell_pending(point) + return self.pending_points.discard(point) tri = self.tri @@ -664,7 +686,12 @@ 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] | np.ndarray, + *, + simplex: tuple[int, ...] | None = None, + ) -> None: point = tuple(point) if not self.inside_bounds(point): return @@ -727,8 +754,10 @@ def _ask_and_tell_pending(self, n=1): xs, losses = zip(*(self._ask() for _ in range(n))) return list(xs), list(losses) - def ask(self, n, tell_pending=True): - """Chose points for learners.""" + def ask( + self, n: int, tell_pending: bool = True + ) -> tuple[list[tuple[float, ...]], list[float]]: + """Choose points for evaluation.""" if not tell_pending: with restore(self): return self._ask_and_tell_pending(n) @@ -754,8 +783,7 @@ 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 @@ -836,11 +864,11 @@ def _ask(self): def _compute_loss(self, simplex): # get the loss vertices = self.tri.get_vertices(simplex) - values = [self.data[tuple(v)] for v in vertices] + values = np.array([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) + values = self._output_multiplier * values if self.nth_neighbors == 0: # compute the loss on the scaled simplex @@ -985,7 +1013,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 @@ -1008,7 +1036,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) -> Any: """Plot the function we want to learn, only works in 2D. Parameters @@ -1066,7 +1094,7 @@ 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) -> Any: """Plot a 1D or 2D interpolated slice of a N-dimensional function. Parameters @@ -1088,12 +1116,12 @@ def plot_slice(self, cut_mapping, n=None): "multidimensional output not yet supported by `plot_slice`" ) n = n or 201 - values = [ - cut_mapping.get(i, np.linspace(*self._bbox[i], n)) - for i in range(self.ndim) + values: list[float | np.ndarray] = [ + cut_mapping[i] if i in cut_mapping else np.linspace(lo, hi, n) + for i, (lo, hi) in enumerate(self._bbox) ] ind = next(i for i in range(self.ndim) if i not in cut_mapping) - x = values[ind] + x = np.asarray(values[ind]) y = self._ip()(*values) p = hv.Path((x, y)) @@ -1138,7 +1166,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 + ) -> Any: """Plot the learner's data in 3D using plotly. Does *not* work with the @@ -1239,7 +1269,7 @@ def _get_iso(self, level=0.0, which="surface"): get_surface = False get_line = True - vertices = [] # index -> (x,y,z) + vertices: list[np.ndarray] = [] # index -> (x,y,z) faces_or_lines = [] # tuple of indices of the corner points @functools.lru_cache @@ -1260,7 +1290,7 @@ def _get_vertex_index(a, b): return new_index for simplex in self.tri.simplices: - plane_or_line = [] + 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]] @@ -1380,15 +1410,14 @@ def _get_hull_mesh(self, opacity=0.2): # 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[tuple[int, ...], tuple[int, ...]] = {} def _get_plane_color(simplex): 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: diff --git a/adaptive/learner/sequence_learner.py b/adaptive/learner/sequence_learner.py index 2209ff875..9d3ba16ed 100644 --- a/adaptive/learner/sequence_learner.py +++ b/adaptive/learner/sequence_learner.py @@ -1,22 +1,19 @@ from __future__ import annotations +from collections.abc import Callable, Sequence from copy import copy -from typing import TYPE_CHECKING, Any, TypeAlias +from typing import Any, TypeAlias import cloudpickle from sortedcontainers import SortedDict, SortedSet -from adaptive.learner.base_learner import BaseLearner -from adaptive.types import Int +from adaptive.learner.base_learner import BaseLearner, DataFrame from adaptive.utils import ( assign_defaults, cache_latest, partial_function_from_dataframe, ) -if TYPE_CHECKING: - from collections.abc import Callable, Sequence - try: import pandas @@ -26,7 +23,7 @@ with_pandas = False -PointType: TypeAlias = tuple[Int, Any] +PointType: TypeAlias = tuple[int, Any] class _IgnoreFirstArgument: @@ -50,7 +47,7 @@ def __getstate__(self): return self.function def __setstate__(self, function): - self.__init__(function) + type(self).__init__(self, function) class SequenceLearner(BaseLearner): @@ -166,7 +163,7 @@ def to_dataframe( # type: ignore[override] y_name: str = "y", *, full_sequence: bool = False, - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a `pandas.DataFrame`. Parameters @@ -205,7 +202,7 @@ def to_dataframe( # type: ignore[override] 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 = map(list, zip(*self.data.items())) if self.data else ([], []) sequence = [self.sequence[i] for i in indices] df = pandas.DataFrame(indices, columns=[index_name]) @@ -219,7 +216,7 @@ def to_dataframe( # type: ignore[override] def load_dataframe( # type: ignore[override] self, - df: pandas.DataFrame, + df: DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", index_name: str = "i", @@ -227,7 +224,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 @@ -293,5 +290,5 @@ def __getstate__(self): def __setstate__(self, state): function, sequence, data = state function = cloudpickle.loads(function) - self.__init__(function, sequence) + type(self).__init__(self, function, sequence) self._set_data(data) diff --git a/adaptive/learner/triangulation.py b/adaptive/learner/triangulation.py index 8cf377248..a2af7f6a7 100644 --- a/adaptive/learner/triangulation.py +++ b/adaptive/learner/triangulation.py @@ -345,7 +345,7 @@ def __init__(self, coords): self.vertices = list(coords) self.simplices = set() # initialise empty set for each vertex - self.vertex_to_simplices = [set() for _ in coords] + self.vertex_to_simplices: list[set[tuple[int, ...]]] = [set() for _ in coords] # find a Delaunay triangulation to start with, then we will throw it # away and continue with our own algorithm @@ -754,7 +754,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[tuple[int, ...], tuple[int, int]] = {} for n, simplex in enumerate(self.simplices): simplex = tuple(simplex) for i, _point in enumerate(simplex): diff --git a/adaptive/notebook_integration.py b/adaptive/notebook_integration.py index 5eb5c6d25..f4c592810 100644 --- a/adaptive/notebook_integration.py +++ b/adaptive/notebook_integration.py @@ -6,6 +6,10 @@ import random import warnings from contextlib import suppress +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from IPython import get_ipython _holoviews_enabled = False _ipywidgets_enabled = False @@ -80,7 +84,7 @@ 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 diff --git a/adaptive/runner.py b/adaptive/runner.py index aee4a6514..6a095a219 100644 --- a/adaptive/runner.py +++ b/adaptive/runner.py @@ -3,22 +3,21 @@ import abc import asyncio import concurrent.futures as concurrent -import functools import inspect import itertools import time import traceback import warnings -from collections.abc import Callable +from collections.abc import Callable, Iterable from contextlib import suppress from datetime import datetime, timedelta from importlib.util import find_spec -from typing import TYPE_CHECKING, Any, Literal, TypeAlias +from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias import loky from adaptive import BalancingLearner, DataSaver, IntegratorLearner, SequenceLearner -from adaptive.learner.base_learner import LearnerType +from adaptive.learner.base_learner import BaseLearner, LearnerType from adaptive.notebook_integration import in_ipynb, live_info, live_plot from adaptive.utils import SequentialExecutor @@ -26,14 +25,15 @@ if TYPE_CHECKING: import distributed - import holoviews import ipyparallel + from holoviews import DynamicMap, Element ExecutorTypes: TypeAlias = ( concurrent.Executor | distributed.Client | ipyparallel.Client ) else: ExecutorTypes = concurrent.Executor + DynamicMap = Element = Any with_ipyparallel = find_spec("ipyparallel") is not None @@ -60,7 +60,7 @@ _default_executor = loky.get_reusable_executor -class BaseRunner(metaclass=abc.ABCMeta): +class BaseRunner(Generic[LearnerType], metaclass=abc.ABCMeta): r"""Base class for runners that use `concurrent.futures.Executor`\'s. Parameters @@ -150,7 +150,7 @@ def __init__( retries: int = 0, raise_if_retries_exceeded: bool = True, allow_running_forever: bool = False, - ): + ) -> None: self.executor = _ensure_executor(executor) self.goal = _goal( learner, @@ -187,9 +187,7 @@ def __init__( self._tracebacks: dict[int, str] = {} self._id_to_point: dict[int, Any] = {} - self._next_id: Callable[[], int] = functools.partial( # type: ignore[assignment] - next, itertools.count() - ) # some unique id to be associated with each point + self._next_id = itertools.count().__next__ def _get_max_tasks(self) -> int: return self._max_tasks or _get_ncores(self.executor) @@ -249,7 +247,7 @@ def overhead(self) -> float: def _process_futures( self, - done_futs: set[FutureTypes], + done_futs: Iterable[FutureTypes], ) -> None: for fut in done_futs: pid = self._pending_tasks.pop(fut) @@ -270,19 +268,20 @@ def _process_futures( self._tracebacks.pop(pid, None) x = self._id_to_point.pop(pid) if self.do_log: - self.log.append(("tell", x, y)) # type: ignore[union-attr] + assert self.log is not None + self.log.append(("tell", x, y)) self.learner.tell(x, y) - def _get_futures( - self, - ) -> list[FutureTypes]: + def _get_futures(self) -> list[Any]: + # Each concrete runner uses only one kind of future. # Launch tasks to replace the ones that completed # on the last iteration, making sure to fill workers # that have started since the last iteration. n_new_tasks = max(0, self._get_max_tasks() - len(self._pending_tasks)) if self.do_log: - self.log.append(("ask", n_new_tasks)) # type: ignore[union-attr] + assert self.log is not None + self.log.append(("ask", n_new_tasks)) pids, _ = self._ask(n_new_tasks) @@ -290,14 +289,14 @@ def _get_futures( start_time = time.time() # so we can measure execution time point = self._id_to_point[pid] fut = self._submit(point) - fut.start_time = start_time + fut.start_time = start_time # type: ignore[union-attr] self._pending_tasks[fut] = pid # Collect and results and add them to the learner futures = list(self._pending_tasks.keys()) return futures - def _remove_unfinished(self) -> list[FutureTypes]: + def _remove_unfinished(self) -> list[Any]: # remove points with 'None' values from the learner self.learner.remove_unfinished() # cancel any outstanding tasks @@ -331,7 +330,7 @@ def elapsed_time(self): """ @abc.abstractmethod - def _submit(self, x): + def _submit(self, x: Any) -> FutureTypes: """Is called in `_get_futures`.""" @property @@ -349,7 +348,7 @@ def pending_points(self) -> list[tuple[FutureTypes, Any]]: ] -class BlockingRunner(BaseRunner): +class BlockingRunner(BaseRunner[LearnerType]): """Run a learner synchronously in an executor. Parameters @@ -460,7 +459,7 @@ def __init__( ) self._run() - def _submit(self, x: tuple[float, ...] | float | int) -> FutureTypes: + def _submit(self, x: Any) -> concurrent.Future: return self.executor.submit(self.learner.function, x) def _run(self) -> None: @@ -472,12 +471,12 @@ def _run(self) -> None: try: while not self.goal(self.learner): futures = self._get_futures() - done, _ = concurrent.wait(futures, return_when=first_completed) # type: ignore[arg-type] - self._process_futures(done) # type: ignore[arg-type] + done, _ = concurrent.wait(futures, return_when=first_completed) + self._process_futures(done) finally: remaining = self._remove_unfinished() if remaining: - concurrent.wait(remaining) # type: ignore[arg-type] + concurrent.wait(remaining) # Some futures get their result set, despite being cancelled. # see https://github.com/python-adaptive/adaptive/issues/319 with_result = {f for f in remaining if not f.cancelled() and f.done()} @@ -494,7 +493,7 @@ def elapsed_time(self) -> float: return self.end_time - self.start_time -class AsyncRunner(BaseRunner): +class AsyncRunner(BaseRunner[LearnerType]): r"""Run a learner asynchronously in an executor using `asyncio`. Parameters @@ -597,7 +596,7 @@ def __init__( ntasks: int | None = None, log: bool = False, shutdown_executor: bool = False, - ioloop=None, + ioloop: asyncio.AbstractEventLoop | None = None, retries: int = 0, raise_if_retries_exceeded: bool = True, ) -> None: @@ -640,7 +639,7 @@ def __init__( stacklevel=2, ) - def _submit(self, x: Any) -> asyncio.Task | asyncio.Future: + def _submit(self, x: Any) -> asyncio.Future: ioloop = self.ioloop if inspect.iscoroutinefunction(self.learner.function): return ioloop.create_task(self.learner.function(x)) @@ -681,11 +680,11 @@ def block_until_done(self) -> None: def live_plot( self, *, - plotter: Callable[[LearnerType], holoviews.Element] | None = None, + plotter: Callable[[LearnerType], Element] | None = None, update_interval: float = 2.0, name: str | None = None, normalize: bool = True, - ) -> holoviews.DynamicMap: + ) -> DynamicMap: """Live plotting of the learner's data. Parameters @@ -783,12 +782,12 @@ async def _run(self) -> None: try: while not self.goal(self.learner): futures = self._get_futures() - done, _ = await asyncio.wait(futures, return_when=first_completed) # type: ignore[arg-type,type-var] + done, _ = await asyncio.wait(futures, return_when=first_completed) self._process_futures(done) finally: remaining = self._remove_unfinished() if remaining: - await asyncio.wait(remaining) # type: ignore[type-var] + await asyncio.wait(remaining) self._cleanup() def elapsed_time(self) -> float: @@ -834,6 +833,7 @@ def start_periodic_saving( """ def default_save(learner): + assert save_kwargs is not None learner.save(**save_kwargs) if method is None: @@ -1031,7 +1031,7 @@ def _get_ncores( elif isinstance(ex, concurrent.ProcessPoolExecutor | concurrent.ThreadPoolExecutor): return ex._max_workers # type: ignore[union-attr] elif isinstance(ex, loky.reusable_executor._ReusablePoolExecutor): - return ex._max_workers # type: ignore[union-attr] + return ex._max_workers elif isinstance(ex, SequentialExecutor): return 1 elif with_distributed and isinstance(ex, distributed.cfexecutor.ClientExecutor): @@ -1047,7 +1047,7 @@ def _get_ncores( # TODO: deprecate -def stop_after(*, seconds=0, minutes=0, hours=0) -> Callable[[LearnerType], bool]: +def stop_after(*, seconds=0, minutes=0, hours=0) -> Callable[[BaseLearner], bool]: """Stop a runner after a specified time. For example, to specify a runner that should stop after @@ -1084,7 +1084,7 @@ def stop_after(*, seconds=0, minutes=0, hours=0) -> Callable[[LearnerType], bool class _TimeGoal: def __init__(self, dt: timedelta | datetime | int | float): self.dt = dt if isinstance(dt, timedelta | datetime) else timedelta(seconds=dt) - self.start_time = None + self.start_time: datetime | None = None def __call__(self, _): if isinstance(self.dt, timedelta): @@ -1102,9 +1102,9 @@ def auto_goal( npoints: int | None = None, end_time: datetime | None = None, duration: timedelta | int | float | None = None, - learner: LearnerType | None = None, + learner: BaseLearner | None = None, allow_running_forever: bool = True, -) -> Callable[[LearnerType], bool]: +) -> Callable[[Any], bool]: """Extract a goal from the learners. Parameters @@ -1154,11 +1154,10 @@ def auto_goal( for lrn in learner.learners ] return lambda learner: all( - goal(lrn) - for lrn, goal in zip(learner.learners, goals) # type: ignore[attr-defined] + goal(lrn) for lrn, goal in zip(learner.learners, goals) ) if npoints is not None: - return lambda learner: learner.npoints >= npoints # type: ignore[operator] + return lambda learner: learner.npoints >= npoints if end_time is not None: return _TimeGoal(end_time) if duration is not None: @@ -1166,7 +1165,7 @@ def auto_goal( if isinstance(learner, DataSaver): assert learner is not None return auto_goal( - learner=learner.learner, # type: ignore[arg-type] + learner=learner.learner, loss=loss, npoints=npoints, end_time=end_time, @@ -1175,9 +1174,9 @@ def auto_goal( ) if all(v is None for v in opts): if isinstance(learner, SequenceLearner): - return SequenceLearner.done # type: ignore[return-value] + return SequenceLearner.done if isinstance(learner, IntegratorLearner): - return IntegratorLearner.done # type: ignore[return-value] + return IntegratorLearner.done if not allow_running_forever: raise ValueError( "Goal is None which means the learners" @@ -1191,14 +1190,14 @@ def auto_goal( def _goal( - learner: LearnerType | None, + learner: LearnerType, goal: Callable[[LearnerType], bool] | None, loss_goal: float | None, npoints_goal: int | None, end_time_goal: datetime | None, duration_goal: timedelta | int | float | None, allow_running_forever: bool, -): +) -> Callable[[LearnerType], bool]: if callable(goal): return goal diff --git a/adaptive/tests/algorithm_4.py b/adaptive/tests/algorithm_4.py index 8741fdc53..bc105c06f 100644 --- a/adaptive/tests/algorithm_4.py +++ b/adaptive/tests/algorithm_4.py @@ -10,8 +10,6 @@ from numpy.testing import assert_allclose from scipy.linalg import inv, norm -from adaptive.types import Real - eps = np.spacing(1) @@ -234,18 +232,18 @@ def __init__(self, msg: str, igral: float, err: None, nr_points: int) -> None: class _Interval: __slots__ = ["a", "b", "c", "fx", "igral", "err", "depth", "rdepth", "ndiv", "c00"] - a: Real - b: Real + a: float + b: float c: np.ndarray fx: np.ndarray - igral: Real - err: Real + igral: float + err: float depth: int rdepth: int ndiv: int - c00: Real + c00: float - def __init__(self, a: Real, b: Real, depth: int, rdepth: int) -> None: + def __init__(self, a: float, b: float, depth: int, rdepth: int) -> None: self.a = a self.b = b self.depth = depth @@ -451,7 +449,7 @@ def f21(x: float | np.ndarray) -> float | np.ndarray: def f63(x: float | np.ndarray, alpha: float, beta: float) -> float | np.ndarray: - return abs(x - beta) ** alpha + return np.abs(x - beta) ** alpha def F63(x, alpha, beta): @@ -459,7 +457,7 @@ def F63(x, alpha, beta): def fdiv(x: float | np.ndarray) -> float | np.ndarray: - return abs(x - 0.987654321) ** -1.1 + return np.abs(x - 0.987654321) ** -1.1 def f_one_with_nan(x): diff --git a/adaptive/tests/test_learners.py b/adaptive/tests/test_learners.py index f740a7a01..e4c8f1815 100644 --- a/adaptive/tests/test_learners.py +++ b/adaptive/tests/test_learners.py @@ -103,7 +103,7 @@ def goal(): # Library of functions and associated learners. -learner_function_combos = collections.defaultdict(list) +learner_function_combos: dict = collections.defaultdict(list) def learn_with(learner_type, **init_kwargs): @@ -157,12 +157,12 @@ def sphere_of_fire(xyz, d: uniform(0.2, 0.5)): # type: ignore[valid-type] @learn_with(SequenceLearner, sequence=range(1000)) @learn_with(AverageLearner, rtol=1) -def gaussian(n): # type: ignore[valid-type] +def gaussian(n): return random.gauss(1, 1) @learn_with(AverageLearner1D, bounds=(-2, 2)) -def noisy_peak( # type: ignore[valid-type] +def noisy_peak( seed_x, sigma: uniform(1.5, 2.5), # type: ignore[valid-type] peak_width: uniform(0.04, 0.06), # type: ignore[valid-type] diff --git a/adaptive/types.py b/adaptive/types.py index e2869d46e..e7f8782aa 100644 --- a/adaptive/types.py +++ b/adaptive/types.py @@ -1,3 +1,5 @@ +"""Legacy type aliases retained for backwards compatibility.""" + from typing import TypeAlias import numpy as np diff --git a/adaptive/utils.py b/adaptive/utils.py index 2a1680cac..fe2d40c71 100644 --- a/adaptive/utils.py +++ b/adaptive/utils.py @@ -11,12 +11,18 @@ from contextlib import contextmanager from functools import wraps from itertools import product -from typing import TYPE_CHECKING, Any, TypeVar +from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar import cloudpickle if TYPE_CHECKING: from dask.distributed import Client as AsyncDaskClient +else: + AsyncDaskClient = Any + +P = ParamSpec("P") +T = TypeVar("T") +F = TypeVar("F", bound=Callable[..., Any]) def named_product(**items: Sequence[Any]): @@ -35,22 +41,23 @@ def restore(*learners) -> Iterator[None]: learner.__setstate__(state) -def cache_latest(f: Callable) -> Callable: +def cache_latest( + f: Callable[Concatenate[Any, P], T], +) -> Callable[Concatenate[Any, P], T]: """Cache the latest return value of the function and add it as 'self._cache[f.__name__]'.""" @functools.wraps(f) - def wrapper(*args, **kwargs): - self = args[0] + def wrapper(self: Any, /, *args: P.args, **kwargs: P.kwargs) -> T: if not hasattr(self, "_cache"): self._cache = {} - self._cache[f.__name__] = f(*args, **kwargs) + self._cache[f.__name__] = f(self, *args, **kwargs) return self._cache[f.__name__] return wrapper -def save(fname: str, data: Any, compress: bool = True) -> bool: +def save(fname: str | os.PathLike[str], data: Any, compress: bool = True) -> bool: fname = os.path.expanduser(fname) dirname = os.path.dirname(fname) if dirname: @@ -79,15 +86,14 @@ def save(fname: str, data: Any, compress: bool = True) -> bool: return True -def load(fname: str, compress: bool = True) -> Any: +def load(fname: str | os.PathLike[str], compress: bool = True) -> Any: fname = os.path.expanduser(fname) - _open = gzip.open if compress else open - with _open(fname, "rb") as f: # type: ignore[operator] + with gzip.open(fname, "rb") if compress else open(fname, "rb") as f: return cloudpickle.load(f) -def copy_docstring_from(other: Callable) -> Callable: - def decorator(method): +def copy_docstring_from(other: Callable[..., Any]) -> Callable[[F], F]: + def decorator(method: F) -> F: method.__doc__ = other.__doc__ return method @@ -152,8 +158,10 @@ class SequentialExecutor(concurrent.Executor): This executor is mainly for testing. """ - def submit(self, fn: Callable, *args, **kwargs) -> concurrent.Future: # type: ignore[override] - fut: concurrent.Future = concurrent.Future() + def submit( # type: ignore[override] + self, fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs + ) -> concurrent.Future[T]: + fut: concurrent.Future[T] = concurrent.Future() try: fut.set_result(fn(*args, **kwargs)) except Exception as e: @@ -163,19 +171,16 @@ def submit(self, fn: Callable, *args, **kwargs) -> concurrent.Future: # type: i def map(self, fn, *iterable, timeout=None, chunksize=1): return map(fn, iterable) - def shutdown(self, wait=True): + def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: pass -def _cache_key(args: tuple[Any], kwargs: dict[str, Any]) -> str: +def _cache_key(args: tuple[Any, ...], kwargs: dict[str, Any]) -> str: arg_strings = [str(a) for a in args] kwarg_strings = [f"{k}={v}" for k, v in sorted(kwargs.items())] return "_".join(arg_strings + kwarg_strings) -T = TypeVar("T") - - def daskify( client: AsyncDaskClient, cache: bool = False ) -> Callable[[Callable[..., T]], Callable[..., Awaitable[T]]]: @@ -183,19 +188,20 @@ def daskify( def _daskify(func: Callable[..., T]) -> Callable[..., Awaitable[T]]: if cache: - func.cache = {} # type: ignore[attr-defined] + setattr(func, "cache", {}) # noqa: B010 delayed_func = delayed(func) @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> T: if cache: - key = _cache_key(args, kwargs) # type: ignore[arg-type] - future = func.cache.get(key) # type: ignore[attr-defined] + key = _cache_key(args, kwargs) + futures = getattr(func, "cache") # noqa: B009 + future = futures.get(key) if future is None: future = client.compute(delayed_func(*args, **kwargs)) - func.cache[key] = future # type: ignore[attr-defined] + futures[key] = future else: future = client.compute(delayed_func(*args, **kwargs)) diff --git a/pyproject.toml b/pyproject.toml index 4c71f831f..13e00d885 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -117,6 +117,14 @@ output = ".coverage.xml" [tool.mypy] ignore_missing_imports = true python_version = "3.11" +check_untyped_defs = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[[tool.mypy.overrides]] +module = ["adaptive.tests.*"] +check_untyped_defs = false [tool.ruff] line-length = 88 @@ -126,7 +134,6 @@ target-version = "py311" select = ["B", "C", "E", "F", "W", "T", "B9", "I", "UP"] ignore = [ "T20", # flake8-print - "ANN101", # Missing type annotation for {name} in method "S101", # Use of assert detected "PD901", # df is a bad variable name. Be kinder to your future self. "ANN401", # Dynamically typed expressions (typing.Any) are disallowed in {name} From 7f45f322b21c51b37f4e69c41f61b298926e17a5 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 20:28:39 -0800 Subject: [PATCH 3/7] Cover typing compatibility and list-based 2D loss Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/tests/test_learner2d.py | 10 ++++++ adaptive/tests/test_learners.py | 4 +-- adaptive/tests/test_typing.py | 58 ++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 3 deletions(-) create mode 100644 adaptive/tests/test_typing.py diff --git a/adaptive/tests/test_learner2d.py b/adaptive/tests/test_learner2d.py index 299184752..9be168966 100644 --- a/adaptive/tests/test_learner2d.py +++ b/adaptive/tests/test_learner2d.py @@ -12,3 +12,13 @@ def test_remove_unfinished_invalidates_pending_loss() -> None: assert not learner.pending_points assert learner.loss(real=False) == learner.loss(real=True) + + +def test_loss_accepts_list(): + def loss(ip): + return [1.0] * len(ip.tri.simplices) + + learner = Learner2D(sum, bounds=[(0, 1), (0, 1)], loss_per_triangle=loss) + for point in learner.ask(4)[0]: + learner.tell(point, sum(point)) + assert learner.loss() == 1.0 diff --git a/adaptive/tests/test_learners.py b/adaptive/tests/test_learners.py index e4c8f1815..7789316f8 100644 --- a/adaptive/tests/test_learners.py +++ b/adaptive/tests/test_learners.py @@ -540,9 +540,7 @@ def test_learner_performance_is_invariant_under_scaling( yscale = 1000 * random.random() l_kwargs = dict(learner_kwargs) - bounds = xscale * np.array(l_kwargs["bounds"]) - bounds = tuple((bounds).tolist()) # to satisfy typeguard tests - l_kwargs["bounds"] = bounds + l_kwargs["bounds"] = xscale * np.array(l_kwargs["bounds"]) def scale_x(x): if isinstance(learner, AverageLearner1D): diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py new file mode 100644 index 000000000..73892db0b --- /dev/null +++ b/adaptive/tests/test_typing.py @@ -0,0 +1,58 @@ +"""PEP 561 and runtime compatibility of the public annotations.""" + +import subprocess +import sys +from importlib.resources import files +from typing import get_origin + +from adaptive import BalancingLearner, DataSaver, Learner1D, Runner + + +def test_py_typed_marker(): + # Also works when this test is run from the installed wheel. + assert files("adaptive").joinpath("py.typed").is_file() + + +def test_generic_subscription(): + for cls in (Runner, DataSaver, BalancingLearner): + assert get_origin(cls[Learner1D]) is cls + + +def test_public_types_without_optional_dependencies(): + subprocess.run( + [ + sys.executable, + "-c", + """ +import os +import sys +from typing import get_type_hints + +os.environ["ADAPTIVE_TRIANGULATION_BACKEND"] = "auto" +sys.modules.update(dict.fromkeys(( + "pandas", "holoviews", "plotly", "distributed", "ipyparallel", "mpi4py", + "dask", "adaptive_triangulation", +))) +import adaptive +from adaptive import BaseLearner, Learner1D, Learner2D, LearnerND +from adaptive import BalancingLearner, DataSaver, Runner + +assert adaptive.types.Real +assert "types" not in adaptive.__all__ + +for cls in (BaseLearner, Learner1D, Learner2D, LearnerND, BalancingLearner, DataSaver): + for name in ( + "__init__", "ask", "tell", "tell_pending", "loss", "new", + "to_dataframe", "load_dataframe", + ): + get_type_hints(getattr(cls, name)) + +for method in ( + Runner.__init__, Runner.live_plot, BalancingLearner.from_product, + LearnerND.plot_3D, LearnerND.plot_slice, adaptive.utils.daskify, +): + get_type_hints(method) +""", + ], + check=True, + ) From a19420dd412815c43ef64b0fb5cc107fc6f6382d Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 20:38:18 -0800 Subject: [PATCH 4/7] Accept async callbacks and NumPy learner inputs Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/learner/average_learner.py | 13 +++++++++---- adaptive/learner/integrator_learner.py | 11 ++++++++--- adaptive/learner/sequence_learner.py | 3 ++- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index de8d082f6..8f60952c5 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -2,6 +2,7 @@ from collections.abc import Callable from math import sqrt +from typing import Any import cloudpickle import numpy as np @@ -50,7 +51,7 @@ class AverageLearner(BaseLearner): def __init__( self, - function: Callable[[int], float], + function: Callable[[int], Any], atol: float | None = None, rtol: float | None = None, min_npoints: int = 2, @@ -176,15 +177,19 @@ 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: float) -> None: + def tell( + self, n: int | np.integer, value: float | np.floating | np.integer + ) -> None: if n in self.data: # The point has already been added before. return self.data[n] = value self.pending_points.discard(n) - self.sum_f += value - self.sum_f_sq += value**2 + # Keep NumPy's scalar promotion without coercing the sample. + sample: Any = value + self.sum_f += sample + self.sum_f_sq += sample**2 self.npoints += 1 def tell_pending(self, n: int) -> None: diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index fc9d4d8c0..49e792e26 100644 --- a/adaptive/learner/integrator_learner.py +++ b/adaptive/learner/integrator_learner.py @@ -3,10 +3,10 @@ import sys from collections import defaultdict -from collections.abc import Callable +from collections.abc import Callable, Sequence from math import sqrt from operator import attrgetter -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import cloudpickle import numpy as np @@ -341,7 +341,12 @@ def __repr__(self) -> str: class IntegratorLearner(BaseLearner): - def __init__(self, function: Callable, bounds: tuple[int, int], tol: float) -> None: + def __init__( + self, + function: Callable[[float], Any], + bounds: Sequence[float | np.floating | np.integer] | np.ndarray, + tol: float, + ) -> None: """ Parameters ---------- diff --git a/adaptive/learner/sequence_learner.py b/adaptive/learner/sequence_learner.py index 9d3ba16ed..e5bb8c3ec 100644 --- a/adaptive/learner/sequence_learner.py +++ b/adaptive/learner/sequence_learner.py @@ -5,6 +5,7 @@ from typing import Any, TypeAlias import cloudpickle +import numpy as np from sortedcontainers import SortedDict, SortedSet from adaptive.learner.base_learner import BaseLearner, DataFrame @@ -80,7 +81,7 @@ class SequenceLearner(BaseLearner): def __init__( self, function: Callable[[Any], Any], - sequence: Sequence[Any], + sequence: Sequence[Any] | np.ndarray, ): self._original_function = function self.function = _IgnoreFirstArgument(function) From d8e586f8c0864ac4d6237e851e7ce6420a2cfffd Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 21:01:07 -0800 Subject: [PATCH 5/7] Address Stage 2 typing review Accept iterator batches, NumPy scalar observations, ndarray simplex losses, and typed balancing callbacks. Describe npoints as read-only for type checking without imposing a runtime property. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/learner/average_learner.py | 2 +- adaptive/learner/average_learner1D.py | 23 +++++++---- adaptive/learner/balancing_learner.py | 49 ++++++++++++++---------- adaptive/learner/base_learner.py | 6 ++- adaptive/learner/integrator_learner.py | 2 +- adaptive/learner/learner1D.py | 20 ++++++---- adaptive/learner/learner2D.py | 4 +- adaptive/learner/learnerND.py | 13 ++++--- adaptive/learner/sequence_learner.py | 2 +- adaptive/tests/algorithm_4.py | 2 +- adaptive/tests/test_balancing_learner.py | 19 +++++++++ adaptive/tests/test_typing.py | 15 +++++++- adaptive/utils.py | 4 +- 13 files changed, 109 insertions(+), 52 deletions(-) diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index 8f60952c5..4995aa2fb 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -68,7 +68,7 @@ def __init__( self.function = function self.atol = atol self.rtol = rtol - self.npoints = 0 + self.npoints: int = 0 # Cannot estimate standard deviation with fewer than 2 points. self.min_npoints = max(min_npoints, 2) self.sum_f: float = 0.0 diff --git a/adaptive/learner/average_learner1D.py b/adaptive/learner/average_learner1D.py index 48e164ea4..0d1aebb6a 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -321,7 +321,9 @@ def tell_pending(self, seed_x: Point) -> None: # type: ignore[override] self._update_neighbors(x, self.neighbors_combined) self._update_losses(x, real=False) - def tell(self, seed_x: Point, y: float) -> None: # type: ignore[override] + def tell( # type: ignore[override] + self, seed_x: Point, y: float | np.floating | np.integer + ) -> None: seed, x = seed_x if y is None: raise TypeError( @@ -329,12 +331,14 @@ def tell(self, seed_x: Point, y: float) -> None: # type: ignore[override] "to indicate that this value is currently being calculated" ) + # Leave NumPy samples in their original dtype. + sample: Any = y if x not in self.data: - self._update_data(x, y, "new") - self._update_data_structures(seed_x, y, "new") + self._update_data(x, sample, "new") + self._update_data_structures(seed_x, sample, "new") elif seed not in self._data_samples[x]: # check if the seed is new - self._update_data(x, y, "resampled") - self._update_data_structures(seed_x, y, "resampled") + self._update_data(x, sample, "resampled") + self._update_data_structures(seed_x, sample, "resampled") self.pending_points.discard(seed_x) def _update_rescaled_error_in_mean(self, x: float, point_type: str) -> None: @@ -496,9 +500,12 @@ def _calc_error_in_mean( def tell_many( # type: ignore[override] self, - xs: Sequence[Point] | np.ndarray, - ys: Sequence[float] | np.ndarray, # type: ignore[override] + xs: Iterable[Point] | np.ndarray, + ys: Iterable[float | np.floating | np.integer] | np.ndarray, ) -> None: + if not isinstance(xs, Sequence | np.ndarray): + xs = list(xs) + # Check that all x are within the bounds # TODO: remove this requirement, all other learners add the data # but ignore it going forward. @@ -508,7 +515,7 @@ def tell_many( # type: ignore[override] ) # Create a mapping of points to a list of samples - mapping: defaultdict[float, dict[int, float]] = defaultdict(dict) + mapping: defaultdict[float, dict[int, Any]] = defaultdict(dict) for (seed, x), y in zip(xs, ys): mapping[x][seed] = y diff --git a/adaptive/learner/balancing_learner.py b/adaptive/learner/balancing_learner.py index 168cf70fa..a821bd062 100644 --- a/adaptive/learner/balancing_learner.py +++ b/adaptive/learner/balancing_learner.py @@ -2,7 +2,7 @@ import itertools from collections import defaultdict -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from contextlib import suppress from functools import partial from operator import itemgetter @@ -29,10 +29,21 @@ def dispatch(child_functions: list[Callable], arg: Any) -> Any: STRATEGY_TYPE: TypeAlias = Literal["loss_improvements", "loss", "npoints", "cycle"] CDIMS_TYPE: TypeAlias = ( - Sequence[dict[str, Any]] | tuple[Sequence[str], Sequence[tuple[Any, ...]]] | None + Iterable[dict[str, Any]] | tuple[Sequence[str], Iterable[Iterable[Any]]] | None ) +def _normalize_cdims(cdims: CDIMS_TYPE) -> Sequence[dict[str, Any]] | None: + if cdims is None: + return None + if not isinstance(cdims, Sequence): + cdims = list(cdims) + if cdims and not isinstance(cdims[0], dict): + keys, values_list = cdims + return [dict(zip(keys, values)) for values in values_list] + return cast(Sequence[dict[str, Any]], cdims) + + ProductLearner = TypeVar("ProductLearner", bound=BaseLearner) @@ -43,7 +54,7 @@ class BalancingLearner(BaseLearner, Generic[LearnerType]): ---------- learners : sequence of `~adaptive.BaseLearner`\s The learners from which to choose. These must all have the same type. - cdims : sequence of dicts, or (keys, iterable of values), optional + cdims : iterable of dicts, or (keys, iterable of values), optional Constant dimensions; the parameters that label the learners. Used in `plot`. Example inputs that all give identical results: @@ -104,7 +115,7 @@ def __init__( self._ask_cache: dict[int, Any] = {} self._loss: dict[int, float] = {} self._pending_loss: dict[int, float] = {} - self._cdims_default = cdims + self._cdims_default = _normalize_cdims(cdims) if len({learner.__class__ for learner in self.learners}) > 1: raise TypeError("A BalacingLearner can handle only one type of learners.") @@ -134,7 +145,7 @@ def pending_points(self) -> set[tuple[int, Any]]: # type: ignore[override] return pending_points @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: return sum(lrn.npoints for lrn in self.learners) @property @@ -344,14 +355,14 @@ def loss(self, real: bool = True) -> float: def plot( self, cdims: CDIMS_TYPE = None, - plotter: Callable[[BaseLearner], Any] | None = None, + plotter: Callable[[LearnerType], Any] | None = None, dynamic: bool = True, ): """Returns a DynamicMap with sliders. Parameters ---------- - cdims : sequence of dicts, or (keys, iterable of values), optional + cdims : iterable of dicts, or (keys, iterable of values), optional Constant dimensions; the parameters that label the learners. Example inputs that all give identical results: @@ -384,21 +395,17 @@ def plot( ``(dynamic=False)`` with sliders that are defined by `cdims`. """ hv = ensure_holoviews() - cdims = cdims or self._cdims_default - - if cdims is None: - cdims = [{"i": i} for i in range(len(self.learners))] - elif not isinstance(cdims[0], dict): - # Normalize the format - keys, values_list = cdims - cdims = [dict(zip(keys, values)) for values in values_list] - cdims = cast(list[dict[str, float]], cdims) + plot_cdims = _normalize_cdims(cdims) if cdims else self._cdims_default + + if plot_cdims is None: + plot_cdims = [{"i": i} for i in range(len(self.learners))] mapping = { - tuple(_cdims.values()): lrn for lrn, _cdims in zip(self.learners, cdims) + tuple(_cdims.values()): lrn + for lrn, _cdims in zip(self.learners, plot_cdims) } d = defaultdict(list) - for _cdims in cdims: + for _cdims in plot_cdims: for k, v in _cdims.items(): d[k].append(v) @@ -435,7 +442,7 @@ def from_product( f, learner_type: Callable[..., ProductLearner], learner_kwargs: dict[str, Any], - combos: dict[str, Sequence[Any]], + combos: Mapping[str, Iterable[Any]], ) -> BalancingLearner[ProductLearner]: """Create a `BalancingLearner` with learners of all combinations of named variables’ values. The `cdims` will be set correctly, so calling @@ -449,7 +456,7 @@ def from_product( The learner that should wrap the function. For example `Learner1D`. learner_kwargs : dict Keyword argument for the `learner_type`. For example `dict(bounds=[0, 1])`. - combos : dict (mapping individual fn arguments -> sequence of values) + combos : mapping (individual fn arguments to iterables of values) For all combinations of each argument a learner will be instantiated. Returns @@ -462,7 +469,7 @@ def from_product( >>> def f(x, n, alpha, beta): ... return scipy.special.eval_jacobi(n, alpha, beta, x) - >>> combos = { + >>> combos: dict[str, Iterable[Any]] = { ... 'n': [1, 2, 4, 8, 16], ... 'alpha': np.linspace(0, 2, 3), ... 'beta': np.linspace(0, 1, 5), diff --git a/adaptive/learner/base_learner.py b/adaptive/learner/base_learner.py index 10a2bd8d8..37edf7700 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -95,10 +95,14 @@ class BaseLearner(abc.ABC): """ data: dict[Any, Any] - npoints: int pending_points: set[Any] function: Callable[..., Any] + if TYPE_CHECKING: + + @property + def npoints(self) -> int: ... + def tell(self, x: Any, y: Any) -> None: """Tell the learner about a single value. diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index 49e792e26..e8c8599d5 100644 --- a/adaptive/learner/integrator_learner.py +++ b/adaptive/learner/integrator_learner.py @@ -533,7 +533,7 @@ def _fill_stack(self) -> list[float]: return self._stack @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) diff --git a/adaptive/learner/learner1D.py b/adaptive/learner/learner1D.py index 093d78f1e..4bcd1edf3 100644 --- a/adaptive/learner/learner1D.py +++ b/adaptive/learner/learner1D.py @@ -3,7 +3,7 @@ import collections.abc import itertools import math -from collections.abc import Callable, Sequence +from collections.abc import Callable, Iterable, Sequence from copy import copy, deepcopy from typing import Any, TypeAlias @@ -281,7 +281,7 @@ def __init__( self.losses_combined = 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 + self._dx_eps = 2 * max(np.abs(np.asarray(bounds))) * np.finfo(float).eps self.bounds: tuple[float, float] = (float(bounds[0]), float(bounds[1])) self.__missing_bounds = set(self.bounds) # cache of missing bounds @@ -395,7 +395,7 @@ def load_dataframe( # type: ignore[override] ) @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) @@ -557,7 +557,11 @@ def _update_scale(self, x: float, y: float | np.ndarray) -> None: 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: + def tell( + self, + x: float, + y: float | np.floating | np.integer | Sequence[float] | np.ndarray, + ) -> None: if x in self.data: # The point is already evaluated before return @@ -600,13 +604,15 @@ def tell_pending(self, x: float) -> None: self._update_neighbors(x, self.neighbors_combined) self._update_losses(x, real=False) - def tell_many( # type: ignore[override] + def tell_many( self, - xs: Sequence[float] | np.ndarray, - ys: Sequence[Any] | np.ndarray, + xs: Iterable[float] | np.ndarray, + ys: Iterable[Any], *, force: bool = False, ) -> None: + if not isinstance(xs, Sequence | np.ndarray): + xs = list(xs) if not force and not (len(xs) > 0.5 * len(self.data) and len(xs) > 2): # Only run this more efficient method if there are # at least 2 points and the amount of points added are diff --git a/adaptive/learner/learner2D.py b/adaptive/learner/learner2D.py index acf938cd5..abeb0cca8 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -564,7 +564,7 @@ def _unscale(self, points: np.ndarray) -> np.ndarray: return points * self.xy_scale + self.xy_mean @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) @@ -712,7 +712,7 @@ def inside_bounds(self, xy: tuple[float, float]) -> bool: def tell( self, point: Iterable[float] | np.ndarray, - value: float | Iterable[float] | np.ndarray, + value: float | np.floating | np.integer | Iterable[float] | np.ndarray, ) -> None: x, y = point point = (x, y) diff --git a/adaptive/learner/learnerND.py b/adaptive/learner/learnerND.py index 3a097fd83..a2f91f9c0 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -92,7 +92,7 @@ def uniform_loss( def std_loss( simplex: Simplex, values: Sequence[Any] | np.ndarray, value_scale: float -) -> float: +) -> np.ndarray: """ Computes the loss of the simplex based on the standard deviation. @@ -107,7 +107,8 @@ def std_loss( Returns ------- - loss : float + loss : numpy.ndarray + A one-element array containing the loss. """ r = np.linalg.norm(np.std(values, axis=0)) @@ -342,7 +343,7 @@ def __init__( bounds: Sequence[Sequence[float | np.floating | np.integer]] | np.ndarray | scipy.spatial.ConvexHull, - loss_per_simplex: Callable[..., float] | None = None, + loss_per_simplex: Callable[..., float | np.ndarray] | None = None, *, anisotropic: bool = False, triangulation_backend: Literal["auto", "python", "rust"] | type = "auto", @@ -351,7 +352,7 @@ def __init__( 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: Callable[..., float] = ( + self.loss_per_simplex: Callable[..., float | np.ndarray] = ( loss_per_simplex or rust_default_loss or default_loss ) @@ -443,7 +444,7 @@ def new(self) -> LearnerND: ) @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) @@ -602,7 +603,7 @@ def points(self): def tell( self, point: Iterable[float] | np.ndarray, - value: float | Sequence[float] | np.ndarray | None, + value: float | np.floating | np.integer | Sequence[float] | np.ndarray | None, ) -> None: point = tuple(point) if point in self.data: diff --git a/adaptive/learner/sequence_learner.py b/adaptive/learner/sequence_learner.py index e5bb8c3ec..814e36875 100644 --- a/adaptive/learner/sequence_learner.py +++ b/adaptive/learner/sequence_learner.py @@ -152,7 +152,7 @@ def result(self) -> list[Any]: return list(self.data.values()) @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: return len(self.data) def to_dataframe( # type: ignore[override] diff --git a/adaptive/tests/algorithm_4.py b/adaptive/tests/algorithm_4.py index bc105c06f..1c2167185 100644 --- a/adaptive/tests/algorithm_4.py +++ b/adaptive/tests/algorithm_4.py @@ -430,7 +430,7 @@ def algorithm_4( def f0(x: float | np.ndarray) -> float | np.ndarray: - return x * np.sin(1 / x) * np.sqrt(abs(1 - x)) + return x * np.sin(1 / x) * np.sqrt(np.abs(1 - x)) def f7(x): diff --git a/adaptive/tests/test_balancing_learner.py b/adaptive/tests/test_balancing_learner.py index b7ad7066b..f838e682c 100644 --- a/adaptive/tests/test_balancing_learner.py +++ b/adaptive/tests/test_balancing_learner.py @@ -2,6 +2,7 @@ from concurrent.futures import ThreadPoolExecutor from functools import partial +from itertools import product import numpy as np import pytest @@ -19,6 +20,24 @@ strategies = ["loss", "loss_improvements", "npoints", "cycle"] +@pytest.mark.parametrize("as_dicts", [True, False]) +def test_plot_reuses_default_iterable_cdims(as_dicts): + hv = pytest.importorskip("holoviews") + pytest.importorskip("bokeh") + hv.extension("bokeh") + cdims = ({"n": n} for n in (1, 2)) if as_dicts else (["n"], product([1, 2])) + learners = [Learner1D(float, bounds=(0, 1)) for _ in range(2)] + learner = BalancingLearner(learners, cdims=cdims) + + def plotter(child: Learner1D): + return hv.Curve(child.bounds) + + for _ in range(2): + plot = learner.plot(plotter=plotter) + assert plot.kdims[0].values == [1, 2] + assert isinstance(plot[1], hv.Curve) + + def test_balancing_learner_loss_cache(): learner = Learner1D(lambda x: x, bounds=(-1, 1)) learner.tell(-1, -1) diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index 73892db0b..0e98edec9 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -5,7 +5,7 @@ from importlib.resources import files from typing import get_origin -from adaptive import BalancingLearner, DataSaver, Learner1D, Runner +from adaptive import AverageLearner1D, BalancingLearner, DataSaver, Learner1D, Runner def test_py_typed_marker(): @@ -56,3 +56,16 @@ def test_public_types_without_optional_dependencies(): ], check=True, ) + + +def test_tell_many_accepts_iterators(): + xs = [0, 1, 2] + learner = Learner1D(float, (0, 2)) + learner.tell_many(iter(xs), map(learner.function, xs)) + assert learner.data == {0: 0, 1: 1, 2: 2} + + samples = [(seed, x) for x in xs for seed in range(2)] + average = AverageLearner1D(lambda point: point[1], (0, 2)) + average.tell_many(iter(samples), map(average.function, samples)) + assert average.data == learner.data + assert average.nsamples == len(samples) diff --git a/adaptive/utils.py b/adaptive/utils.py index fe2d40c71..c1b5a1aaa 100644 --- a/adaptive/utils.py +++ b/adaptive/utils.py @@ -7,7 +7,7 @@ import os import pickle import warnings -from collections.abc import Awaitable, Callable, Iterator, Sequence +from collections.abc import Awaitable, Callable, Iterable, Iterator from contextlib import contextmanager from functools import wraps from itertools import product @@ -25,7 +25,7 @@ F = TypeVar("F", bound=Callable[..., Any]) -def named_product(**items: Sequence[Any]): +def named_product(**items: Iterable[Any]): names = items.keys() vals = items.values() return [dict(zip(names, res)) for res in product(*vals)] From ebed0a4c321c361d6f9aa537be67f425237da850 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 21:21:56 -0800 Subject: [PATCH 6/7] Polish Stage 2 learner typing Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/learner/average_learner1D.py | 21 ++++++++++------ adaptive/learner/balancing_learner.py | 4 +-- adaptive/learner/base_learner.py | 3 ++- adaptive/learner/learnerND.py | 36 ++++++++++++--------------- adaptive/tests/test_typing.py | 10 ++++++++ 5 files changed, 43 insertions(+), 31 deletions(-) diff --git a/adaptive/learner/average_learner1D.py b/adaptive/learner/average_learner1D.py index 0d1aebb6a..db7d0d180 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -3,10 +3,10 @@ import math import sys from collections import defaultdict -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from copy import deepcopy from math import hypot -from typing import Any +from typing import Any, TypeVar import numpy as np import scipy.stats @@ -28,6 +28,7 @@ Point = tuple[int, float] Points = list[Point] +_Seed = TypeVar("_Seed", bound=int | np.integer) __all__: list[str] = ["AverageLearner1D"] @@ -386,7 +387,9 @@ def _update_data(self, x: float, y: float, 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: float, point_type: str) -> None: + def _update_data_structures( + self, seed_x: tuple[int | np.integer, float], y: float, point_type: str + ) -> None: seed, x = seed_x if point_type == "new": self._data_samples[x] = {seed: y} @@ -529,15 +532,17 @@ 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: float, seed_y_mapping: dict[int, float]) -> None: + def tell_many_at_point( + self, x: float, seed_y_mapping: Mapping[_Seed, float | np.floating | np.integer] + ) -> None: """Tell the learner about many samples at a certain location x. Parameters ---------- x : float Value from the function domain. - seed_y_mapping : Dict[int, float] - Dictionary of ``seed`` -> ``y`` at ``x``. + seed_y_mapping : Mapping + Mapping of integer seeds to real-valued samples at ``x``. """ # Check x is within the bounds if not np.prod(x >= self.bounds[0] and x <= self.bounds[1]): @@ -548,9 +553,9 @@ def tell_many_at_point(self, x: float, seed_y_mapping: dict[int, float]) -> None # If x is a new point: if x not in self.data: # we make a copy because we don't want to modify the original dict - seed_y_mapping = seed_y_mapping.copy() + seed_y_mapping = dict(seed_y_mapping) seed = next(iter(seed_y_mapping)) - y = seed_y_mapping.pop(seed) + y: Any = seed_y_mapping.pop(seed) self._update_data(x, y, "new") self._update_data_structures((seed, x), y, "new") diff --git a/adaptive/learner/balancing_learner.py b/adaptive/learner/balancing_learner.py index a821bd062..72dbb7591 100644 --- a/adaptive/learner/balancing_learner.py +++ b/adaptive/learner/balancing_learner.py @@ -442,7 +442,7 @@ def from_product( f, learner_type: Callable[..., ProductLearner], learner_kwargs: dict[str, Any], - combos: Mapping[str, Iterable[Any]], + combos: Mapping[str, Any], ) -> BalancingLearner[ProductLearner]: """Create a `BalancingLearner` with learners of all combinations of named variables’ values. The `cdims` will be set correctly, so calling @@ -469,7 +469,7 @@ def from_product( >>> def f(x, n, alpha, beta): ... return scipy.special.eval_jacobi(n, alpha, beta, x) - >>> combos: dict[str, Iterable[Any]] = { + >>> combos = { ... 'n': [1, 2, 4, 8, 16], ... 'alpha': np.linspace(0, 2, 3), ... 'beta': np.linspace(0, 1, 5), diff --git a/adaptive/learner/base_learner.py b/adaptive/learner/base_learner.py index 37edf7700..077ce81d3 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -3,6 +3,7 @@ import abc from collections.abc import Callable, Iterable from contextlib import suppress +from functools import cached_property from os import PathLike from typing import TYPE_CHECKING, Any, TypeVar @@ -100,7 +101,7 @@ class BaseLearner(abc.ABC): if TYPE_CHECKING: - @property + @cached_property def npoints(self) -> int: ... def tell(self, x: Any, y: Any) -> None: diff --git a/adaptive/learner/learnerND.py b/adaptive/learner/learnerND.py index a2f91f9c0..b1e0649bd 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -7,7 +7,7 @@ from collections import OrderedDict from collections.abc import Callable, Iterable, Mapping, Sequence from copy import deepcopy -from typing import Any, Literal, TypeAlias +from typing import Any, Literal, SupportsFloat, TypeAlias import numpy as np import scipy.spatial @@ -343,7 +343,7 @@ def __init__( bounds: Sequence[Sequence[float | np.floating | np.integer]] | np.ndarray | scipy.spatial.ConvexHull, - loss_per_simplex: Callable[..., float | np.ndarray] | None = None, + loss_per_simplex: Callable[..., SupportsFloat | np.ndarray] | None = None, *, anisotropic: bool = False, triangulation_backend: Literal["auto", "python", "rust"] | type = "auto", @@ -352,7 +352,7 @@ def __init__( 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: Callable[..., float | np.ndarray] = ( + self.loss_per_simplex: Callable[..., SupportsFloat | np.ndarray] = ( loss_per_simplex or rust_default_loss or default_loss ) @@ -874,33 +874,29 @@ def _compute_loss(self, simplex): if self.nth_neighbors == 0: # compute the loss on the scaled simplex loss = self.loss_per_simplex(vertices, 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) + else: + # 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] + neighbor_points = self.tri.get_vertices(neighbors) + neighbor_values = [self.data.get(x, None) for x in neighbor_points] - for i, point in enumerate(neighbor_points): - if point is not None: - neighbor_points[i] = point @ self._transform + for i, point in enumerate(neighbor_points): + if point is not None: + neighbor_points[i] = point @ self._transform - for i, value in enumerate(neighbor_values): - if value is not None: - neighbor_values[i] = self._output_multiplier * value + for i, value in enumerate(neighbor_values): + if value is not None: + neighbor_values[i] = self._output_multiplier * value - return float( - self.loss_per_simplex( + loss = self.loss_per_simplex( vertices, values, self._output_multiplier, neighbor_points, neighbor_values, ) - ) + return float(loss.item() if isinstance(loss, np.ndarray) else loss) def _update_losses(self, to_delete: set, to_add: set): # XXX: add the points outside the triangulation to this as well diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index 0e98edec9..2449f32cd 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -5,7 +5,11 @@ from importlib.resources import files from typing import get_origin +import numpy as np + from adaptive import AverageLearner1D, BalancingLearner, DataSaver, Learner1D, Runner +from adaptive.learner.base_learner import uses_nth_neighbors +from adaptive.learner.learnerND import LearnerND def test_py_typed_marker(): @@ -69,3 +73,9 @@ def test_tell_many_accepts_iterators(): average.tell_many(iter(samples), map(average.function, samples)) assert average.data == learner.data assert average.nsamples == len(samples) + + +def test_neighbor_aware_array_loss(): + learner = LearnerND(sum, [(0, 1)] * 2, uses_nth_neighbors(1)(lambda *_: np.ones(1))) + learner.tell_many([(0, 0), (0, 1), (1, 0), (1, 1)], [0, 1, 1, 2]) + assert learner.loss() == 1.0 From 4b54cf4c63814f20d3e8d27b2f28a75216f858b4 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Dec 2026 00:00:32 -0800 Subject: [PATCH 7/7] Stabilize mypy imports and accept balancing learner sequences Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/learner/balancing_learner.py | 8 +++++--- adaptive/learner/base_learner.py | 2 +- adaptive/tests/test_typing.py | 12 +++++++++++- pyproject.toml | 5 +++++ 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/adaptive/learner/balancing_learner.py b/adaptive/learner/balancing_learner.py index 72dbb7591..7f4a94ead 100644 --- a/adaptive/learner/balancing_learner.py +++ b/adaptive/learner/balancing_learner.py @@ -100,12 +100,12 @@ class BalancingLearner(BaseLearner, Generic[LearnerType]): def __init__( self, - learners: list[LearnerType], + learners: Sequence[LearnerType], *, cdims: CDIMS_TYPE = None, strategy: STRATEGY_TYPE = "loss_improvements", ) -> None: - self.learners = learners + self.learners: list[LearnerType] = list(learners) # Naively we would make 'function' a method, but this causes problems # when using executors from 'concurrent.futures' because we have to @@ -627,6 +627,8 @@ def __getstate__(self) -> tuple[list[LearnerType], CDIMS_TYPE, STRATEGY_TYPE]: self.strategy, ) - def __setstate__(self, state: tuple[list[LearnerType], CDIMS_TYPE, STRATEGY_TYPE]): + def __setstate__( + self, state: tuple[Sequence[LearnerType], CDIMS_TYPE, STRATEGY_TYPE] + ) -> None: learners, cdims, strategy = state type(self).__init__(self, learners, cdims=cdims, strategy=strategy) diff --git a/adaptive/learner/base_learner.py b/adaptive/learner/base_learner.py index 077ce81d3..acac5dfa4 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -100,7 +100,7 @@ class BaseLearner(abc.ABC): function: Callable[..., Any] if TYPE_CHECKING: - + # With cached_property, mypy accepts either a property or an attribute. @cached_property def npoints(self) -> int: ... diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index 2449f32cd..859813ed9 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -3,7 +3,7 @@ import subprocess import sys from importlib.resources import files -from typing import get_origin +from typing import assert_type, get_origin import numpy as np @@ -22,6 +22,16 @@ def test_generic_subscription(): assert get_origin(cls[Learner1D]) is cls +def test_balancing_learner_accepts_tuple() -> None: + learners: tuple[Learner1D, ...] = ( + Learner1D(float, (0, 1)), + Learner1D(float, (1, 2)), + ) + learner = BalancingLearner(learners) + assert_type(learner, BalancingLearner[Learner1D]) + assert learner.learners == list(learners) + + def test_public_types_without_optional_dependencies(): subprocess.run( [ diff --git a/pyproject.toml b/pyproject.toml index 13e00d885..3295e6262 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -126,6 +126,11 @@ no_implicit_optional = true module = ["adaptive.tests.*"] check_untyped_defs = false +[[tool.mypy.overrides]] +module = ["adaptive_triangulation.*", "scipy.*", "pandas.*"] +follow_imports = "skip" +follow_imports_for_stubs = true + [tool.ruff] line-length = 88 target-version = "py311"