From d20ca710291a9c8fc78862a3ad5a0e5d003b7c4d Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 16:44:06 -0800 Subject: [PATCH 1/9] Type runners, notebook integration, and shared utilities Preserve concrete learner types in runners and retire runtime typeguard instrumentation before adding static-only types. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- .github/workflows/typeguard.yml | 20 ---- .pre-commit-config.yaml | 2 +- adaptive/__init__.py | 4 +- adaptive/_types.py | 24 ----- adaptive/notebook_integration.py | 76 ++++++++++---- adaptive/runner.py | 174 ++++++++++++++++++------------- adaptive/tests/test_learners.py | 10 +- adaptive/utils.py | 125 +++++++++++++++------- noxfile.py | 8 -- pyproject.toml | 1 - 10 files changed, 256 insertions(+), 188 deletions(-) delete mode 100644 .github/workflows/typeguard.yml delete mode 100644 adaptive/_types.py diff --git a/.github/workflows/typeguard.yml b/.github/workflows/typeguard.yml deleted file mode 100644 index c89a4442..00000000 --- a/.github/workflows/typeguard.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: typeguard - -on: - pull_request: - push: - branches: [main] - -jobs: - typeguard: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: "3.13" - - name: Install uv - uses: astral-sh/setup-uv@v6 - - name: Test with nox - run: uv run --group nox nox -e pytest_typeguard diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e41c8498..c1c4264b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -23,7 +23,7 @@ repos: args: ["ruff", "--fix", "--ignore=E402,B018,F704"] additional_dependencies: [jupytext, ruff] - repo: https://github.com/pre-commit/mirrors-mypy - rev: "v1.15.0" + rev: "v2.4.1" hooks: - id: mypy exclude: ipynb_filter.py diff --git a/adaptive/__init__.py b/adaptive/__init__.py index 34f75d9a..47742d34 100644 --- a/adaptive/__init__.py +++ b/adaptive/__init__.py @@ -19,7 +19,7 @@ ) from adaptive.runner import AsyncRunner, BlockingRunner, Runner -from adaptive import learner, runner, utils # isort:skip +from adaptive import learner, notebook_integration, runner, utils # isort:skip __all__ = [ "learner", @@ -46,4 +46,4 @@ ] # to avoid confusion with `notebook_extension` -del notebook_integration # type: ignore[name-defined] # noqa: F821 +del notebook_integration diff --git a/adaptive/_types.py b/adaptive/_types.py deleted file mode 100644 index 3f56bf59..00000000 --- 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/notebook_integration.py b/adaptive/notebook_integration.py index 5eb5c6d2..cb564fc9 100644 --- a/adaptive/notebook_integration.py +++ b/adaptive/notebook_integration.py @@ -5,14 +5,42 @@ import importlib import random import warnings +from collections.abc import Hashable from contextlib import suppress +from types import ModuleType +from typing import TYPE_CHECKING, cast + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Mapping + from typing import Protocol + + import holoviews + import ipywidgets + + from adaptive.learner.base_learner import LearnerType + from adaptive.runner import AsyncRunner + + # IPython supplies this as a builtin; it is absent outside IPython. + get_ipython: Callable[[], object] + + class _Plottable(Protocol): + def plot(self) -> holoviews.Element: ... + + class _HasSamples(Protocol): + @property + def nsamples(self) -> int: ... + + class _HasLossCache(Protocol): + @property + def _cache(self) -> Mapping[str, float]: ... + _holoviews_enabled = False _ipywidgets_enabled = False _plotly_enabled = False -def notebook_extension(*, _inline_js=True): +def notebook_extension(*, _inline_js: bool = True) -> None: """Enable ipywidgets, holoviews, and asyncio notebook integration.""" if not in_ipynb(): raise RuntimeError( @@ -50,7 +78,7 @@ def notebook_extension(*, _inline_js=True): ) -def ensure_holoviews(): +def ensure_holoviews() -> ModuleType: try: return importlib.import_module("holoviews") except ModuleNotFoundError: @@ -59,7 +87,7 @@ def ensure_holoviews(): ) from None -def ensure_plotly(): +def ensure_plotly() -> ModuleType: global _plotly_enabled try: import plotly @@ -80,17 +108,24 @@ def ensure_plotly(): def in_ipynb() -> bool: try: # If we are running in IPython, then `get_ipython()` is always a global - return get_ipython().__class__.__name__ == "ZMQInteractiveShell" # type: ignore[name-defined] + return get_ipython().__class__.__name__ == "ZMQInteractiveShell" except NameError: return False # Fancy displays in the Jupyter notebook -active_plotting_tasks: dict[str, asyncio.Task] = {} +active_plotting_tasks: dict[Hashable, asyncio.Task[None]] = {} -def live_plot(runner, *, plotter=None, update_interval=2, name=None, normalize=True): +def live_plot( + runner: AsyncRunner[LearnerType], + *, + plotter: Callable[[LearnerType], holoviews.Element] | None = None, + update_interval: float = 2, + name: Hashable = None, + normalize: bool = True, +) -> holoviews.DynamicMap: """Live plotting of the learner's data. Parameters @@ -101,7 +136,7 @@ def live_plot(runner, *, plotter=None, update_interval=2, name=None, normalize=T holoviews object. By default ``learner.plot()`` will be called. update_interval : int Number of second between the updates of the plot. - name : hasable + name : hashable Name for the `live_plot` task in `adaptive.active_plotting_tasks`. By default the name is None and if another task with the same name already exists that other `live_plot` is canceled. @@ -125,10 +160,10 @@ def live_plot(runner, *, plotter=None, update_interval=2, name=None, normalize=T if name in active_plotting_tasks: active_plotting_tasks[name].cancel() - def plot_generator(): + def plot_generator() -> Iterator[holoviews.Element]: while True: if not plotter: - yield runner.learner.plot() + yield cast("_Plottable", runner.learner).plot() else: yield plotter(runner.learner) @@ -148,7 +183,7 @@ def plot_generator(): # Could have used dm.periodic in the following, but this would either spin # off a thread (and learner is not threadsafe) or block the kernel. - async def updater(): + async def updater() -> None: event = lambda: hv.streams.Stream.trigger( # noqa: E731 dm.streams ) # XXX: used to be dm.event() @@ -163,7 +198,7 @@ async def updater(): active_plotting_tasks.pop(name, None) cancel_button.layout.display = "none" # remove cancel button - def cancel(_): + def cancel(_: object) -> None: with suppress(KeyError): active_plotting_tasks[name].cancel() @@ -174,7 +209,7 @@ def cancel(_): return dm -def should_update(status): +def should_update(status: ipywidgets.HTML) -> bool: try: # Get the length of the write buffer size buffer_size = len(status.comm.kernel.iopub_thread._events) @@ -192,7 +227,9 @@ def should_update(status): return True -def live_info(runner, *, update_interval=0.5): +def live_info( + runner: AsyncRunner[LearnerType], *, update_interval: float = 0.5 +) -> None: """Display live information about the runner. Returns an interactive ipywidget that can be @@ -213,7 +250,7 @@ def live_info(runner, *, update_interval=0.5): ) cancel.on_click(lambda _: runner.cancel()) - async def update(): + async def update() -> None: while not runner.task.done(): await asyncio.sleep(update_interval) @@ -230,7 +267,7 @@ async def update(): display(ipywidgets.VBox((status, cancel))) -def _table_row(i, key, value): +def _table_row(i: int, key: str, value: object) -> str: """Style the rows of a table. Based on the default Jupyterlab table style.""" style = "text-align: right; padding: 0.5em 0.5em; line-height: 1.0;" if i % 2 == 1: @@ -238,7 +275,7 @@ def _table_row(i, key, value): return f'{key}{value}' -def _info_html(runner): +def _info_html(runner: AsyncRunner[LearnerType]) -> str: status = runner.status() color = { @@ -252,7 +289,7 @@ def _info_html(runner): red_level = max(0, min(int(255 * overhead / 100), 255)) overhead_color = f"#{red_level:02x}{255 - red_level:02x}{0:02x}" - info = [ + info: list[tuple[str, str | int | datetime.timedelta]] = [ ("status", f'{status}'), ("elapsed time", datetime.timedelta(seconds=runner.elapsed_time())), ("overhead", f'{overhead:.2f}%'), @@ -262,10 +299,11 @@ def _info_html(runner): info.append(("# of points", runner.learner.npoints)) with suppress(Exception): - info.append(("# of samples", runner.learner.nsamples)) + info.append(("# of samples", cast("_HasSamples", runner.learner).nsamples)) with suppress(Exception): - info.append(("latest loss", f"{runner.learner._cache['loss']:.3f}")) + cache = cast("_HasLossCache", runner.learner)._cache + info.append(("latest loss", f"{cache['loss']:.3f}")) table = "\n".join(_table_row(i, k, v) for i, (k, v) in enumerate(info)) diff --git a/adaptive/runner.py b/adaptive/runner.py index 99f1f4e4..962579cc 100644 --- a/adaptive/runner.py +++ b/adaptive/runner.py @@ -9,25 +9,53 @@ 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, cast 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 FutureTypes: TypeAlias = concurrent.Future | asyncio.Future +_LogEntry: TypeAlias = tuple[Literal["tell"], Any, Any] | tuple[Literal["ask"], int] if TYPE_CHECKING: + from typing import Protocol + + import distributed.cfexecutor import holoviews + import ipyparallel.client.view + import mpi4py.futures + + from adaptive.notebook_integration import _HasLossCache, _HasSamples + + 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 + ) + + class _TimedFuture(Protocol): + start_time: float - from ._types import ExecutorTypes + class _HasMaxWorkers(Protocol): + _max_workers: int + + class _HasLearners(Protocol): + @property + def learners(self) -> Iterable[BaseLearner]: ... with_ipyparallel = find_spec("ipyparallel") is not None @@ -38,7 +66,8 @@ with suppress(ModuleNotFoundError): import uvloop - asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + # Preserve the existing uvloop integration on supported Python versions. + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # ty: ignore[deprecated] # -- Runner definitions @@ -54,7 +83,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 @@ -144,7 +173,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, @@ -167,12 +196,12 @@ def __init__( self.shutdown_executor = shutdown_executor self.learner = learner - self.log: list | None = [] if log else None + self.log: list[_LogEntry] | None = [] if log else None # Timing self.start_time = time.time() self.end_time: float | None = None - self._elapsed_function_time = 0 + self._elapsed_function_time: float = 0 # Error handling attributes self.retries = retries @@ -181,8 +210,8 @@ 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() + self._next_id = cast( + "Callable[[], int]", functools.partial(next, itertools.count()) ) # some unique id to be associated with each point def _get_max_tasks(self) -> int: @@ -243,14 +272,14 @@ 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) try: y = fut.result() # total execution time - t = time.time() - fut.start_time # type: ignore[union-attr] + t = time.time() - cast("_TimedFuture", fut).start_time except Exception as e: self._tracebacks[pid] = traceback.format_exc() self._to_retry[pid] = self._to_retry.get(pid, 0) + 1 @@ -264,7 +293,7 @@ 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] + cast("list[_LogEntry]", self.log).append(("tell", x, y)) self.learner.tell(x, y) def _get_futures( @@ -276,7 +305,7 @@ def _get_futures( 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] + cast("list[_LogEntry]", self.log).append(("ask", n_new_tasks)) pids, _ = self._ask(n_new_tasks) @@ -284,7 +313,7 @@ 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 + cast("_TimedFuture", fut).start_time = start_time self._pending_tasks[fut] = pid # Collect and results and add them to the learner @@ -317,7 +346,7 @@ def failed(self) -> set[int]: return set(self._tracebacks) - set(self._to_retry) @abc.abstractmethod - def elapsed_time(self): + def elapsed_time(self) -> float: """Return the total time elapsed since the runner was started. @@ -325,15 +354,15 @@ def elapsed_time(self): """ @abc.abstractmethod - def _submit(self, x): + def _submit(self, x: Any) -> FutureTypes: """Is called in `_get_futures`.""" @property - def tracebacks(self) -> list[tuple[int, str]]: + def tracebacks(self) -> list[tuple[Any, str]]: return [(self._id_to_point[pid], tb) for pid, tb in self._tracebacks.items()] @property - def to_retry(self) -> list[tuple[int, int]]: + def to_retry(self) -> list[tuple[Any, int]]: return [(self._id_to_point[pid], n) for pid, n in self._to_retry.items()] @property @@ -343,7 +372,7 @@ def pending_points(self) -> list[tuple[FutureTypes, Any]]: ] -class BlockingRunner(BaseRunner): +class BlockingRunner(BaseRunner[LearnerType]): """Run a learner synchronously in an executor. Parameters @@ -454,7 +483,7 @@ def __init__( ) self._run() - def _submit(self, x: tuple[float, ...] | float | int) -> FutureTypes: + def _submit(self, x: Any) -> concurrent.Future[Any]: return self.executor.submit(self.learner.function, x) def _run(self) -> None: @@ -465,13 +494,14 @@ 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] + # BlockingRunner._submit produces only concurrent futures. + futures = cast("list[concurrent.Future[Any]]", self._get_futures()) + done, _ = concurrent.wait(futures, return_when=first_completed) + self._process_futures(done) finally: - remaining = self._remove_unfinished() + remaining = cast("list[concurrent.Future[Any]]", 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()} @@ -488,7 +518,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 @@ -591,7 +621,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: @@ -624,7 +654,7 @@ def __init__( self.executor.shutdown() # Make sure we don't shoot ourselves later self.task = self.ioloop.create_task(self._run()) - self.saving_task: asyncio.Task | None = None + self.saving_task: asyncio.Task[None] | None = None if in_ipynb() and not self.ioloop.is_running(): warnings.warn( "The runner has been scheduled, but the asyncio " @@ -634,7 +664,7 @@ def __init__( stacklevel=2, ) - def _submit(self, x: Any) -> asyncio.Task | asyncio.Future: + def _submit(self, x: Any) -> asyncio.Future[Any]: ioloop = self.ioloop if inspect.iscoroutinefunction(self.learner.function): return ioloop.create_task(self.learner.function(x)) @@ -690,7 +720,7 @@ def live_plot( holoviews object. By default ``learner.plot()`` will be called. update_interval : int Number of second between the updates of the plot. - name : hasable + name : hashable Name for the `live_plot` task in `adaptive.active_plotting_tasks`. By default the name is None and if another task with the same name already exists that other `live_plot` is canceled. @@ -720,7 +750,7 @@ def live_info(self, *, update_interval: float = 0.1) -> None: def live_info_terminal( self, *, update_interval: float = 0.5, overwrite_previous: bool = True - ) -> asyncio.Task: + ) -> asyncio.Task[None]: """ Display live information about the runner in the terminal. @@ -754,7 +784,7 @@ def live_info_terminal( position. It might not work as expected on all terminal emulators. """ - async def _update(runner: AsyncRunner) -> None: + async def _update(runner: AsyncRunner[LearnerType]) -> None: try: while not runner.task.done(): if overwrite_previous: @@ -776,13 +806,14 @@ 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] + # AsyncRunner._submit produces only asyncio futures. + futures = cast("list[asyncio.Future[Any]]", self._get_futures()) + done, _ = await asyncio.wait(futures, return_when=first_completed) self._process_futures(done) finally: - remaining = self._remove_unfinished() + remaining = cast("list[asyncio.Future[Any]]", self._remove_unfinished()) if remaining: - await asyncio.wait(remaining) # type: ignore[type-var] + await asyncio.wait(remaining) self._cleanup() def elapsed_time(self) -> float: @@ -803,7 +834,7 @@ def start_periodic_saving( save_kwargs: dict[str, Any] | None = None, interval: int = 30, method: Callable[[LearnerType], None] | None = None, - ): + ) -> asyncio.Task[None]: """Periodically save the learner's data. Parameters @@ -827,15 +858,16 @@ def start_periodic_saving( ... interval=600) """ - def default_save(learner): - learner.save(**save_kwargs) - if method is None: - method = default_save if save_kwargs is None: raise ValueError("Must provide `save_kwargs` if method=None.") - async def _saver(): + def default_save(learner: LearnerType) -> None: + learner.save(**save_kwargs) + + method = default_save + + async def _saver() -> None: while self.status() == "running": method(self.learner) # No asyncio.shield needed, as 'wait' does not cancel any tasks. @@ -846,7 +878,7 @@ async def _saver(): return self.saving_task -def _info_text(runner, separator: str = "\n"): +def _info_text(runner: AsyncRunner[LearnerType], separator: str = "\n") -> str: status = runner.status() color_map = { @@ -862,7 +894,7 @@ def _info_text(runner, separator: str = "\n"): else: overhead_color = "\033[31m" # Red - info = [ + info: list[tuple[str, str | int]] = [ ("time", str(datetime.now())), ("status", f"{color_map[status]}{status}\033[0m"), ("elapsed time", str(timedelta(seconds=runner.elapsed_time()))), @@ -873,10 +905,11 @@ def _info_text(runner, separator: str = "\n"): info.append(("# of points", runner.learner.npoints)) with suppress(Exception): - info.append(("# of samples", runner.learner.nsamples)) + info.append(("# of samples", cast("_HasSamples", runner.learner).nsamples)) with suppress(Exception): - info.append(("latest loss", f"{runner.learner._cache['loss']:.3f}")) + cache = cast("_HasLossCache", runner.learner)._cache + info.append(("latest loss", f"{cache['loss']:.3f}")) width = 30 formatted_info = [f"{k}: {v}".ljust(width) for i, (k, v) in enumerate(info)] @@ -896,7 +929,7 @@ def simple( end_time_goal: datetime | None = None, duration_goal: timedelta | int | float | None = None, points_per_ask: int = 1, -): +) -> None: """Run the learner until the goal is reached. Requests points from the learner, evaluates @@ -952,10 +985,7 @@ def simple( learner.tell(x, y) -def replay_log( - learner: LearnerType, - log: list[tuple[Literal["tell"], Any, Any] | tuple[Literal["ask"], int]], -) -> None: +def replay_log(learner: BaseLearner, log: list[_LogEntry]) -> None: """Apply a sequence of method calls to a learner. This is useful for debugging runners. @@ -1010,22 +1040,20 @@ def _ensure_executor(executor: ExecutorTypes | None) -> concurrent.Executor: ) -def _get_ncores( - ex: ExecutorTypes, -) -> int: +def _get_ncores(ex: concurrent.Executor) -> int: """Return the maximum number of cores that an executor can use.""" if with_ipyparallel: - import ipyparallel + import ipyparallel.client.view if with_distributed: - import distributed + import distributed.cfexecutor if with_mpi4py: import mpi4py.futures if with_ipyparallel and isinstance(ex, ipyparallel.client.view.ViewExecutor): return len(ex.view) elif isinstance(ex, concurrent.ProcessPoolExecutor | concurrent.ThreadPoolExecutor): - return ex._max_workers # type: ignore[union-attr] + return cast("_HasMaxWorkers", ex)._max_workers elif isinstance(ex, loky.reusable_executor._ReusablePoolExecutor): - return ex._max_workers # type: ignore[union-attr] + return cast("_HasMaxWorkers", ex)._max_workers elif isinstance(ex, SequentialExecutor): return 1 elif with_distributed and isinstance(ex, distributed.cfexecutor.ClientExecutor): @@ -1041,7 +1069,9 @@ def _get_ncores( # TODO: deprecate -def stop_after(*, seconds=0, minutes=0, hours=0) -> Callable[[LearnerType], bool]: +def stop_after( + *, seconds: float = 0, minutes: float = 0, hours: float = 0 +) -> Callable[[BaseLearner], bool]: """Stop a runner after a specified time. For example, to specify a runner that should stop after @@ -1076,11 +1106,11 @@ def stop_after(*, seconds=0, minutes=0, hours=0) -> Callable[[LearnerType], bool class _TimeGoal: - def __init__(self, dt: timedelta | datetime | int | float): + def __init__(self, dt: timedelta | datetime | int | float) -> None: 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, _): + def __call__(self, _: BaseLearner) -> bool: if isinstance(self.dt, timedelta): if self.start_time is None: self.start_time = datetime.now() @@ -1149,29 +1179,31 @@ def auto_goal( ] return lambda learner: all( goal(lrn) - for lrn, goal in zip(learner.learners, goals) # type: ignore[attr-defined] + for lrn, goal in zip(cast("_HasLearners", 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: return _TimeGoal(duration) if isinstance(learner, DataSaver): assert learner is not None - return auto_goal( - learner=learner.learner, # type: ignore[arg-type] + goal = auto_goal( + learner=learner.learner, loss=loss, npoints=npoints, end_time=end_time, duration=duration, allow_running_forever=allow_running_forever, ) + # DataSaver delegates attributes to its wrapped learner. + return cast("Callable[[LearnerType], bool]", goal) if all(v is None for v in opts): if isinstance(learner, SequenceLearner): - return SequenceLearner.done # type: ignore[return-value] + return cast("Callable[[LearnerType], bool]", SequenceLearner.done) if isinstance(learner, IntegratorLearner): - return IntegratorLearner.done # type: ignore[return-value] + return cast("Callable[[LearnerType], bool]", IntegratorLearner.done) if not allow_running_forever: raise ValueError( "Goal is None which means the learners" @@ -1192,7 +1224,7 @@ def _goal( 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/test_learners.py b/adaptive/tests/test_learners.py index f740a7a0..71189160 100644 --- a/adaptive/tests/test_learners.py +++ b/adaptive/tests/test_learners.py @@ -9,6 +9,8 @@ import shutil import tempfile import time +from collections.abc import Callable +from typing import Any import flaky import numpy as np @@ -103,7 +105,9 @@ def goal(): # Library of functions and associated learners. -learner_function_combos = collections.defaultdict(list) +learner_function_combos: dict[type, list[tuple[Callable[..., Any], dict[str, Any]]]] = ( + collections.defaultdict(list) +) def learn_with(learner_type, **init_kwargs): @@ -157,12 +161,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/utils.py b/adaptive/utils.py index 2a1680ca..8ae024f1 100644 --- a/adaptive/utils.py +++ b/adaptive/utils.py @@ -7,26 +7,48 @@ import os import pickle import warnings -from collections.abc import Awaitable, Callable, Iterator, Sequence +from collections.abc import Awaitable, Callable, Generator, Iterable, Iterator, Sequence 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, ParamSpec, Protocol, TypeVar, cast import cloudpickle if TYPE_CHECKING: + from os import PathLike + + import pandas from dask.distributed import Client as AsyncDaskClient -def named_product(**items: Sequence[Any]): +P = ParamSpec("P") +T = TypeVar("T") +F = TypeVar("F", bound=Callable[..., Any]) + + +class _Restorable(Protocol): + def __getstate__(self) -> Any: ... + + def __setstate__(self, state: Any, /) -> None: ... + + +class _HasCache(Protocol): + _cache: dict[str, Any] + + +class _HasName(Protocol): + __name__: str + + +def named_product(**items: Sequence[T]) -> list[dict[str, T]]: names = items.keys() vals = items.values() return [dict(zip(names, res)) for res in product(*vals)] @contextmanager -def restore(*learners) -> Iterator[None]: +def restore(*learners: _Restorable) -> Generator[None, None, None]: states = [learner.__getstate__() for learner in learners] try: yield @@ -35,22 +57,23 @@ def restore(*learners) -> Iterator[None]: learner.__setstate__(state) -def cache_latest(f: Callable) -> Callable: +def cache_latest(f: Callable[P, T]) -> Callable[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(*args: P.args, **kwargs: P.kwargs) -> T: + self = cast(_HasCache, args[0]) if not hasattr(self, "_cache"): self._cache = {} - self._cache[f.__name__] = f(*args, **kwargs) - return self._cache[f.__name__] + named = cast(_HasName, f) + self._cache[named.__name__] = f(*args, **kwargs) + return self._cache[named.__name__] return wrapper -def save(fname: str, data: Any, compress: bool = True) -> bool: +def save(fname: str | PathLike[str], data: Any, compress: bool = True) -> bool: fname = os.path.expanduser(fname) dirname = os.path.dirname(fname) if dirname: @@ -79,22 +102,26 @@ def save(fname: str, data: Any, compress: bool = True) -> bool: return True -def load(fname: str, compress: bool = True) -> Any: +def load(fname: str | 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] + if compress: + with gzip.open(fname, "rb") as f: + return cloudpickle.load(f) + with 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 return decorator -def _default_parameters(function, function_prefix: str = "function."): +def _default_parameters( + function: Callable[..., Any], function_prefix: str = "function." +) -> dict[str, Any]: sig = inspect.signature(function) defaults = { f"{function_prefix}{k}": v.default @@ -104,13 +131,19 @@ def _default_parameters(function, function_prefix: str = "function."): return defaults -def assign_defaults(function, df, function_prefix: str = "function."): +def assign_defaults( + function: Callable[..., Any], + df: pandas.DataFrame, + function_prefix: str = "function.", +) -> None: defaults = _default_parameters(function, function_prefix) for k, v in defaults.items(): df[k] = len(df) * [v] -def partial_function_from_dataframe(function, df, function_prefix: str = "function."): +def partial_function_from_dataframe( + function: Callable[..., T], df: pandas.DataFrame, function_prefix: str = "function." +) -> Callable[..., T]: if function_prefix == "": raise ValueError( "The function_prefix cannot be an empty string because" @@ -152,50 +185,64 @@ 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() - try: - fut.set_result(fn(*args, **kwargs)) - except Exception as e: - fut.set_exception(e) - return fut - - def map(self, fn, *iterable, timeout=None, chunksize=1): + if TYPE_CHECKING: + + def submit( + self, fn: Callable[P, T], /, *args: P.args, **kwargs: P.kwargs + ) -> concurrent.Future[T]: ... + + else: + + def submit( + 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: + fut.set_exception(e) + return fut + + def map( + self, + fn: Callable[..., T], + *iterable: Iterable[Any], + timeout: float | None = None, + chunksize: int = 1, + ) -> Iterator[T]: 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]]]: +) -> Callable[[Callable[P, T]], Callable[P, Awaitable[T]]]: from dask import delayed - def _daskify(func: Callable[..., T]) -> Callable[..., Awaitable[T]]: + def _daskify(func: Callable[P, T]) -> Callable[P, 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: + async def wrapper(*args: P.args, **kwargs: P.kwargs) -> 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) + cached: dict[str, Awaitable[T]] = getattr(func, "cache") # noqa: B009 + future = cached.get(key) if future is None: future = client.compute(delayed_func(*args, **kwargs)) - func.cache[key] = future # type: ignore[attr-defined] + getattr(func, "cache")[key] = future # noqa: B009 else: future = client.compute(delayed_func(*args, **kwargs)) diff --git a/noxfile.py b/noxfile.py index 17c663d7..b2e121fc 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 470ec746..5f3e672c 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]"] From 370f2909b27de7bff73c208d488867be0ca43f1d Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 16:45:13 -0800 Subject: [PATCH 2/9] Type learner interfaces, implementations, and triangulation backends Keep the base contract and concrete learners together so each commit type-checks. Preserve runtime learner signatures and pickle payloads. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/learner/average_learner.py | 84 ++-- adaptive/learner/average_learner1D.py | 151 ++++--- adaptive/learner/balancing_learner.py | 155 ++++---- adaptive/learner/base_learner.py | 201 ++++++---- adaptive/learner/data_saver.py | 63 +-- adaptive/learner/integrator_coeffs.py | 35 +- adaptive/learner/integrator_learner.py | 122 +++--- adaptive/learner/learner1D.py | 326 +++++++++------ adaptive/learner/learner2D.py | 273 ++++++++----- adaptive/learner/learnerND.py | 462 ++++++++++++++-------- adaptive/learner/sequence_learner.py | 62 +-- adaptive/learner/triangulation.py | 163 +++++--- adaptive/learner/triangulation_backend.py | 136 ++++++- adaptive/tests/algorithm_4.py | 28 +- adaptive/types.py | 2 + 15 files changed, 1470 insertions(+), 793 deletions(-) diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index 2ee30992..d506797c 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -2,19 +2,23 @@ from collections.abc import Callable from math import sqrt +from typing import TYPE_CHECKING, Any, Self, TypeAlias, cast import cloudpickle import numpy as np from adaptive.learner.base_learner import BaseLearner from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Float, Int, Real from adaptive.utils import ( assign_defaults, cache_latest, partial_function_from_dataframe, ) +if TYPE_CHECKING: + from holoviews.element import Histogram + from numpy.typing import NDArray + try: import pandas @@ -24,6 +28,11 @@ with_pandas = False +_Seed: TypeAlias = int | np.integer[Any] +_Sample: TypeAlias = float | np.float64 | np.int_ +_AverageData: TypeAlias = tuple[dict[_Seed, _Sample], int, _Sample, _Sample] + + class AverageLearner(BaseLearner): """A naive implementation of adaptive computing of averages. @@ -49,9 +58,20 @@ class AverageLearner(BaseLearner): Number of evaluated points. """ + data: dict[_Seed, _Sample] + pending_points: set[_Seed] + + if TYPE_CHECKING: + # Keep this a writable instance attribute at runtime. + @property + def npoints(self) -> int: ... + + @npoints.setter + def npoints(self, value: int) -> None: ... + def __init__( self, - function: Callable[[int], Real], + function: Callable[[int], _Sample], atol: float | None = None, rtol: float | None = None, min_npoints: int = 2, @@ -65,28 +85,30 @@ def __init__( self.data = {} self.pending_points = set() - self.function = function # type: ignore + self.function: Callable[[int], _Sample] = function self.atol = atol self.rtol = rtol self.npoints = 0 # Cannot estimate standard deviation with fewer than 2 points. self.min_npoints = max(min_npoints, 2) - self.sum_f: Real = 0.0 - self.sum_f_sq: Real = 0.0 + self.sum_f: _Sample = 0.0 + self.sum_f_sq: _Sample = 0.0 - def new(self) -> AverageLearner: + def new(self) -> Self: """Create a copy of `~adaptive.AverageLearner` without the data.""" - return AverageLearner(self.function, self.atol, self.rtol, self.min_npoints) + return cast( + Self, AverageLearner(self.function, self.atol, self.rtol, self.min_npoints) + ) @property def n_requested(self) -> int: return self.npoints + len(self.pending_points) - def to_numpy(self): + def to_numpy(self) -> NDArray[Any]: """Data as NumPy array of size (npoints, 2) with seeds and values.""" return np.array(sorted(self.data.items())) - def to_dataframe( # type: ignore[override] + def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -126,14 +148,14 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, df: pandas.DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", seed_name: str = "seed", y_name: str = "y", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -160,7 +182,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 +199,7 @@ def ask(self, n: int, tell_pending: bool = True) -> tuple[list[int], list[Float] self.tell_pending(p) return points, loss_improvements - def tell(self, n: Int, value: Real) -> None: + def tell(self, n: _Seed, value: _Sample) -> None: if n in self.data: # The point has already been added before. return @@ -188,16 +210,17 @@ def tell(self, n: Int, value: Real) -> None: self.sum_f_sq += value**2 self.npoints += 1 - def tell_pending(self, n: int) -> None: + def tell_pending(self, n: _Seed) -> None: self.pending_points.add(n) @property - def mean(self) -> Float: + def mean(self) -> float: """The average of all values in `data`.""" - return self.sum_f / self.npoints + # Division of these real scalars produces a float or a numpy.float64. + return cast(float, self.sum_f / self.npoints) @property - def std(self) -> Float: + def std(self) -> float: """The corrected sample standard deviation of the values in `data`.""" n = self.npoints @@ -210,11 +233,9 @@ def std(self) -> Float: return sqrt(numerator / (n - 1)) @cache_latest - def loss(self, real: bool = True, *, n=None) -> Float: + def loss(self, real: bool = True, *, n: int | None = None) -> float: if n is None: n = self.npoints if real else self.n_requested - else: - n = n if min(self.npoints, n) < self.min_npoints: return np.inf standard_error = self.std / sqrt(n) @@ -225,18 +246,18 @@ def loss(self, real: bool = True, *, n=None) -> Float: rloss /= abs(mean) return max(aloss, rloss) - def _loss_improvement(self, n: int) -> Float: + def _loss_improvement(self, n: int) -> float: loss = self.loss() if np.isfinite(loss): return loss - self.loss(n=self.npoints + n) else: return np.inf - def remove_unfinished(self): + def remove_unfinished(self) -> None: """Remove uncomputed data from the learner.""" self.pending_points = set() - def plot(self): + def plot(self) -> Histogram: """Returns a histogram of the evaluated data. Returns @@ -251,13 +272,13 @@ def plot(self): vals = hv.Points(vals) return hv.operation.histogram(vals, num_bins=num_bins, dimension="y") - def _get_data(self) -> tuple[dict[int, Real], int, Real, Real]: + def _get_data(self) -> _AverageData: return (self.data, self.npoints, self.sum_f, self.sum_f_sq) - def _set_data(self, data: tuple[dict[int, Real], int, Real, Real]) -> None: + def _set_data(self, data: _AverageData) -> None: self.data, self.npoints, self.sum_f, self.sum_f_sq = data - def __getstate__(self): + def __getstate__(self) -> tuple[bytes, float, float, int, _AverageData]: return ( cloudpickle.dumps(self.function), self.atol, @@ -266,8 +287,11 @@ def __getstate__(self): self._get_data(), ) - def __setstate__(self, state): - function, atol, rtol, min_npoints, data = state - function = cloudpickle.loads(function) - self.__init__(function, atol, rtol, min_npoints) + def __setstate__( + self, state: tuple[bytes, float, float, int, _AverageData] + ) -> None: + pickled_function, atol, rtol, min_npoints, data = state + type(self).__init__( + self, cloudpickle.loads(pickled_function), atol, rtol, min_npoints + ) self._set_data(data) diff --git a/adaptive/learner/average_learner1D.py b/adaptive/learner/average_learner1D.py index 82c76f5d..095a722c 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -6,15 +6,23 @@ from collections.abc import Callable, Iterable, Sequence from copy import deepcopy from math import hypot +from typing import TYPE_CHECKING, Any, Self, TypeAlias, cast import numpy as np import scipy.stats -from sortedcollections import ItemSortedDict -from sortedcontainers import SortedDict - -from adaptive.learner.learner1D import Learner1D, _get_intervals +from numpy.typing import NDArray + +from adaptive.learner.learner1D import ( + Interval, + IntervalLoss, + ItemSortedDict, + Learner1D, + SortedDict, + _get_intervals, + _SampleData, + _StoredData, +) from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Int, Real from adaptive.utils import assign_defaults, partial_function_from_dataframe try: @@ -25,8 +33,12 @@ except ModuleNotFoundError: with_pandas = False -Point = tuple[int, Real] -Points = list[Point] +if TYPE_CHECKING: + import holoviews + +Point: TypeAlias = tuple[int, float] +Points: TypeAlias = list[Point] +ScalarIntervalLoss: TypeAlias = Callable[[Sequence[float], Sequence[float]], float] __all__: list[str] = ["AverageLearner1D"] @@ -74,19 +86,25 @@ class AverageLearner1D(Learner1D): [self.data[x] - min_error, self.data[x] + min_error]. """ + # The public sampling interface uses (seed, x) rather than x, while + # the inherited interval calculations still use the real coordinate x. + if TYPE_CHECKING: + function: Callable[[Point], float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] + pending_points: set[Point] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] + data: dict[float, float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] + def __init__( self, - function: Callable[[tuple[int, Real]], Real], - bounds: tuple[Real, Real], - loss_per_interval: None - | (Callable[[Sequence[Real], Sequence[Real]], float]) = None, + function: Callable[[Point], float], + bounds: tuple[float, float], + loss_per_interval: ScalarIntervalLoss | 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 +116,13 @@ def __init__( if min_samples > max_samples: raise ValueError("max_samples should be larger than min_samples.") - super().__init__(function, bounds, loss_per_interval) # type: ignore[arg-type] + # The shared initializer only stores the function; the loss is + # evaluated on scalar means, never on vector-valued observations. + super().__init__( + cast("Callable[[float], float]", function), + bounds, + cast("IntervalLoss | None", loss_per_interval), + ) self.delta = delta self.alpha = alpha @@ -109,34 +133,37 @@ def __init__( # Contains all samples f(x) for each # point x in the form {x0: {0: f_0(x0), 1: f_1(x0), ...}, ...} - self._data_samples: SortedDict[float, dict[int, Real]] = SortedDict() + self._data_samples: SortedDict[float, dict[int, float]] = SortedDict() # Contains the number of samples taken # at each point x in the form {x0: n0, x1: n1, ...} - self._number_samples = SortedDict() + self._number_samples: SortedDict[float, int] = SortedDict() # This set contains the points x that have less than min_samples # samples or less than a (neighbor_sampling*100)% of their neighbors - self._undersampled_points: set[Real] = set() + self._undersampled_points: set[float] = set() # Contains the error in the estimate of the # mean at each point x in the form {x0: error(x0), ...} - self.error: dict[Real, float] = decreasing_dict() + self.error = decreasing_dict() #  Distance between two neighboring points in the # form {xi: ((xii-xi)^2 + (yii-yi)^2)^0.5, ...} - self._distances: dict[Real, float] = decreasing_dict() + self._distances = decreasing_dict() # {xii: error[xii]/min(_distances[xi], _distances[xii], ...} - self.rescaled_error: ItemSortedDict[Real, float] = decreasing_dict() + self.rescaled_error = decreasing_dict() - def new(self) -> AverageLearner1D: + def new(self) -> Self: """Create a copy of `~adaptive.AverageLearner1D` without the data.""" - return AverageLearner1D( - self.function, - self.bounds, - self.loss_per_interval, # type: ignore[arg-type] - self.delta, - self.alpha, - self.neighbor_sampling, - self.min_samples, - self.max_samples, - self.min_error, + return cast( + "Self", + AverageLearner1D( + self.function, + self.bounds, + self.loss_per_interval, + self.delta, + self.alpha, + self.neighbor_sampling, + self.min_samples, + self.max_samples, + self.min_error, + ), ) @property @@ -150,7 +177,7 @@ def min_samples_per_point(self) -> int: return 0 return min(self._number_samples.values()) - def to_numpy(self, mean: bool = False) -> np.ndarray: + def to_numpy(self, mean: bool = False) -> NDArray[Any]: if mean: return super().to_numpy() else: @@ -162,7 +189,7 @@ def to_numpy(self, mean: bool = False) -> np.ndarray: ] ) - def to_dataframe( # type: ignore[override] + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, mean: bool = False, with_default_function_args: bool = True, @@ -199,11 +226,12 @@ def to_dataframe( # type: ignore[override] """ if not with_pandas: raise ImportError("pandas is not installed.") + data: list[tuple[float, float]] | list[tuple[int, float, float]] if mean: - data: list[tuple[Real, Real]] = sorted(self.data.items()) + data = sorted(self.data.items()) columns = [x_name, y_name] else: - data: list[tuple[int, Real, Real]] = [ # type: ignore[no-redef] + data = [ (seed, x, y) for x, seed_y in sorted(self._data_samples.items()) for seed, y in sorted(seed_y.items()) @@ -216,7 +244,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -224,7 +252,7 @@ def load_dataframe( # type: ignore[override] seed_name: str = "seed", x_name: str = "x", y_name: str = "y", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -250,13 +278,13 @@ def load_dataframe( # type: ignore[override] # Were using zip instead of df[[seed_name, x_name]].values because that will # make the seeds into floats seed_x = list(zip(df[seed_name].values.tolist(), df[x_name].values.tolist())) - self.tell_many(seed_x, df[y_name].values) + self.tell_many(seed_x, cast("Sequence[float]", df[y_name].values)) if with_default_function_args: self.function = partial_function_from_dataframe( self.function, df, function_prefix ) - def ask(self, n: int, tell_pending: bool = True) -> tuple[Points, list[float]]: # type: ignore[override] + def ask(self, n: int, tell_pending: bool = True) -> tuple[Points, list[float]]: # type: ignore[override] # ty: ignore[incompatible-method-override] """Return 'n' points that are expected to maximally reduce the loss.""" # If some point is undersampled, resample it if len(self._undersampled_points): @@ -285,7 +313,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,16 +339,16 @@ def _ask_for_new_point(self, n: int) -> tuple[Points, list[float]]: points, (loss_improvement,) = self._ask_points_without_adding(1) seed_points = list(zip(range(n), n * points)) loss_improvements = [loss_improvement / n] * n - return seed_points, loss_improvements # type: ignore[return-value] + return seed_points, loss_improvements - def tell_pending(self, seed_x: Point) -> None: # type: ignore[override] + def tell_pending(self, seed_x: Point) -> None: # type: ignore[override] # ty: ignore[incompatible-method-override] _, x = seed_x self.pending_points.add(seed_x) if x not in self.data: self._update_neighbors(x, self.neighbors_combined) self._update_losses(x, real=False) - def tell(self, seed_x: Point, y: Real) -> None: # type: ignore[override] + def tell(self, seed_x: Point, y: float) -> None: # type: ignore[override] # ty: ignore[incompatible-method-override] seed, x = seed_x if y is None: raise TypeError( @@ -336,7 +364,7 @@ def tell(self, seed_x: Point, y: Real) -> None: # type: ignore[override] self._update_data_structures(seed_x, y, "resampled") self.pending_points.discard(seed_x) - def _update_rescaled_error_in_mean(self, x: Real, point_type: str) -> None: + def _update_rescaled_error_in_mean(self, x: float, point_type: str) -> None: """Updates ``self.rescaled_error``. Parameters @@ -360,7 +388,7 @@ def _update_rescaled_error_in_mean(self, x: Real, point_type: str) -> None: self.rescaled_error[x_left] = self.error[x_left] / norm if x_right is None: - d_right = dists[x_left] + d_right = dists[cast(float, x_left)] else: d_right = dists[x] if x_right in self.rescaled_error: @@ -373,7 +401,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 +409,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 +477,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 +485,7 @@ def _update_distances(self, x: Real) -> None: if x_right is not None: self._distances[x] = hypot((x_right - x), (self.data[x_right] - y)) - def _update_losses_resampling(self, x: Real, real=True) -> None: + def _update_losses_resampling(self, x: float, real: bool = True) -> None: """Update all losses that depend on x, whenever the new point is a re-sampled point.""" # (x_left, x_right) are the "real" neighbors of 'x'. x_left, x_right = self._find_neighbors(x, self.neighbors) @@ -471,6 +499,8 @@ def _update_losses_resampling(self, x: Real, real=True) -> None: elif x_left is not None and x_right is not None: # 'x' happens to be in between two real points, # so we can interpolate the losses. + # Combined neighbors exist when there are real neighbors. + a, b = cast("Interval", (a, b)) dx = x_right - x_left loss = self.losses[x_left, x_right] self.losses_combined[a, x] = (x - a) * loss / dx @@ -486,13 +516,13 @@ def _update_losses_resampling(self, x: Real, real=True) -> None: if (b is not None) and right_loss_is_unknown: self.losses_combined[x, b] = float("inf") - def _calc_error_in_mean(self, ys: Iterable[Real], y_avg: Real, n: int) -> float: + def _calc_error_in_mean(self, ys: Iterable[float], y_avg: float, n: int) -> float: variance_in_mean = sum((y - y_avg) ** 2 for y in ys) / (n - 1) t_student = scipy.stats.t.ppf(1 - self.alpha, df=n - 1) return t_student * (variance_in_mean / n) ** 0.5 - def tell_many( # type: ignore[override] - self, xs: Points | np.ndarray, ys: Sequence[Real] | np.ndarray + def tell_many( # type: ignore[override] # ty: ignore[incompatible-method-override] + self, xs: Sequence[Point] | NDArray[Any], ys: Sequence[float] | NDArray[Any] ) -> None: # Check that all x are within the bounds # TODO: remove this requirement, all other learners add the data @@ -503,8 +533,9 @@ 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) + # We only assign to this inner defaultdict; the factory is not used. + mapping: defaultdict[float, dict[int, float]] = defaultdict( + lambda: cast("dict[int, float]", defaultdict(dict)) ) for (seed, x), y in zip(xs, ys): mapping[x][seed] = y @@ -519,7 +550,7 @@ def tell_many( # type: ignore[override] # simultaneously, before we move on to a new x self.tell_many_at_point(x, seed_y_mapping) - def tell_many_at_point(self, x: Real, seed_y_mapping: dict[int, Real]) -> None: + def tell_many_at_point(self, x: float, seed_y_mapping: dict[int, float]) -> None: """Tell the learner about many samples at a certain location x. Parameters @@ -574,15 +605,15 @@ def tell_many_at_point(self, x: Real, seed_y_mapping: dict[int, Real]) -> None: self._update_interpolated_loss_in_interval(*interval) self._oldscale = deepcopy(self._scale) - def _get_data(self) -> dict[Real, dict[Int, Real]]: # type: ignore[override] + def _get_data(self) -> _SampleData: return self._data_samples - def _set_data(self, data: dict[Real, dict[Int, Real]]) -> None: # type: ignore[override] + def _set_data(self, data: _StoredData) -> None: if data: - for x, samples in data.items(): + for x, samples in cast("_SampleData", data).items(): self.tell_many_at_point(x, samples) - def plot(self): + def plot(self) -> holoviews.Overlay: # type: ignore[override] # ty: ignore[incompatible-method-override] """Returns a plot of the evaluated data with error bars. This is only implemented for scalar functions, i.e., it requires ``vdim=1``. @@ -612,10 +643,10 @@ def plot(self): return p.redim(x={"range": plot_bounds}) -def decreasing_dict() -> ItemSortedDict: +def decreasing_dict() -> ItemSortedDict[float, float]: """This initialization orders the dictionary from large to small values""" - def sorting_rule(key, value): + def sorting_rule(key: float, value: float) -> float: return -value return ItemSortedDict(sorting_rule, SortedDict()) diff --git a/adaptive/learner/balancing_learner.py b/adaptive/learner/balancing_learner.py index 32f48e3c..67f7641a 100644 --- a/adaptive/learner/balancing_learner.py +++ b/adaptive/learner/balancing_learner.py @@ -6,13 +6,26 @@ from contextlib import suppress from functools import partial from operator import itemgetter -from typing import Any, Literal, TypeAlias, cast +from typing import TYPE_CHECKING, Any, Generic, Literal, Self, TypeAlias, cast from adaptive.learner.base_learner import BaseLearner, LearnerType from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Int, Real from adaptive.utils import cache_latest, named_product, restore +if TYPE_CHECKING: + from os import PathLike + from typing import Protocol, SupportsIndex + + from holoviews.core import Dimensioned, DynamicMap, HoloMap + + class _HasNSamples(Protocol): + @property + def nsamples(self) -> int: ... + + class _Plottable(Protocol): + def plot(self) -> Dimensioned: ... + + try: import pandas @@ -21,19 +34,22 @@ with_pandas = False -def dispatch(child_functions: list[Callable], arg: Any) -> Any: +def dispatch(child_functions: list[Callable[..., Any]], arg: _Point) -> Any: index, x = arg return child_functions[index](x) STRATEGY_TYPE: TypeAlias = Literal["loss_improvements", "loss", "npoints", "cycle"] -CDIMS_TYPE: TypeAlias = ( - Sequence[dict[str, Any]] | tuple[Sequence[str], Sequence[tuple[Any, ...]]] | None -) +_Point: TypeAlias = tuple[int, Any] +_NamedDimensions: TypeAlias = tuple[Sequence[str], Iterable[tuple[Any, ...]]] +CDIMS_TYPE: TypeAlias = Sequence[dict[str, Any]] | _NamedDimensions | None + +if TYPE_CHECKING: + _Filename: TypeAlias = str | PathLike[str] -class BalancingLearner(BaseLearner): +class BalancingLearner(BaseLearner, Generic[LearnerType]): r"""Choose the optimal points from a set of learners. Parameters @@ -86,7 +102,7 @@ class BalancingLearner(BaseLearner): def __init__( self, - learners: list[BaseLearner], + learners: list[LearnerType], *, cdims: CDIMS_TYPE = None, strategy: STRATEGY_TYPE = "loss_improvements", @@ -96,9 +112,9 @@ 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._ask_cache: dict[int, tuple[list[Any], list[float]]] = {} self._loss: dict[int, float] = {} self._pending_loss: dict[int, float] = {} self._cdims_default = cdims @@ -108,36 +124,39 @@ def __init__( self.strategy: STRATEGY_TYPE = strategy - def new(self) -> BalancingLearner: + def new(self) -> Self: """Create a new `BalancingLearner` with the same parameters.""" - return BalancingLearner( - [learner.new() for learner in self.learners], - cdims=self._cdims_default, - strategy=self.strategy, + return cast( + Self, + BalancingLearner( + [learner.new() for learner in self.learners], + cdims=self._cdims_default, + strategy=self.strategy, + ), ) @property - def data(self) -> dict[tuple[int, Any], Any]: # type: ignore[override] + def data(self) -> dict[_Point, Any]: data = {} for i, lrn in enumerate(self.learners): data.update({(i, p): v for p, v in lrn.data.items()}) return data @property - def pending_points(self) -> set[tuple[int, Any]]: # type: ignore[override] - pending_points = set() + def pending_points(self) -> set[_Point]: + pending_points: set[_Point] = set() for i, lrn in enumerate(self.learners): pending_points.update({(i, p) for p in lrn.pending_points}) return pending_points @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: return sum(lrn.npoints for lrn in self.learners) @property - def nsamples(self): + def nsamples(self) -> int: if hasattr(self.learners[0], "nsamples"): - return sum(lrn.nsamples for lrn in self.learners) + return sum(cast("_HasNSamples", lrn).nsamples for lrn in self.learners) else: raise AttributeError( f"{type(self.learners[0])} as no attribute called `nsamples`." @@ -174,8 +193,8 @@ def strategy(self, strategy: STRATEGY_TYPE) -> None: def _ask_and_tell_based_on_loss_improvements( self, n: int - ) -> tuple[list[tuple[int, Any]], list[float]]: - selected = [] # tuples ((learner_index, point), loss_improvement) + ) -> tuple[list[_Point], list[float]]: + selected: list[tuple[_Point, float]] = [] total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners] for _ in range(n): to_select = [] @@ -203,12 +222,8 @@ def _ask_and_tell_based_on_loss_improvements( points, loss_improvements = map(list, zip(*selected)) return points, loss_improvements - def _ask_and_tell_based_on_loss( - self, n: int - ) -> tuple[list[tuple[int, Any]], list[float]]: - selected: list[ - tuple[tuple[int, Any], float] - ] = [] # tuples ((learner_index, point), loss_improvement) + def _ask_and_tell_based_on_loss(self, n: int) -> tuple[list[_Point], list[float]]: + selected: list[tuple[_Point, float]] = [] total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners] exhausted: set[int] = set() # learners that have no point to give now while len(selected) < n and len(exhausted) < len(self.learners): @@ -240,11 +255,9 @@ def _ask_and_tell_based_on_loss( return points, loss_improvements def _ask_and_tell_based_on_npoints( - self, n: Int - ) -> tuple[list[tuple[Int, Any]], list[float]]: - selected: list[ - tuple[tuple[Int, Any], float] - ] = [] # tuples ((learner_index, point), loss_improvement) + self, n: int + ) -> tuple[list[_Point], list[float]]: + selected: list[tuple[_Point, float]] = [] total_points = [lrn.npoints + len(lrn.pending_points) for lrn in self.learners] exhausted: set[int] = set() # learners that have no point to give now while len(selected) < n and len(exhausted) < len(self.learners): @@ -268,9 +281,7 @@ def _ask_and_tell_based_on_npoints( points, loss_improvements = map(list, zip(*selected)) return points, loss_improvements - def _ask_and_tell_based_on_cycle( - self, n: int - ) -> tuple[list[tuple[Int, Any]], list[float]]: + def _ask_and_tell_based_on_cycle(self, n: int) -> tuple[list[_Point], list[float]]: points, loss_improvements = [], [] for _ in range(n): # Skip learners that have no point to give now, at most one round. @@ -289,7 +300,7 @@ def _ask_and_tell_based_on_cycle( def ask( self, n: int, tell_pending: bool = True - ) -> tuple[list[tuple[Int, Any]], list[float]]: + ) -> tuple[list[_Point], list[float]]: """Chose points for learners.""" if n == 0: return [], [] @@ -303,14 +314,14 @@ def ask( else: return self._ask_and_tell(n) - def tell(self, x: tuple[Int, Any], y: Any) -> None: + def tell(self, x: _Point, 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: _Point) -> None: index, x_ = x self._ask_cache.pop(index, None) self._loss.pop(index, None) @@ -341,9 +352,9 @@ def loss(self, real: bool = True) -> float: def plot( self, cdims: CDIMS_TYPE = None, - plotter: Callable[[BaseLearner], Any] | None = None, + plotter: Callable[[LearnerType], Dimensioned] | None = None, dynamic: bool = True, - ): + ) -> DynamicMap | HoloMap: """Returns a DynamicMap with sliders. Parameters @@ -383,26 +394,34 @@ def plot( hv = ensure_holoviews() cdims = cdims or self._cdims_default + dimensions: Sequence[dict[str, Any]] if cdims is None: - cdims = [{"i": i} for i in range(len(self.learners))] + dimensions = [{"i": i} for i in range(len(self.learners))] elif not isinstance(cdims[0], dict): # Normalize the format - keys, values_list = cdims - cdims = [dict(zip(keys, values)) for values in values_list] - cdims = cast(list[dict[str, Real]], cdims) + keys, values_list = cast(_NamedDimensions, cdims) + dimensions = [dict(zip(keys, values)) for values in values_list] + else: + dimensions = cast(Sequence[dict[str, Any]], cdims) mapping = { - tuple(_cdims.values()): lrn for lrn, _cdims in zip(self.learners, cdims) + tuple(_cdims.values()): lrn + for lrn, _cdims in zip(self.learners, dimensions) } - d = defaultdict(list) - for _cdims in cdims: + d: defaultdict[str, list[Any]] = defaultdict(list) + for _cdims in dimensions: for k, v in _cdims.items(): d[k].append(v) - def plot_function(*args): + def plot_function(*args: Any) -> Dimensioned | None: with suppress(KeyError): learner = mapping[tuple(args)] - return learner.plot() if plotter is None else plotter(learner) + return ( + cast("_Plottable", learner).plot() + if plotter is None + else plotter(learner) + ) + return None dm = hv.DynamicMap(plot_function, kdims=list(d.keys())) dm = dm.redim.values(**d) @@ -427,11 +446,11 @@ def remove_unfinished(self) -> None: @classmethod def from_product( cls, - f, - learner_type: LearnerType, + f: Callable[..., Any], + learner_type: Callable[..., LearnerType], learner_kwargs: dict[str, Any], combos: dict[str, Sequence[Any]], - ) -> BalancingLearner: + ) -> BalancingLearner[LearnerType]: """Create a `BalancingLearner` with learners of all combinations of named variables’ values. The `cdims` will be set correctly, so calling `learner.plot` will be a `holoviews.core.HoloMap` with the correct labels. @@ -474,11 +493,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( + self, index_name: str = "learner_index", **kwargs: Any + ) -> pandas.DataFrame: """Return the data as a concatenated `pandas.DataFrame` from child learners. Parameters @@ -510,9 +531,9 @@ def to_dataframe(self, index_name: str = "learner_index", **kwargs): # type: ig df = pandas.concat(dfs, axis=0, ignore_index=True) return df - def load_dataframe( # type: ignore[override] - self, df: pandas.DataFrame, index_name: str = "learner_index", **kwargs - ): + def load_dataframe( + self, df: pandas.DataFrame, index_name: str = "learner_index", **kwargs: Any + ) -> None: """Load the data from a `pandas.DataFrame` into the child learners. Parameters @@ -525,11 +546,11 @@ def load_dataframe( # type: ignore[override] Keyword arguments passed to each ``child_learner.load_dataframe(**kwargs)``. """ for i, gr in df.groupby(index_name): - self.learners[i].load_dataframe(gr, **kwargs) + self.learners[cast("SupportsIndex", i)].load_dataframe(gr, **kwargs) def save( self, - fname: Callable[[BaseLearner], str] | Sequence[str], + fname: Callable[[LearnerType], _Filename] | Iterable[_Filename], compress: bool = True, ) -> None: """Save the data of the child learners into pickle files @@ -571,7 +592,7 @@ def save( def load( self, - fname: Callable[[BaseLearner], str] | Sequence[str], + fname: Callable[[LearnerType], _Filename] | Iterable[_Filename], compress: bool = True, ) -> None: """Load the data of the child learners from pickle files @@ -600,17 +621,19 @@ def load( def _get_data(self) -> list[Any]: return [lrn._get_data() for lrn in self.learners] - def _set_data(self, data: list[Any]): + def _set_data(self, data: list[Any]) -> None: for lrn, _data in zip(self.learners, data): lrn._set_data(_data) - def __getstate__(self) -> tuple[list[BaseLearner], CDIMS_TYPE, STRATEGY_TYPE]: + def __getstate__(self) -> tuple[list[LearnerType], CDIMS_TYPE, STRATEGY_TYPE]: return ( self.learners, self._cdims_default, self.strategy, ) - def __setstate__(self, state: tuple[list[BaseLearner], CDIMS_TYPE, STRATEGY_TYPE]): + def __setstate__( + self, state: tuple[list[LearnerType], CDIMS_TYPE, STRATEGY_TYPE] + ) -> None: learners, cdims, strategy = state - self.__init__(learners, cdims=cdims, strategy=strategy) # type: ignore[misc] + type(self).__init__(self, learners, cdims=cdims, strategy=strategy) diff --git a/adaptive/learner/base_learner.py b/adaptive/learner/base_learner.py index f5ef73ec..f98d5758 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -3,7 +3,7 @@ import abc from collections.abc import Callable from contextlib import suppress -from typing import TYPE_CHECKING, Any, TypeVar +from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, Self, TypeVar, cast import cloudpickle @@ -13,7 +13,19 @@ import pandas -def uses_nth_neighbors(n: int): +_P = ParamSpec("_P") +_R_co = TypeVar("_R_co", covariant=True) + + +class _NeighborLoss(Protocol[_P, _R_co]): + nth_neighbors: int + + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R_co: ... + + +def uses_nth_neighbors( + n: int, +) -> Callable[[Callable[_P, _R_co]], _NeighborLoss[_P, _R_co]]: """Decorator to specify how many neighboring intervals the loss function uses. Wraps loss functions to indicate that they expect intervals together @@ -60,9 +72,10 @@ def uses_nth_neighbors(n: int): ... return loss """ - def _wrapped(loss_per_interval): - loss_per_interval.nth_neighbors = n - return loss_per_interval + def _wrapped(loss_per_interval: Callable[_P, _R_co]) -> _NeighborLoss[_P, _R_co]: + loss = cast("_NeighborLoss[_P, _R_co]", loss_per_interval) + loss.nth_neighbors = n + return loss return _wrapped @@ -91,22 +104,53 @@ class BaseLearner(abc.ABC): and returns a holoviews plot. """ - data: DataType - npoints: int - pending_points: set function: Callable[..., Any] - def tell(self, x, y): - """Tell the learner about a single value. + if TYPE_CHECKING: + # Subclasses can expose these through attributes or read-only properties. + # Keep runtime attribute-based subclasses working, too. + @property + def data(self) -> DataType: ... - Parameters - ---------- - x : A value from the function domain - y : A value from the function image - """ - self.tell_many([x], [y]) + @property + def pending_points(self) -> set[Any]: ... + + @property + @abc.abstractmethod + def npoints(self) -> int: ... + + # Subclasses need not use these parameter names. Keep accepting the + # historical keywords at runtime on the base implementation. + def tell(self, x: Any, y: Any, /) -> None: ... + + @abc.abstractmethod + def tell_pending(self, x: Any, /) -> None: ... + + @abc.abstractmethod + def _set_data(self, data: Any, /) -> None: ... + + else: + + def tell(self, x: Any, y: Any) -> None: + """Tell the learner about a single value. + + Parameters + ---------- + x : A value from the function domain + y : A value from the function image + """ + self.tell_many([x], [y]) + + @abc.abstractmethod + def tell_pending(self, x: Any) -> None: + """Tell the learner that 'x' has been requested such + that it's not suggested again.""" - def tell_many(self, xs, ys): + @abc.abstractmethod + def _set_data(self, data: Any) -> None: + pass + + def tell_many(self, xs: Any, ys: Any) -> None: """Tell the learner about some values. Parameters @@ -118,16 +162,11 @@ def tell_many(self, xs, ys): self.tell(x, y) @abc.abstractmethod - def tell_pending(self, x): - """Tell the learner that 'x' has been requested such - that it's not suggested again.""" - - @abc.abstractmethod - def remove_unfinished(self): + def remove_unfinished(self) -> None: """Remove uncomputed data from the learner.""" @abc.abstractmethod - def loss(self, real=True): + def loss(self, real: bool = True) -> float: """Return the loss for the current state of the learner. Parameters @@ -139,7 +178,7 @@ def loss(self, real=True): """ @abc.abstractmethod - def ask(self, n, tell_pending=True): + def ask(self, n: int, tell_pending: bool = True) -> tuple[list[Any], list[float]]: """Choose the next 'n' points to evaluate. Parameters @@ -157,15 +196,11 @@ def _get_data(self) -> Any: pass @abc.abstractmethod - def _set_data(self, data: Any) -> None: - pass - - @abc.abstractmethod - def new(self): + def new(self) -> Self: """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 +210,7 @@ def copy_from(self, other): """ self._set_data(other._get_data()) - def save(self, fname, compress=True): + def save(self, fname: Any, compress: bool = True) -> None: """Save the data of the learner into a pickle file. Parameters @@ -189,7 +224,7 @@ def save(self, fname, compress=True): data = self._get_data() save(fname, data, compress) - def load(self, fname, compress=True): + def load(self, fname: Any, compress: bool = True) -> None: """Load the data of a learner from a pickle file. Parameters @@ -204,52 +239,64 @@ def load(self, fname, compress=True): data = load(fname, compress) self._set_data(data) - @abc.abstractmethod - def to_dataframe( - self, - with_default_function_args: bool = True, - function_prefix: str = "function.", - **kwargs: Any, - ) -> pandas.DataFrame: - """Return the data as a `pandas.DataFrame`. - - Parameters - ---------- - with_default_function_args : bool, optional - Include the ``learner.function``'s default arguments as a - column, by default True - function_prefix : str, optional - Prefix to the ``learner.function``'s default arguments' names, - by default "function." - x_name : str, optional - Name of the input value, by default "x" - y_name : str, optional - Name of the output value, by default "y" - - Returns - ------- - pandas.DataFrame - """ - - @abc.abstractmethod - def load_dataframe( - self, - df: pandas.DataFrame, - with_default_function_args: bool = True, - function_prefix: str = "function.", - **kwargs: Any, - ) -> None: - """Load data from a `pandas.DataFrame`. - - If ``with_default_function_args`` is True, then ``learner.function``'s - default arguments are set (using `functools.partial`) from the values - in the `pandas.DataFrame`. - """ - - def __getstate__(self): + if TYPE_CHECKING: + # Each learner defines its own dataframe options and argument order. + @abc.abstractmethod + def to_dataframe(self, *args: Any, **kwargs: Any) -> pandas.DataFrame: ... + + @abc.abstractmethod + def load_dataframe( + self, df: pandas.DataFrame, *args: Any, **kwargs: Any + ) -> None: ... + + else: + + @abc.abstractmethod + def to_dataframe( + self, + with_default_function_args: bool = True, + function_prefix: str = "function.", + **kwargs: Any, + ) -> pandas.DataFrame: + """Return the data as a `pandas.DataFrame`. + + Parameters + ---------- + with_default_function_args : bool, optional + Include the ``learner.function``'s default arguments as a + column, by default True + function_prefix : str, optional + Prefix to the ``learner.function``'s default arguments' names, + by default "function." + x_name : str, optional + Name of the input value, by default "x" + y_name : str, optional + Name of the output value, by default "y" + + Returns + ------- + pandas.DataFrame + """ + + @abc.abstractmethod + def load_dataframe( + self, + df: pandas.DataFrame, + with_default_function_args: bool = True, + function_prefix: str = "function.", + **kwargs: Any, + ) -> None: + """Load data from a `pandas.DataFrame`. + + If ``with_default_function_args`` is True, then ``learner.function``'s + default arguments are set (using `functools.partial`) from the values + in the `pandas.DataFrame`. + """ + + def __getstate__(self) -> Any: return cloudpickle.dumps(self.__dict__) - def __setstate__(self, state): + def __setstate__(self, state: Any) -> None: self.__dict__ = cloudpickle.loads(state) diff --git a/adaptive/learner/data_saver.py b/adaptive/learner/data_saver.py index 44088e2c..e0a812c0 100644 --- a/adaptive/learner/data_saver.py +++ b/adaptive/learner/data_saver.py @@ -3,11 +3,14 @@ import functools from collections import OrderedDict from collections.abc import Callable -from typing import Any +from typing import TYPE_CHECKING, Any, Generic, Self, cast from adaptive.learner.base_learner import BaseLearner, LearnerType from adaptive.utils import copy_docstring_from +if TYPE_CHECKING: + from os import PathLike + try: import pandas @@ -17,11 +20,11 @@ with_pandas = False -def _to_key(x): +def _to_key(x: pandas.Series) -> Any: return tuple(x.values) if x.values.size > 1 else x.item() -class DataSaver(BaseLearner): +class DataSaver(BaseLearner, Generic[LearnerType]): """Save extra data associated with the values that need to be learned. Parameters @@ -41,26 +44,31 @@ class DataSaver(BaseLearner): >>> learner = DataSaver(_learner, arg_picker=itemgetter('y')) """ - def __init__(self, learner: LearnerType, arg_picker: Callable) -> None: + if TYPE_CHECKING: + # This attribute is read from the wrapped learner via __getattr__. + @property + def npoints(self) -> int: ... + + def __init__(self, learner: LearnerType, arg_picker: Callable[[Any], Any]) -> None: self.learner = learner self.extra_data: OrderedDict[Any, Any] = OrderedDict() self.function = learner.function self.arg_picker = arg_picker - def new(self) -> DataSaver: + def new(self) -> Self: """Return a new `DataSaver` with the same `arg_picker` and `learner`.""" - return DataSaver(self.learner.new(), self.arg_picker) + return cast(Self, DataSaver(self.learner.new(), self.arg_picker)) @copy_docstring_from(BaseLearner.ask) - def ask(self, *args, **kwargs): + def ask(self, *args: Any, **kwargs: Any) -> tuple[list[Any], list[float]]: return self.learner.ask(*args, **kwargs) @copy_docstring_from(BaseLearner.loss) - def loss(self, *args, **kwargs): + def loss(self, *args: Any, **kwargs: Any) -> float: return self.learner.loss(*args, **kwargs) @copy_docstring_from(BaseLearner.remove_unfinished) - def remove_unfinished(self, *args, **kwargs): + def remove_unfinished(self, *args: Any, **kwargs: Any) -> None: return self.learner.remove_unfinished(*args, **kwargs) def __getattr__(self, attr: str) -> Any: @@ -76,7 +84,7 @@ def tell(self, x: Any, result: Any) -> None: def tell_pending(self, x: Any) -> None: self.learner.tell_pending(x) - def to_dataframe( # type: ignore[override] + def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -114,14 +122,14 @@ def to_dataframe( # type: ignore[override] ] return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, df: pandas.DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", extra_data_name: str = "extra_data", input_names: tuple[str, ...] = (), - **kwargs, + **kwargs: Any, ) -> None: """Load the data from a `pandas.DataFrame` into the learner. @@ -161,37 +169,44 @@ def _set_data( learner_data, self.extra_data = data self.learner._set_data(learner_data) - def __getstate__(self) -> tuple[LearnerType, Callable, OrderedDict]: - return ( # type: ignore[return-value] + def __getstate__( + self, + ) -> tuple[LearnerType, Callable[[Any], Any], OrderedDict[Any, Any]]: + return ( self.learner, self.arg_picker, self.extra_data, ) - def __setstate__(self, state: tuple[LearnerType, Callable, OrderedDict]) -> None: + def __setstate__( + self, state: tuple[LearnerType, Callable[[Any], Any], OrderedDict[Any, Any]] + ) -> None: learner, arg_picker, extra_data = state - self.__init__(learner, arg_picker) # type: ignore[misc] + type(self).__init__(self, learner, arg_picker) self.extra_data = extra_data @copy_docstring_from(BaseLearner.save) - def save(self, fname, compress=True) -> None: - # We copy this method because the 'DataSaver' is not a - # subclass of the 'BaseLearner'. + def save(self, fname: str | PathLike[str], compress: bool = True) -> None: BaseLearner.save(self, fname, compress) @copy_docstring_from(BaseLearner.load) - def load(self, fname, compress=True) -> None: - # We copy this method because the 'DataSaver' is not a - # subclass of the 'BaseLearner'. + def load(self, fname: str | PathLike[str], compress: bool = True) -> None: BaseLearner.load(self, fname, compress) -def _ds(learner_type, arg_picker, *args, **kwargs): +def _ds( + learner_type: Callable[..., LearnerType], + arg_picker: Callable[[Any], Any], + *args: Any, + **kwargs: Any, +) -> DataSaver[LearnerType]: args = args[2:] # functools.partial passes the first 2 arguments in 'args'! return DataSaver(learner_type(*args, **kwargs), arg_picker) -def make_datasaver(learner_type, arg_picker): +def make_datasaver( + learner_type: Callable[..., LearnerType], arg_picker: Callable[[Any], Any] +) -> functools.partial[DataSaver[LearnerType]]: """Create a `DataSaver` of a `learner_type` that can be instantiated with the `learner_type`'s key-word arguments. diff --git a/adaptive/learner/integrator_coeffs.py b/adaptive/learner/integrator_coeffs.py index 862f76eb..f96654b0 100644 --- a/adaptive/learner/integrator_coeffs.py +++ b/adaptive/learner/integrator_coeffs.py @@ -4,9 +4,29 @@ from collections import defaultdict from fractions import Fraction from functools import cache +from typing import TYPE_CHECKING, cast import numpy as np import scipy.linalg +from numpy.typing import NDArray + +if TYPE_CHECKING: + # These module attributes are provided lazily by __getattr__. + eps: np.float64 + ns: tuple[int, int, int, int] + xi: list[NDArray[np.float64]] + V: list[NDArray[np.float64]] + V_inv: list[NDArray[np.float64]] + Vcond: list[float] + T_left: NDArray[np.float64] + T_right: NDArray[np.float64] + hint: float + min_sep: np.float64 + ndiv_max: int + k: NDArray[np.int_] + alpha: NDArray[np.float64] + gamma: NDArray[np.float64] + b_def: list[NDArray[np.float64]] def legendre(n: int) -> list[list[Fraction]]: @@ -30,7 +50,7 @@ def legendre(n: int) -> list[list[Fraction]]: return result -def newton(n: int) -> np.ndarray: +def newton(n: int) -> NDArray[np.float64]: """Compute the monomial coefficients of the Newton polynomial over the nodes of the n-point Clenshaw-Curtis quadrature rule. """ @@ -105,10 +125,11 @@ def scalar_product(a: list[Fraction], b: list[Fraction]) -> Fraction: c[i + j] += a[j] * bi # Calculate the definite integral from -1 to 1. - return 2 * sum(c[i] / (i + 1) for i in range(0, lc, 2)) # type: ignore[return-value] + # There is at least one term, so sum does not return its integer start value. + return cast(Fraction, 2 * sum(c[i] / (i + 1) for i in range(0, lc, 2))) -def calc_bdef(ns: tuple[int, int, int, int]) -> list[np.ndarray]: +def calc_bdef(ns: tuple[int, int, int, int]) -> list[NDArray[np.float64]]: """Calculate the decompositions of Newton polynomials (over the nodes of the n-point Clenshaw-Curtis quadrature rule) in terms of Legandre polynomials. @@ -134,7 +155,7 @@ def calc_bdef(ns: tuple[int, int, int, int]) -> list[np.ndarray]: return result -def calc_V(x: np.ndarray, n: int) -> np.ndarray: +def calc_V(x: NDArray[np.float64], n: int) -> NDArray[np.float64]: V = [np.ones(x.shape), x.copy()] for i in range(2, n): V.append((2 * i - 1) / i * x * V[-1] - (i - 1) / i * V[-2]) @@ -144,7 +165,7 @@ def calc_V(x: np.ndarray, n: int) -> np.ndarray: @cache -def _coefficients(): +def _coefficients() -> dict[str, object]: """Compute the coefficients on demand, in order to avoid doing linear algebra on import.""" eps = np.spacing(1) @@ -157,7 +178,7 @@ def _coefficients(): # Compute the Vandermonde-like matrix and its inverse. V = [calc_V(x, n) for x, n in zip(xi, ns)] - V_inv = list(map(scipy.linalg.inv, V)) + V_inv: list[NDArray[np.float64]] = list(map(scipy.linalg.inv, V)) Vcond = [ scipy.linalg.norm(a, 2) * scipy.linalg.norm(b, 2) for a, b in zip(V, V_inv) ] @@ -187,7 +208,7 @@ def _coefficients(): return locals() -def __getattr__(name): +def __getattr__(name: str) -> object: try: return _coefficients()[name] except KeyError: diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index d6ee9ef1..bf6da370 100644 --- a/adaptive/learner/integrator_learner.py +++ b/adaptive/learner/integrator_learner.py @@ -3,13 +3,14 @@ import sys from collections import defaultdict -from collections.abc import Callable +from collections.abc import Callable, Iterable, Iterator from math import sqrt from operator import attrgetter -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Protocol, Self, TypeAlias, cast import cloudpickle import numpy as np +from numpy.typing import NDArray from scipy.linalg import norm from sortedcontainers import SortedSet @@ -26,8 +27,18 @@ except ModuleNotFoundError: with_pandas = False +if TYPE_CHECKING: + from holoviews.element import Path -def _downdate(c: np.ndarray, nans: list[int], depth: int) -> np.ndarray: + class _IntervalSet(Protocol): + def __iter__(self) -> Iterator[_Interval]: ... + def add(self, value: _Interval, /) -> None: ... + def update(self, values: Iterable[_Interval], /) -> None: ... + + +def _downdate( + c: NDArray[np.float64], nans: list[int], depth: int +) -> NDArray[np.float64]: # This is algorithm 5 from the thesis of Pedro Gonnet. b = coeff.b_def[depth].copy() m = coeff.ns[depth] - 1 @@ -47,7 +58,7 @@ def _downdate(c: np.ndarray, nans: list[int], depth: int) -> np.ndarray: return c -def _zero_nans(fx: np.ndarray) -> list[int]: +def _zero_nans(fx: NDArray[np.float64]) -> list[int]: """Caution: this function modifies fx.""" nans = [] for i in range(len(fx)): @@ -57,7 +68,7 @@ def _zero_nans(fx: np.ndarray) -> list[int]: return nans -def _calc_coeffs(fx: np.ndarray, depth: int) -> np.ndarray: +def _calc_coeffs(fx: NDArray[np.float64], depth: int) -> NDArray[np.float64]: """Caution: this function modifies fx.""" nans = _zero_nans(fx) c_new = coeff.V_inv[depth] @ fx @@ -136,7 +147,7 @@ class _Interval: "removed", ] - def __init__(self, a: int | float, b: int | float, depth: int, rdepth: int) -> None: + def __init__(self, a: float, b: float, depth: int, rdepth: int) -> None: self.children: list[_Interval] = [] self.data: dict[float, float] = {} self.a = a @@ -150,10 +161,10 @@ def __init__(self, a: int | float, b: int | float, depth: int, rdepth: int) -> N self.ndiv: int self.parent: _Interval | None self.err: float - self.c: np.ndarray + self.c: NDArray[np.float64] @classmethod - def make_first(cls, a: int, b: int, depth: int = 2) -> _Interval: + def make_first(cls, a: float, b: float, depth: int = 2) -> _Interval: ival = _Interval(a, b, depth, rdepth=1) ival.ndiv = 0 ival.parent = None @@ -161,7 +172,7 @@ def make_first(cls, a: int, b: int, depth: int = 2) -> _Interval: return ival @property - def T(self) -> np.ndarray: + def T(self) -> NDArray[np.float64]: """Get the correct shift matrix. Should only be called on children of a split interval. @@ -178,7 +189,7 @@ def refinement_complete(self, depth: int) -> bool: return False return all(p in self.data for p in self.points(depth)) - def points(self, depth: int | None = None) -> np.ndarray: + def points(self, depth: int | None = None) -> NDArray[np.float64]: if depth is None: depth = self.depth a = self.a @@ -220,17 +231,17 @@ def update_heuristic_err(self, value: float) -> None: continue child.update_heuristic_err(value / 2) - def calc_err(self, c_old: np.ndarray) -> float: + def calc_err(self, c_old: NDArray[np.float64]) -> float: c_new = self.c c_diff = np.zeros(max(len(c_old), len(c_new))) c_diff[: len(c_old)] = c_old c_diff[: len(c_new)] -= c_new - c_diff = norm(c_diff) - self.err = (self.b - self.a) * c_diff + diff: float = norm(c_diff) + self.err = (self.b - self.a) * diff for child in self.children: if child.depth_complete is None: child.update_heuristic_err(self.err / 2) - return c_diff + return diff def calc_ndiv(self) -> None: assert self.parent is not None @@ -252,7 +263,7 @@ def update_ndiv_recursively(self) -> None: for child in self.children: child.update_ndiv_recursively() - def complete_process(self, depth: int) -> tuple[bool, bool] | tuple[bool, np.bool_]: + def complete_process(self, depth: int) -> tuple[bool | np.bool_, bool | np.bool_]: """Calculate the integral contribution and error from this interval, and update the done leaves of all ancestor intervals.""" assert self.depth_complete is None or self.depth_complete == depth - 1 @@ -260,7 +271,7 @@ def complete_process(self, depth: int) -> tuple[bool, bool] | tuple[bool, np.boo fx = [self.data[k] for k in self.points(depth)] self.fx = np.array(fx) - force_split = False # This may change when refining + force_split: bool | np.bool_ = False # This may change when refining first_ival = self.parent is None and depth == 2 @@ -307,11 +318,11 @@ def complete_process(self, depth: int) -> tuple[bool, bool] | tuple[bool, np.boo ival = self.parent old_leaves = set() while ival is not None: - unused_children = [ - child for child in ival.children if child.done_leaves is not None - ] - - if not all(len(child.done_leaves) for child in unused_children): # type: ignore[arg-type] + if not all( + child.done_leaves + for child in ival.children + if child.done_leaves is not None + ): break if ival.done_leaves is None: @@ -340,8 +351,28 @@ def __repr__(self) -> str: return " ".join(lst) +_Data: TypeAlias = tuple[ + list[_Interval], + dict[float, float], + set[float], + list[float], + dict[float, set[_Interval]], + set[_Interval], + _Interval, +] +_State: TypeAlias = tuple[bytes, tuple[float, float], float, _Data] + + class IntegratorLearner(BaseLearner): - def __init__(self, function: Callable, bounds: tuple[int, int], tol: float) -> None: + data: dict[float, float] + pending_points: set[float] + + def __init__( + self, + function: Callable[[float], float], + bounds: tuple[float, float], + tol: float, + ) -> None: """ Parameters ---------- @@ -375,7 +406,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 @@ -383,7 +414,7 @@ def __init__(self, function: Callable, bounds: tuple[int, int], tol: float) -> N self.data = {} self.pending_points = set() self._stack: list[float] = [] - self.x_mapping: dict[float, SortedSet] = defaultdict( + self.x_mapping: defaultdict[float, _IntervalSet] = defaultdict( lambda: SortedSet([], key=attrgetter("rdepth")) ) self.ivals: set[_Interval] = set() @@ -391,9 +422,9 @@ def __init__(self, function: Callable, bounds: tuple[int, int], tol: float) -> N self.add_ival(ival) self.first_ival = ival - def new(self) -> IntegratorLearner: - """Create a copy of `~adaptive.Learner2D` without the data.""" - return IntegratorLearner(self.function, self.bounds, self.tol) + def new(self) -> Self: + """Create a copy without the data.""" + return cast(Self, IntegratorLearner(self.function, self.bounds, self.tol)) @property def approximating_intervals(self) -> set[_Interval]: @@ -433,11 +464,13 @@ def tell(self, point: float, value: float) -> None: assert ival in self.ivals self.priority_split.append(ival) - def tell_pending(self): + # The integrator tracks pending points itself; preserve this legacy no-op + # signature, which does not accept the base method's point argument. + def tell_pending(self) -> None: # type: ignore[override] # ty: ignore[incompatible-method-override] pass def propagate_removed(self, ival: _Interval) -> None: - def _propagate_removed_down(ival): + def _propagate_removed_down(ival: _Interval) -> None: ival.removed = True self.ivals.discard(ival) @@ -489,7 +522,7 @@ def pop_from_stack(self, n: int) -> tuple[list[float], list[float]]: ] return points, loss_improvements - def remove_unfinished(self): + def remove_unfinished(self) -> None: pass def _fill_stack(self) -> list[float]: @@ -528,7 +561,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) @@ -546,7 +579,7 @@ def err(self) -> float: err = np.inf return err - def done(self): + def done(self) -> bool | np.bool_: err = self.err igral = self.igral err_excess = sum(i.err for i in self.approximating_intervals if i.removed) @@ -558,10 +591,10 @@ def done(self): ) @cache_latest - def loss(self, real=True): + def loss(self, real: bool = True) -> float: return abs(abs(self.igral) * self.tol - self.err) - def plot(self): + def plot(self) -> Path: hv = ensure_holoviews() ivals = sorted(self.ivals, key=attrgetter("a")) if not self.data: @@ -569,11 +602,11 @@ def plot(self): xs, ys = zip(*[(x, y) for ival in ivals for x, y in sorted(ival.data.items())]) return hv.Path((xs, ys)) - def to_numpy(self): + def to_numpy(self) -> NDArray[np.floating | np.integer]: """Data as NumPy array of size (npoints, 2).""" return np.array(sorted(self.data.items())) - def to_dataframe( # type: ignore[override] + def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -613,7 +646,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -642,7 +675,7 @@ def load_dataframe( # type: ignore[override] """ raise NotImplementedError - def _get_data(self): + def _get_data(self) -> _Data: # Change the defaultdict of SortedSets to a normal dict of sets. x_mapping = {k: set(v) for k, v in self.x_mapping.items()} @@ -656,7 +689,7 @@ def _get_data(self): self.first_ival, ) - def _set_data(self, data): + def _set_data(self, data: _Data) -> None: ( self.priority_split, self.data, @@ -678,7 +711,7 @@ def _set_data(self, data): for k, _set in x_mapping.items(): self.x_mapping[k].update(_set) - def __getstate__(self): + def __getstate__(self) -> _State: return ( cloudpickle.dumps(self.function), self.bounds, @@ -686,8 +719,9 @@ def __getstate__(self): self._get_data(), ) - def __setstate__(self, state): - function, bounds, tol, data = state - function = cloudpickle.loads(function) - self.__init__(function, bounds, tol) + def __setstate__(self, state: _State) -> None: + function_pickle, bounds, tol, data = state + function = cloudpickle.loads(function_pickle) + # Retain virtual dispatch for subclasses that reuse this pickle state. + cast(Any, self).__init__(function, bounds, tol) self._set_data(data) diff --git a/adaptive/learner/learner1D.py b/adaptive/learner/learner1D.py index dfc3f81c..59742183 100644 --- a/adaptive/learner/learner1D.py +++ b/adaptive/learner/learner1D.py @@ -3,20 +3,18 @@ import collections.abc import itertools import math -from collections.abc import Callable, Sequence +from collections.abc import Callable, Mapping, Sequence from copy import copy, deepcopy -from typing import Any, TypeAlias +from typing import TYPE_CHECKING, Any, Self, TypeAlias, TypeVar, cast import cloudpickle import numpy as np -from sortedcollections.recipes import ItemSortedDict -from sortedcontainers.sorteddict import SortedDict +from numpy.typing import NDArray from adaptive.learner.base_learner import BaseLearner, uses_nth_neighbors from adaptive.learner.learnerND import volume from adaptive.learner.triangulation_backend import simplex_volume_in_embedding from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Float, Int, Real from adaptive.utils import ( assign_defaults, cache_latest, @@ -32,21 +30,85 @@ with_pandas = False -# Commonly used types -Interval: TypeAlias = tuple[float, float] | tuple[float, float, int] +_Key = TypeVar("_Key") +_Value = TypeVar("_Value") + +if TYPE_CHECKING: + from collections.abc import Iterator, KeysView, MutableMapping + from typing import overload + + import holoviews + + _Default = TypeVar("_Default") + + # The sorted mapping libraries are not typed. Their classes extend dict, + # but keys() also supports indexing and slicing in sorted order. + class _SortedKeys(KeysView[_Key], Sequence[_Key]): ... + + class SortedDict(MutableMapping[_Key, _Value]): + def __init__(self, mapping: Mapping[_Key, _Value] = ...) -> None: ... + def __getitem__(self, key: _Key) -> _Value: ... + def __setitem__(self, key: _Key, value: _Value) -> None: ... + def __delitem__(self, key: _Key) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_Key]: ... + def __reversed__(self) -> Iterator[_Key]: ... + def keys(self) -> _SortedKeys[_Key]: ... + def bisect_left(self, key: _Key) -> int: ... + def index(self, key: _Key) -> int: ... + def peekitem(self, index: int = -1) -> tuple[_Key, _Value]: ... + + # Lookups can safely miss, including for absent neighbor sentinels. + @overload + def get(self, key: object, default: None = None, /) -> _Value | None: ... + @overload + def get(self, key: object, default: _Value, /) -> _Value: ... + @overload + def get(self, key: object, default: _Default, /) -> _Value | _Default: ... + def get(self, key: object, default: object = None, /) -> object: ... + + @overload + def pop(self, key: _Key, /) -> _Value: ... + @overload + def pop(self, key: object, default: _Value, /) -> _Value: ... + @overload + def pop(self, key: object, default: _Default, /) -> _Value | _Default: ... + def pop(self, key: object, default: object = ..., /) -> object: ... + + class ItemSortedDict(SortedDict[_Key, _Value]): + def __init__( + self, + key: Callable[[_Key, _Value], object], + mapping: Mapping[_Key, _Value] = ..., + ) -> None: ... +else: + from sortedcollections.recipes import ItemSortedDict + from sortedcontainers.sorteddict import SortedDict + +Interval: TypeAlias = tuple[float, float] +_Qual: TypeAlias = tuple[float, float, int] +_IntervalKey = TypeVar("_IntervalKey", bound=Interval | _Qual) NeighborsType: TypeAlias = SortedDict[float, list[float | None]] -# Types for loss_per_interval functions -XsType0: TypeAlias = tuple[float, float] -YsType0: TypeAlias = tuple[float, float] | tuple[np.ndarray, np.ndarray] -XsType1: TypeAlias = tuple[float | None, float | None, float | None, float | None] -YsType1: TypeAlias = ( - tuple[float | None, float | None, float | None, float | None] - | tuple[np.ndarray | None, np.ndarray | None, np.ndarray | None, np.ndarray | None] -) -XsTypeN: TypeAlias = tuple[float | None, ...] -YsTypeN: TypeAlias = tuple[float | None, ...] | tuple[np.ndarray | None, ...] +_ScaledValue: TypeAlias = float | NDArray[Any] +# The bulk tell path can store user-supplied sequences without conversion. +Value: TypeAlias = _ScaledValue | Sequence[float] +IntervalLoss: TypeAlias = Callable[[Sequence[float], Sequence[_ScaledValue]], float] +NeighborLoss: TypeAlias = Callable[ + [Sequence[float | None], Sequence[_ScaledValue | None]], float +] +# AverageLearner1D uses the same pickle layout with samples in the data slot. +_SampleData: TypeAlias = Mapping[float, dict[int, float]] +_StoredData: TypeAlias = Mapping[float, Value] | _SampleData +_PickleState: TypeAlias = tuple[ + bytes, + tuple[float, ...], + IntervalLoss, + dict[Interval, float], + dict[Interval, float], + _StoredData, +] __all__ = [ "uniform_loss", @@ -60,7 +122,7 @@ @uses_nth_neighbors(0) -def uniform_loss(xs: XsType0, ys: YsType0) -> Float: +def uniform_loss(xs: Sequence[float], ys: Sequence[Value]) -> float: """Loss function that samples the domain uniformly. Works with `~adaptive.Learner1D` only. @@ -80,7 +142,7 @@ def uniform_loss(xs: XsType0, ys: YsType0) -> Float: @uses_nth_neighbors(0) -def default_loss(xs: XsType0, ys: YsType0) -> Float: +def default_loss(xs: Sequence[float], ys: Sequence[Value]) -> float: """Calculate loss on a single interval. Currently returns the rescaled length of the interval. If one of the @@ -89,42 +151,48 @@ def default_loss(xs: XsType0, ys: YsType0) -> Float: """ dx = xs[1] - xs[0] if isinstance(ys[0], collections.abc.Iterable): - dy_vec = np.array([abs(a - b) for a, b in zip(*ys)]) + vectors = cast("Sequence[Sequence[float]]", ys) + dy_vec = np.array([abs(a - b) for a, b in zip(*vectors)]) return np.hypot(dx, dy_vec).max() else: - dy = ys[1] - ys[0] + scalars = cast("Sequence[float]", ys) + dy = scalars[1] - scalars[0] return np.hypot(dx, dy) @uses_nth_neighbors(0) -def abs_min_log_loss(xs: XsType0, ys: YsType0) -> Float: +def abs_min_log_loss(xs: Sequence[float], ys: Sequence[Value]) -> float: """Calculate loss of a single interval that prioritizes the absolute minimum.""" - ys_log: YsType0 = tuple(np.log(np.abs(y).min()) for y in ys) # type: ignore[assignment] + ys_log = tuple(np.log(np.abs(y).min()) for y in ys) return default_loss(xs, ys_log) @uses_nth_neighbors(1) -def triangle_loss(xs: XsType1, ys: YsType1) -> Float: +def triangle_loss(xs: Sequence[float | None], ys: Sequence[Value | None]) -> float: assert len(xs) == 4 x = [x for x in xs if x is not None] y = [y for y in ys if y is not None] if len(x) == 2: # we do not have enough points for a triangle - return x[1] - x[0] # type: ignore[operator] + return x[1] - x[0] N = len(x) - 2 # number of constructed triangles + pts: list[tuple[float, ...]] + vol: Callable[[Sequence[tuple[float, ...]]], float] if isinstance(y[0], collections.abc.Iterable): - pts = [(x, *y) for x, y in zip(x, y)] # type: ignore[misc] + vectors = cast("Sequence[Sequence[float]]", y) + pts = [(x, *v) for x, v in zip(x, vectors)] vol = simplex_volume_in_embedding else: - pts = list(zip(x, y)) + scalars = cast("Sequence[float]", y) + pts = list(zip(x, scalars)) vol = volume return sum(vol(pts[i : i + 3]) for i in range(N)) / N def resolution_loss_function( - min_length: Real = 0, max_length: Real = 1 -) -> Callable[[XsType0, YsType0], Float]: + min_length: float = 0, max_length: float = 1 +) -> IntervalLoss: """Loss function that is similar to the `default_loss` function, but you can set the maximum and minimum size of an interval. @@ -147,7 +215,7 @@ def resolution_loss_function( """ @uses_nth_neighbors(0) - def resolution_loss(xs: XsType0, ys: YsType0) -> Float: + def resolution_loss(xs: Sequence[float], ys: Sequence[Value]) -> float: loss = uniform_loss(xs, ys) if loss < min_length: # Return zero such that this interval won't be chosen again @@ -162,17 +230,18 @@ def resolution_loss(xs: XsType0, ys: YsType0) -> Float: def curvature_loss_function( - area_factor: Real = 1, euclid_factor: Real = 0.02, horizontal_factor: Real = 0.02 -) -> Callable[[XsType1, YsType1], Float]: + area_factor: float = 1, euclid_factor: float = 0.02, horizontal_factor: float = 0.02 +) -> NeighborLoss: # XXX: add a doc-string @uses_nth_neighbors(1) - def curvature_loss(xs: XsType1, ys: YsType1) -> Float: - xs_middle = xs[1:3] - ys_middle = ys[1:3] + def curvature_loss(xs: Sequence[float | None], ys: Sequence[Value | None]) -> float: + # Only the outside neighbors can be missing. + xs_middle = cast("Sequence[float]", xs[1:3]) + ys_middle = cast("Sequence[Value]", ys[1:3]) triangle_loss_ = triangle_loss(xs, ys) default_loss_ = default_loss(xs_middle, ys_middle) - dx = xs_middle[1] - xs_middle[0] # type: ignore[operator] + dx = xs_middle[1] - xs_middle[0] return ( area_factor * (triangle_loss_**0.5) + euclid_factor * default_loss_ @@ -182,7 +251,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 +263,7 @@ def linspace(x_left: Real, x_right: Real, n: Int) -> list[Float]: return [x_left + step * i for i in range(1, n)] -def _get_neighbors_from_array(xs: np.ndarray) -> NeighborsType: +def _get_neighbors_from_array(xs: NDArray[Any]) -> NeighborsType: xs = np.sort(xs) xs_left = np.roll(xs, 1).tolist() xs_right = np.roll(xs, -1).tolist() @@ -259,30 +328,27 @@ class Learner1D(BaseLearner): decorator for more information. """ + data: dict[float, Value] + pending_points: set[float] + def __init__( self, - function: Callable[[Real], Float | np.ndarray], - bounds: tuple[Real, Real], - loss_per_interval: Callable[[XsTypeN, YsTypeN], Float] | None = None, - ): - self.function = function # type: ignore - - if loss_per_interval is not None and hasattr( - loss_per_interval, "nth_neighbors" - ): - self.nth_neighbors = loss_per_interval.nth_neighbors - else: - self.nth_neighbors = 0 + function: Callable[[float], Value], + bounds: tuple[float, float], + loss_per_interval: IntervalLoss | None = None, + ) -> None: + self.function: Callable[[float], Value] = function + self.nth_neighbors: int = getattr(loss_per_interval, "nth_neighbors", 0) - self.loss_per_interval = loss_per_interval or default_loss + self.loss_per_interval: IntervalLoss = loss_per_interval or default_loss # When the scale changes by a factor 2, the losses are # recomputed. This is tunable such that we can test # the learners behavior in the tests. self._recompute_losses_factor = 2 - self.data: dict[Real, Real] = {} - self.pending_points: set[Real] = set() + self.data = {} + self.pending_points = set() # A dict {x_n: [x_{n-1}, x_{n+1}]} for quick checking of local # properties. @@ -290,15 +356,17 @@ def __init__( self.neighbors_combined: NeighborsType = SortedDict() # Bounding box [[minx, maxx], [miny, maxy]]. - self._bbox = [list(bounds), [np.inf, -np.inf]] + self._bbox: list[list[_ScaledValue]] = [list(bounds), [np.inf, -np.inf]] # Data scale (maxx - minx), (maxy - miny) self._scale = [bounds[1] - bounds[0], 0] self._oldscale = deepcopy(self._scale) # A LossManager storing the loss function for each interval x_n. - self.losses = loss_manager(self._scale[0]) - self.losses_combined = loss_manager(self._scale[0]) + self.losses: ItemSortedDict[Interval, float] = loss_manager(self._scale[0]) + self.losses_combined: ItemSortedDict[Interval, float] = loss_manager( + self._scale[0] + ) # The precision in 'x' below which we set losses to 0. self._dx_eps = 2 * max(np.abs(bounds)) * np.finfo(float).eps @@ -308,9 +376,11 @@ def __init__( self._vdim: int | None = None - def new(self) -> Learner1D: + def new(self) -> Self: """Create a copy of `~adaptive.Learner1D` without the data.""" - return Learner1D(self.function, self.bounds, self.loss_per_interval) + return cast( + "Self", Learner1D(self.function, self.bounds, self.loss_per_interval) + ) @property def vdim(self) -> int: @@ -332,13 +402,13 @@ def vdim(self) -> int: return 1 return self._vdim - def to_numpy(self): + def to_numpy(self) -> NDArray[Any]: """Data as NumPy array of size ``(npoints, 2)`` if ``learner.function`` returns a scalar and ``(npoints, 1+vdim)`` if ``learner.function`` returns a vector of length ``vdim``. """ return np.array([(x, *np.atleast_1d(y)) for x, y in sorted(self.data.items())]) - def to_dataframe( # type: ignore[override] + def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -380,7 +450,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -408,14 +478,17 @@ def load_dataframe( # type: ignore[override] y_name : str, optional The ``y_name`` used in ``to_dataframe``, by default "y" """ - self.tell_many(df[x_name].values, df[y_name].values) + self.tell_many( + cast("Sequence[float]", df[x_name].values), + cast("Sequence[Value]", df[y_name].values), + ) if with_default_function_args: self.function = partial_function_from_dataframe( self.function, df, function_prefix ) @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) @@ -435,16 +508,18 @@ def loss(self, real: bool = True) -> float: max_interval, max_loss = losses.peekitem(0) return max_loss - def _scale_x(self, x: Float | None) -> Float | None: + def _scale_x(self, x: float | None) -> float | None: if x is None: return None return x / self._scale[0] - def _scale_y(self, y: Float | np.ndarray | None) -> Float | np.ndarray | None: + def _scale_y(self, y: Value | None) -> _ScaledValue | None: if y is None: return None y_scale = self._scale[1] or 1 - return y / y_scale + # The NumPy scale handles reflected division for raw sequences + # stored by tell_many; single tells already normalize them to arrays. + return cast("_ScaledValue", y) / y_scale def _get_point_by_index(self, ind: int) -> float | None: if ind < 0 or ind >= len(self.neighbors): @@ -463,16 +538,19 @@ 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] + # The key lookup misses for an absent neighbor, represented by None. + ys = [self.data.get(cast(float, x), None) for x in xs] xs_scaled = tuple(self._scale_x(x) for x in xs) ys_scaled = tuple(self._scale_y(y) for y in ys) - # we need to compute the loss for this interval - return self.loss_per_interval(xs_scaled, ys_scaled) + # The loss's nth_neighbors metadata determines whether the tuples + # include optional neighboring points, or just the interval itself. + loss = cast("NeighborLoss", self.loss_per_interval) + return loss(xs_scaled, ys_scaled) def _update_interpolated_loss_in_interval( - self, x_left: float, x_right: float + self, x_left: float | None, x_right: float | None ) -> None: if x_left is None or x_right is None: return @@ -485,7 +563,7 @@ def _update_interpolated_loss_in_interval( a, b = x_left, None dx = x_right - x_left while b != x_right: - b = self.neighbors_combined[a][1] + b = cast(float, self.neighbors_combined[a][1]) self.losses_combined[a, b] = (b - a) * loss / dx a = b @@ -499,7 +577,7 @@ def _update_losses(self, x: float, real: bool = True) -> None: a, b = self._find_neighbors(x, self.neighbors_combined) # (a, b) is splitted into (a, x) and (x, b) so if (a, b) exists - self.losses_combined.pop((a, b), None) # we get rid of (a, b). + self.losses_combined.pop((a, b), None) if real: # We need to update all interpolated losses in the interval @@ -511,11 +589,14 @@ def _update_losses(self, x: float, real: bool = True) -> None: # Since 'x' is in between (x_left, x_right), # we get rid of the interval. - self.losses.pop((x_left, x_right), None) - self.losses_combined.pop((x_left, x_right), None) + old_interval = (x_left, x_right) + self.losses.pop(old_interval, None) + self.losses_combined.pop(old_interval, None) elif x_left is not None and x_right is not None: # 'x' happens to be in between two real points, # so we can interpolate the losses. + # Combined neighbors exist when there are real neighbors. + a, b = cast("Interval", (a, b)) dx = x_right - x_left loss = self.losses[x_left, x_right] self.losses_combined[a, x] = (x - a) * loss / dx @@ -532,7 +613,7 @@ def _update_losses(self, x: float, real: bool = True) -> None: self.losses_combined[x, b] = float("inf") @staticmethod - def _find_neighbors(x: float, neighbors: NeighborsType) -> Any: + def _find_neighbors(x: float, neighbors: NeighborsType) -> Sequence[float | None]: if x in neighbors: return neighbors[x] pos = neighbors.bisect_left(x) @@ -545,10 +626,12 @@ def _update_neighbors(self, x: float, neighbors: NeighborsType) -> None: if x not in neighbors: # The point is new x_left, x_right = self._find_neighbors(x, neighbors) neighbors[x] = [x_left, x_right] - neighbors.get(x_left, [None, None])[1] = x - neighbors.get(x_right, [None, None])[0] = x + left: list[float | None] = neighbors.get(x_left, [None, None]) + left[1] = x + right: list[float | None] = neighbors.get(x_right, [None, None]) + right[0] = x - def _update_scale(self, x: float, y: Float | np.ndarray) -> None: + def _update_scale(self, x: float, y: _ScaledValue) -> None: """Update the scale with which the x and y-values are scaled. For a learner where the function returns a single scalar the scale @@ -557,11 +640,14 @@ def _update_scale(self, x: float, y: Float | np.ndarray) -> None: When the function returns a vector the learners y-scale is set by the level with the the largest peak-to-peak value. """ - self._bbox[0][0] = min(self._bbox[0][0], x) - self._bbox[0][1] = max(self._bbox[0][1], x) - self._scale[0] = self._bbox[0][1] - self._bbox[0][0] + x_bounds = cast("list[float]", self._bbox[0]) + x_bounds[0] = min(x_bounds[0], x) + x_bounds[1] = max(x_bounds[1], x) + self._scale[0] = x_bounds[1] - x_bounds[0] if y is not None: if self.vdim > 1: + y_min: _ScaledValue + y_max: _ScaledValue try: y_min = np.nanmin([self._bbox[1][0], y], axis=0) y_max = np.nanmax([self._bbox[1][1], y], axis=0) @@ -571,11 +657,14 @@ def _update_scale(self, x: float, y: Float | np.ndarray) -> None: self._bbox[1] = [y_min, y_max] self._scale[1] = np.max(y_max - y_min) else: - self._bbox[1][0] = min(self._bbox[1][0], y) - self._bbox[1][1] = max(self._bbox[1][1], y) - self._scale[1] = self._bbox[1][1] - self._bbox[1][0] - - def tell(self, x: float, y: Float | Sequence[Float] | np.ndarray) -> None: + # Zero-dimensional and length-one arrays act as scalars here. + y_bounds = cast("list[float]", self._bbox[1]) + scalar = cast(float, y) + y_bounds[0] = min(y_bounds[0], scalar) + y_bounds[1] = max(y_bounds[1], scalar) + self._scale[1] = y_bounds[1] - y_bounds[0] + + def tell(self, x: float, y: Value) -> None: if x in self.data: # The point is already evaluated before return @@ -620,13 +709,8 @@ def tell_pending(self, x: float) -> None: def tell_many( self, - xs: Sequence[Float] | np.ndarray, - ys: ( - Sequence[Float] - | Sequence[Sequence[Float]] - | Sequence[np.ndarray] - | np.ndarray - ), + xs: Sequence[float] | NDArray[Any], + ys: Sequence[Value] | NDArray[Any], *, force: bool = False, ) -> None: @@ -655,13 +739,14 @@ def tell_many( # Update scale self._bbox[0] = [points_combined.min(), points_combined.max()] self._bbox[1] = [values.min(axis=0), values.max(axis=0)] - self._scale[0] = self._bbox[0][1] - self._bbox[0][0] + x_bounds = cast("list[float]", self._bbox[0]) + self._scale[0] = x_bounds[1] - x_bounds[0] self._scale[1] = np.max(self._bbox[1][1] - self._bbox[1][0]) self._oldscale = deepcopy(self._scale) # Find the intervals for which the losses should be calculated. intervals, intervals_combined = ( - [(x_m, x_r) for x_m, (x_l, x_r) in neighbors.items()][:-1] + [(x_m, cast(float, x_r)) for x_m, (_, x_r) in neighbors.items()][:-1] for neighbors in (self.neighbors, self.neighbors_combined) ) @@ -671,7 +756,7 @@ def tell_many( self.losses[ival] = self._get_loss_in_interval(*ival) # List with "real" intervals that have interpolated intervals inside - to_interpolate: list[tuple[Real, Real]] = [] + to_interpolate: list[Interval] = [] self.losses_combined = loss_manager(self._scale[0]) for ival in intervals_combined: @@ -685,7 +770,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 +792,7 @@ def ask(self, n: int, tell_pending: bool = True) -> tuple[list[float], list[floa return points, loss_improvements - def _missing_bounds(self) -> list[Real]: + def _missing_bounds(self) -> list[float]: missing_bounds = [] for b in copy(self.__missing_bounds): if b in self.data: @@ -741,7 +826,7 @@ def _ask_points_without_adding(self, n: int) -> tuple[list[float], list[float]]: a, b = self.bounds return np.linspace(a, b, n).tolist(), [np.inf] * n - quals = loss_manager(self._scale[0]) + quals: ItemSortedDict[_Qual, float] = loss_manager(self._scale[0]) if len(missing_bounds) > 0: # There is at least one point in between the bounds. all_points = list(self.data.keys()) + list(self.pending_points) @@ -772,8 +857,8 @@ def _ask_points_without_adding(self, n: int) -> tuple[list[float], list[float]]: quals[(ival[0], ival[1], 2)] = loss_ival / 2 else: quals.pop(qual, None) - *xs, n = qual - quals[(*xs, n + 1)] = loss_qual * n / (n + 1) + x_l, x_r, n = qual + quals[x_l, x_r, n + 1] = loss_qual * n / (n + 1) points = list( itertools.chain.from_iterable( @@ -794,12 +879,12 @@ def _ask_points_without_adding(self, n: int) -> tuple[list[float], list[float]]: return points, loss_improvements def _loss( - self, mapping: dict[Interval, float], ival: Interval - ) -> tuple[float, Interval]: + self, mapping: Mapping[_IntervalKey, float], ival: _IntervalKey + ) -> tuple[float, Interval | _Qual]: loss = mapping[ival] return finite_loss(ival, loss, self._scale[0]) - def plot(self, *, scatter_or_line: str = "scatter"): + def plot(self, *, scatter_or_line: str = "scatter") -> holoviews.Overlay: """Returns a plot of the evaluated data. Parameters @@ -839,15 +924,17 @@ def remove_unfinished(self) -> None: self.losses_combined = deepcopy(self.losses) self.neighbors_combined = deepcopy(self.neighbors) - def _get_data(self) -> dict[float, float]: + def _get_data(self) -> _StoredData: return self.data - def _set_data(self, data: dict[float, float]) -> None: + def _set_data(self, data: _StoredData) -> None: if data: - xs, ys = zip(*data.items()) + # Each learner restores only its own representation of the data. + values = cast("Mapping[float, Value]", data) + xs, ys = zip(*values.items()) self.tell_many(xs, ys) - def __getstate__(self): + def __getstate__(self) -> _PickleState: return ( cloudpickle.dumps(self.function), tuple(self.bounds), @@ -857,25 +944,28 @@ def __getstate__(self): self._get_data(), ) - def __setstate__(self, state): - function, bounds, loss_per_interval, losses, losses_combined, data = state - function = cloudpickle.loads(function) - self.__init__(function, bounds, loss_per_interval) + def __setstate__(self, state: _PickleState) -> None: + function_bytes, bounds, loss_per_interval, losses, losses_combined, data = state + function = cloudpickle.loads(function_bytes) + # Retain virtual dispatch for AverageLearner1D and other subclasses. + cast(Any, self).__init__(function, bounds, loss_per_interval) self._set_data(data) self.losses.update(losses) self.losses_combined.update(losses_combined) -def loss_manager(x_scale: float) -> ItemSortedDict[Interval, float]: - def sort_key(ival, loss): - loss, ival = finite_loss(ival, loss, x_scale) - return -loss, ival +def loss_manager(x_scale: float) -> ItemSortedDict[_IntervalKey, float]: + def sort_key(ival: _IntervalKey, loss: float) -> tuple[float, Interval | _Qual]: + finite, key = finite_loss(ival, loss, x_scale) + return -finite, key sorted_dict = ItemSortedDict(sort_key) return sorted_dict -def finite_loss(ival: Interval, loss: float, x_scale: float) -> tuple[float, Interval]: +def finite_loss( + ival: Interval | _Qual, loss: float, x_scale: float +) -> tuple[float, Interval | _Qual]: """Get the so-called finite_loss of an interval in order to be able to sort intervals that have infinite loss.""" # If the loss is infinite we return the @@ -885,7 +975,7 @@ def finite_loss(ival: Interval, loss: float, x_scale: float) -> tuple[float, Int if len(ival) == 3: # Used when constructing quals. Last item is # the number of points inside the qual. - loss /= ival[2] # type: ignore[misc] + loss /= ival[2] # We round the loss to 12 digits such that losses # are equal up to numerical precision will be considered diff --git a/adaptive/learner/learner2D.py b/adaptive/learner/learner2D.py index 40c267a0..859f0006 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -3,19 +3,21 @@ import itertools import warnings from collections import OrderedDict -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Sequence, Sized from copy import copy from math import sqrt +from typing import TYPE_CHECKING, Any, Protocol, Self, TypeAlias, cast import cloudpickle import numpy as np +from numpy.typing import ArrayLike, NDArray from scipy import interpolate from scipy.interpolate import CloughTocher2DInterpolator, LinearNDInterpolator +from scipy.spatial import Delaunay from adaptive.learner.base_learner import BaseLearner from adaptive.learner.triangulation_backend import simplex_volume_in_embedding from adaptive.notebook_integration import ensure_holoviews -from adaptive.types import Bool, Float, Real from adaptive.utils import ( assign_defaults, cache_latest, @@ -30,10 +32,55 @@ except ModuleNotFoundError: with_pandas = False +_Point: TypeAlias = tuple[float, float] +_PointInput: TypeAlias = ( + Sequence[float | np.floating | np.integer] | NDArray[np.floating | np.integer] +) +_Value: TypeAlias = ( + float + | np.floating + | np.integer + | Iterable[float] + | NDArray[np.floating | np.integer] +) +_TriangleLoss: TypeAlias = Callable[ + [LinearNDInterpolator], NDArray[np.float64] | list[float] +] +_State: TypeAlias = tuple[ + bytes, + tuple[_Point, _Point], + _TriangleLoss, + OrderedDict[_Point, float], + dict[_Point, _Value], +] + +if TYPE_CHECKING: + from holoviews.core import HoloMap, Overlay + + # The SciPy interpolators expose these attributes at runtime but do not + # document them as part of their public interface. + class _TriangulationData(Protocol): + points: NDArray[np.float64] + simplices: NDArray[np.int32] + neighbors: NDArray[np.int32] + + class _LinearInterpolatorData(Protocol): + tri: _TriangulationData + values: NDArray[np.float64] + + def __call__(self, *coords: NDArray[np.float64]) -> NDArray[np.float64]: ... + + class _CloughTocherData(Protocol): + grad: NDArray[np.float64] + + class _HasMax(Protocol): + def max(self) -> float: ... + + # Learner2D and helper functions. -def deviations(ip: LinearNDInterpolator) -> np.ndarray: +def deviations(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Returns the deviation of the linear estimate. Is useful when defining custom loss functions. @@ -47,11 +94,13 @@ def deviations(ip: LinearNDInterpolator) -> np.ndarray: deviations : numpy.ndarray The deviation per triangle. """ - values = ip.values / (np.ptp(ip.values, axis=0).max() or 1) - gradients = CloughTocher2DInterpolator(ip.tri, values, tol=1e-6).grad + interp = cast("_LinearInterpolatorData", ip) + values = interp.values / (np.max(np.ptp(interp.values, axis=0)) or 1) + cubic = CloughTocher2DInterpolator(cast(Delaunay, interp.tri), values, tol=1e-6) + gradients = cast("_CloughTocherData", cubic).grad - simplices = ip.tri.simplices - p = ip.tri.points[simplices] + simplices = interp.tri.simplices + p = interp.tri.points[simplices] vs = values[simplices] gs = gradients[simplices] @@ -65,7 +114,7 @@ def deviations(ip: LinearNDInterpolator) -> np.ndarray: return np.swapaxes(devs, 0, 1) -def areas(ip: LinearNDInterpolator) -> np.ndarray: +def areas(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Returns the area per triangle of the triangulation inside a `LinearNDInterpolator` instance. @@ -80,13 +129,14 @@ def areas(ip: LinearNDInterpolator) -> np.ndarray: areas : numpy.ndarray The area per triangle in ``ip.tri``. """ - p = ip.tri.points[ip.tri.simplices] + tri = cast("_LinearInterpolatorData", ip).tri + p = tri.points[tri.simplices] q = p[:, :-1, :] - p[:, -1, None, :] areas = abs(q[:, 0, 0] * q[:, 1, 1] - q[:, 0, 1] * q[:, 1, 0]) / 2 return areas -def uniform_loss(ip: LinearNDInterpolator) -> np.ndarray: +def uniform_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Loss function that samples the domain uniformly. Works with `~adaptive.Learner2D` only. @@ -119,7 +169,7 @@ def uniform_loss(ip: LinearNDInterpolator) -> np.ndarray: def resolution_loss_function( min_distance: float = 0, max_distance: float = 1 -) -> Callable[[LinearNDInterpolator], np.ndarray]: +) -> Callable[[LinearNDInterpolator], NDArray[np.float64]]: """Loss function that is similar to the `default_loss` function, but you can set the maximimum and minimum size of a triangle. @@ -142,7 +192,7 @@ def resolution_loss_function( >>> learner = adaptive.Learner2D(f, bounds=[(-1, -1), (1, 1)], loss_per_triangle=loss) """ - def resolution_loss(ip): + def resolution_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: loss = default_loss(ip) A = areas(ip) @@ -158,7 +208,7 @@ def resolution_loss(ip): return resolution_loss -def minimize_triangle_surface_loss(ip: LinearNDInterpolator) -> np.ndarray: +def minimize_triangle_surface_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Loss function that is similar to the distance loss function in the `~adaptive.Learner1D`. The loss is the area spanned by the 3D vectors of the vertices. @@ -185,12 +235,15 @@ def minimize_triangle_surface_loss(ip: LinearNDInterpolator) -> np.ndarray: ... loss_per_triangle=minimize_triangle_surface_loss) >>> """ - tri = ip.tri + interp = cast("_LinearInterpolatorData", ip) + tri = interp.tri points = tri.points[tri.simplices] - values = ip.values[tri.simplices] - values = values / (np.ptp(ip.values, axis=0).max() or 1) + values = interp.values[tri.simplices] + values = values / (np.max(np.ptp(interp.values, axis=0)) or 1) - def _get_vectors(points): + def _get_vectors( + points: NDArray[np.float64], + ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: delta = points - points[:, -1, :][:, None, :] vectors = delta[:, :2, :] return vectors[:, 0, :], vectors[:, 1, :] @@ -204,7 +257,7 @@ def _get_vectors(points): return np.linalg.norm(np.cross(a, b) / 2, axis=1) -def default_loss(ip: LinearNDInterpolator) -> np.ndarray: +def default_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Loss function that combines `deviations` and `areas` of the triangles. Works with `~adaptive.Learner2D` only. @@ -228,7 +281,7 @@ def thresholded_loss_function( lower_threshold: float | None = None, upper_threshold: float | None = None, priority_factor: float = 0.1, -) -> Callable[[LinearNDInterpolator], np.ndarray]: +) -> Callable[[LinearNDInterpolator], NDArray[np.float64]]: """ Factory function to create a custom loss function that deprioritizes values above an upper threshold and below a lower threshold. @@ -251,7 +304,7 @@ def thresholded_loss_function( A custom loss function that can be used with Learner2D. """ - def custom_loss(ip: LinearNDInterpolator) -> np.ndarray: + def custom_loss(ip: LinearNDInterpolator) -> NDArray[np.float64]: """Loss function that deprioritizes values outside an upper and lower threshold. Parameters @@ -266,8 +319,9 @@ def custom_loss(ip: LinearNDInterpolator) -> np.ndarray: losses = default_loss(ip) if lower_threshold is not None or upper_threshold is not None: - simplices = ip.tri.simplices - values = ip.values[simplices] + interp = cast("_LinearInterpolatorData", ip) + simplices = interp.tri.simplices + values = interp.values[simplices] if lower_threshold is not None: mask_lower = (values < lower_threshold).all(axis=(1, -1)) if mask_lower.any(): @@ -283,11 +337,15 @@ def custom_loss(ip: LinearNDInterpolator) -> np.ndarray: return custom_loss -def _cross_2d(x, y): +def _cross_2d( + x: NDArray[np.float64], y: NDArray[np.float64] +) -> NDArray[np.float64] | np.float64: return x[..., 0] * y[..., 1] - x[..., 1] * y[..., 0] -def choose_point_in_triangle(triangle: np.ndarray, max_badness: int) -> np.ndarray: +def choose_point_in_triangle( + triangle: NDArray[np.float64], max_badness: int +) -> NDArray[np.float64]: """Choose a new point in inside a triangle. If the ratio of the longest edge of the triangle squared @@ -313,7 +371,7 @@ def choose_point_in_triangle(triangle: np.ndarray, max_badness: int) -> np.ndarr area = 0.5 * _cross_2d(b - a, c - a) triangle_roll = np.roll(triangle, 1, axis=0) edge_lengths = np.linalg.norm(triangle - triangle_roll, axis=1) - i = edge_lengths.argmax() + i = np.argmax(edge_lengths) # We multiply by sqrt(3) / 4 such that a equilateral triangle has badness=1 badness = (edge_lengths[i] ** 2 / area) * (sqrt(3) / 4) @@ -324,7 +382,7 @@ def choose_point_in_triangle(triangle: np.ndarray, max_badness: int) -> np.ndarr return point -def triangle_loss(ip): +def triangle_loss(ip: LinearNDInterpolator) -> list[float]: r"""Computes the average of the volumes of the simplex combined with each neighbouring point. @@ -343,18 +401,19 @@ def triangle_loss(ip): same result as the `adaptive.LearnerND`\s `~adaptive.learner.learnerND.triangle_loss`. """ - tri = ip.tri + interp = cast("_LinearInterpolatorData", ip) + tri = interp.tri - def get_neighbors(i, ip): + def get_neighbors(i: int, ip: _LinearInterpolatorData) -> NDArray[np.float64]: n = np.array([tri.simplices[n] for n in tri.neighbors[i] if n != -1]) # remove the vertices that are in the simplex c = np.setdiff1d(n.reshape(-1), tri.simplices[i]) return np.concatenate((tri.points[c], ip.values[c]), axis=-1) simplices = np.concatenate( - [tri.points[tri.simplices], ip.values[tri.simplices]], axis=-1 + [tri.points[tri.simplices], interp.values[tri.simplices]], axis=-1 ) - neighbors = [get_neighbors(i, ip) for i in range(len(tri.simplices))] + neighbors = [get_neighbors(i, interp) for i in range(len(tri.simplices))] return [ sum(simplex_volume_in_embedding(np.vstack([simplex, n])) for n in neighbors[i]) @@ -371,9 +430,8 @@ class Learner2D(BaseLearner): function : callable The function to learn. Must take a tuple of two real parameters and return a real number. - bounds : list of 2-tuples - A list ``[(a1, b1), (a2, b2)]`` containing bounds, - one per dimension. + bounds : sequence of pairs + Bounds ``[(a1, b1), (a2, b2)]``, one pair per dimension. loss_per_triangle : callable, optional A function that returns the loss for every triangle. If not provided, then a default is used, which uses @@ -426,11 +484,14 @@ class Learner2D(BaseLearner): over each triangle. """ + data: dict[_Point, _Value] + pending_points: set[_Point] + def __init__( self, - function: Callable, - bounds: tuple[tuple[Real, Real], tuple[Real, Real]], - loss_per_triangle: Callable | None = None, + function: Callable[[_Point], _Value], + bounds: Sequence[Sequence[float | np.floating | np.integer]], + loss_per_triangle: _TriangleLoss | None = None, ) -> None: self.ndim = len(bounds) self._vdim: int | None = None @@ -440,32 +501,33 @@ def __init__( (float(bounds[1][0]), float(bounds[1][1])), ) self.data = OrderedDict() - self._stack = OrderedDict() + self._stack: OrderedDict[_Point, float] = OrderedDict() self.pending_points = set() self.xy_mean = np.mean(self.bounds, axis=1) self._xy_scale = np.ptp(self.bounds, axis=1) - self.aspect_ratio = 1 + self.aspect_ratio: float = 1 - self._bounds_points = list(itertools.product(*bounds)) + self._bounds_points = cast(list[_Point], list(itertools.product(*bounds))) self._stack.update(dict.fromkeys(self._bounds_points, np.inf)) - self.function = function # type: ignore - self._ip = self._ip_combined = None + self.function = function + self._ip: LinearNDInterpolator | None = None + self._ip_combined: LinearNDInterpolator | None = None self.stack_size = 10 - def new(self) -> Learner2D: - return Learner2D(self.function, self.bounds, self.loss_per_triangle) + def new(self) -> Self: + return cast(Self, Learner2D(self.function, self.bounds, self.loss_per_triangle)) @property - def xy_scale(self) -> np.ndarray: + def xy_scale(self) -> NDArray[np.float64]: xy_scale = self._xy_scale if self.aspect_ratio == 1: return xy_scale else: return np.array([xy_scale[0], xy_scale[1] / self.aspect_ratio]) - def to_numpy(self): + def to_numpy(self) -> NDArray[np.floating | np.integer]: """Data as NumPy array of size ``(npoints, 3)`` if ``learner.function`` returns a scalar and ``(npoints, 2+vdim)`` if ``learner.function`` returns a vector of length ``vdim``. """ @@ -473,7 +535,7 @@ def to_numpy(self): [(x, y, *np.atleast_1d(z)) for (x, y), z in sorted(self.data.items())] ) - def to_dataframe( # type: ignore[override] + def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -519,7 +581,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -527,7 +589,7 @@ def load_dataframe( # type: ignore[override] x_name: str = "x", y_name: str = "y", z_name: str = "z", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -551,22 +613,20 @@ def load_dataframe( # type: ignore[override] The ``z_name`` used in ``to_dataframe``, by default "z" """ data = df.set_index([x_name, y_name])[z_name].to_dict() - self._set_data(data) + self._set_data(cast("dict[_Point, _Value]", data)) if with_default_function_args: self.function = partial_function_from_dataframe( self.function, df, function_prefix ) - def _scale(self, points: list[tuple[float, float]] | np.ndarray) -> np.ndarray: - points = np.asarray(points, dtype=float) - return (points - self.xy_mean) / self.xy_scale + def _scale(self, points: ArrayLike) -> NDArray[np.float64]: + return (np.asarray(points, dtype=float) - self.xy_mean) / self.xy_scale - def _unscale(self, points: np.ndarray) -> np.ndarray: - points = np.asarray(points, dtype=float) - return points * self.xy_scale + self.xy_mean + def _unscale(self, points: ArrayLike) -> NDArray[np.float64]: + return np.asarray(points, dtype=float) * self.xy_scale + self.xy_mean @property - def npoints(self) -> int: # type: ignore[override] + def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) @@ -581,7 +641,7 @@ def vdim(self) -> int: if self._vdim is None and self.data: try: value = next(iter(self.data.values())) - self._vdim = len(value) + self._vdim = len(cast(Sized, value)) except TypeError: self._vdim = 1 return self._vdim or 1 @@ -594,7 +654,7 @@ def bounds_are_done(self) -> bool: def interpolated_on_grid( self, n: int | None = None - ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + ) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]: """Get the interpolated data on a grid. Parameters @@ -613,7 +673,7 @@ def interpolated_on_grid( if n is None: # Calculate how many grid points are needed. # factor from A=√3/4 * a² (equilateral triangle) - n = int(0.658 / sqrt(areas(ip).min())) + n = int(0.658 / sqrt(np.min(areas(ip)))) n = max(n, 10) # The bounds of the linspace should be (-0.5, 0.5) but because of @@ -622,25 +682,32 @@ def interpolated_on_grid( # boundary would be outside of the domain. See #181. eps = 1e-13 xs = ys = np.linspace(-0.5 + eps, 0.5 - eps, n) - zs = ip(xs[:, None], ys[None, :] * self.aspect_ratio).squeeze() + interp = cast("_LinearInterpolatorData", ip) + zs = interp(xs[:, None], ys[None, :] * self.aspect_ratio).squeeze() xs, ys = self._unscale(np.vstack([xs, ys]).T).T return xs, ys, zs - def _data_in_bounds(self) -> tuple[np.ndarray, np.ndarray]: + def _data_in_bounds( + self, + ) -> tuple[NDArray[np.floating | np.integer], NDArray[np.float64]]: if self.data: points = np.array(list(self.data.keys())) values = np.array(list(self.data.values()), dtype=float) + ll: NDArray[np.float64] + ur: NDArray[np.float64] ll, ur = np.reshape(self.bounds, (2, 2)).T inds = np.all(np.logical_and(ll <= points, points <= ur), axis=1) return points[inds], values[inds].reshape(-1, self.vdim) return np.zeros((0, 2)), np.zeros((0, self.vdim), dtype=float) - def _data_interp(self) -> tuple[np.ndarray | list[tuple[float, float]], np.ndarray]: + def _data_interp( + self, + ) -> tuple[NDArray[np.float64] | list[_Point], NDArray[np.float64]]: if self.pending_points: points = list(self.pending_points) if self.bounds_are_done: ip = self.interpolator(scaled=True) - values = ip(self._scale(points)) + values = cast("_LinearInterpolatorData", ip)(self._scale(points)) else: # Without the bounds the interpolation cannot be done properly, # so we just set everything to zero. @@ -648,7 +715,9 @@ def _data_interp(self) -> tuple[np.ndarray | list[tuple[float, float]], np.ndarr return points, values return np.zeros((0, 2)), np.zeros((0, self.vdim), dtype=float) - def _data_combined(self) -> tuple[np.ndarray, np.ndarray]: + def _data_combined( + self, + ) -> tuple[NDArray[np.floating | np.integer], NDArray[np.float64]]: points, values = self._data_in_bounds() if not self.pending_points: return points, values @@ -708,32 +777,30 @@ def _interpolator_combined(self) -> LinearNDInterpolator: self._ip_combined = interpolate.LinearNDInterpolator(points, values) return self._ip_combined - def inside_bounds(self, xy: tuple[float, float]) -> Bool: + def inside_bounds(self, xy: _PointInput) -> bool | np.bool_: x, y = xy (xmin, xmax), (ymin, ymax) = self.bounds return xmin <= x <= xmax and ymin <= y <= ymax - def tell(self, point: tuple[float, float], value: float | Iterable[float]) -> None: - point = tuple(point) # type: ignore[assignment] - self.data[point] = value - if not self.inside_bounds(point): + def tell(self, point: _PointInput, value: _Value) -> None: + xy = cast(_Point, tuple(point)) + self.data[xy] = value + if not self.inside_bounds(xy): return - self.pending_points.discard(point) + self.pending_points.discard(xy) self._ip = None self._ip_combined = None - self._stack.pop(point, None) + self._stack.pop(xy, None) - def tell_pending(self, point: tuple[float, float]) -> None: - point = tuple(point) # type: ignore[assignment] - if not self.inside_bounds(point): + def tell_pending(self, point: _PointInput) -> None: + xy = cast(_Point, tuple(point)) + if not self.inside_bounds(xy): return - self.pending_points.add(point) + self.pending_points.add(xy) self._ip_combined = None - self._stack.pop(point, None) + self._stack.pop(xy, None) - def _fill_stack( - self, stack_till: int = 1 - ) -> tuple[list[tuple[float, float]], list[float]]: + def _fill_stack(self, stack_till: int = 1) -> tuple[list[_Point], list[float]]: if len(self.data) + len(self.pending_points) < self.ndim + 1: raise ValueError("too few points...") @@ -741,21 +808,24 @@ def _fill_stack( ip = self._interpolator_combined() losses = self.loss_per_triangle(ip) + interp = cast("_LinearInterpolatorData", ip) + + # np.clip results in numerical precision problems + # https://github.com/python-adaptive/adaptive/issues/7 + def clip(x: float, lo: float, up: float) -> float: + return max(lo, min(up, x)) points_new = [] losses_new = [] for _j, _ in enumerate(losses): jsimplex = np.argmax(losses) - triangle = ip.tri.points[ip.tri.simplices[jsimplex]] - point_new = choose_point_in_triangle(triangle, max_badness=5) - point_new = tuple(self._unscale(point_new)) - - # np.clip results in numerical precision problems - # https://github.com/python-adaptive/adaptive/issues/7 - clip = lambda x, lo, up: max(lo, min(up, x)) # noqa: E731 + tri = interp.tri + triangle = tri.points[tri.simplices[jsimplex]] + point = choose_point_in_triangle(triangle, max_badness=5) + xy = tuple(self._unscale(point)) point_new = ( - clip(point_new[0], *self.bounds[0]), - clip(point_new[1], *self.bounds[1]), + clip(xy[0], *self.bounds[0]), + clip(xy[1], *self.bounds[1]), ) loss_new = losses[jsimplex] @@ -774,7 +844,7 @@ def _fill_stack( def ask( self, n: int, tell_pending: bool = True - ) -> tuple[list[tuple[float, float] | np.ndarray], list[float]]: + ) -> tuple[list[_Point], list[float]]: # Even if tell_pending is False we add the point such that _fill_stack # will return new points, later we remove these points if needed. points = list(self._stack.keys()) @@ -810,7 +880,8 @@ 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() + # Unlike point selection, loss reporting expects an array result. + return cast("_HasMax", losses).max() def remove_unfinished(self) -> None: self.pending_points = set() @@ -819,7 +890,7 @@ def remove_unfinished(self) -> None: if p not in self.data: self._stack[p] = np.inf - def plot(self, n=None, tri_alpha=0.0): + def plot(self, n: int | None = None, tri_alpha: float = 0.0) -> Overlay | HoloMap: r"""Plot the Learner2D's current state. This plot function interpolates the data on a regular grid. @@ -855,7 +926,7 @@ def plot(self, n=None, tri_alpha=0.0): if len(self.data) >= 4: ip = self.interpolator(scaled=True) - x, y, z = self.interpolated_on_grid(n) + _, _, z = self.interpolated_on_grid(n) if self.vdim > 1: ims = { @@ -867,7 +938,8 @@ def plot(self, n=None, tri_alpha=0.0): im = hv.Image(np.rot90(z), bounds=lbrt) if tri_alpha: - points = self._unscale(ip.tri.points[ip.tri.simplices]) + tri = cast("_LinearInterpolatorData", ip).tri + points = self._unscale(tri.points[tri.simplices]) points = np.pad( points[:, [0, 1, 2, 0], :], pad_width=((0, 0), (0, 1), (0, 0)), @@ -884,17 +956,17 @@ def plot(self, n=None, tri_alpha=0.0): line_width=0.5, alpha=tri_alpha, tools=[] ) - def _get_data(self) -> dict[tuple[float, float], Float | np.ndarray]: + def _get_data(self) -> dict[_Point, _Value]: return self.data - def _set_data(self, data: dict[tuple[float, float], Float | np.ndarray]) -> None: + def _set_data(self, data: dict[_Point, _Value]) -> None: self.data = data # Remove points from stack if they already exist for point in copy(self._stack): if point in self.data: self._stack.pop(point) - def __getstate__(self): + def __getstate__(self) -> _State: return ( cloudpickle.dumps(self.function), self.bounds, @@ -903,9 +975,10 @@ def __getstate__(self): self._get_data().copy(), ) - def __setstate__(self, state): - function, bounds, loss_per_triangle, _stack, data = state - function = cloudpickle.loads(function) - self.__init__(function, bounds, loss_per_triangle) + def __setstate__(self, state: _State) -> None: + function_pickle, bounds, loss_per_triangle, _stack, data = state + function = cloudpickle.loads(function_pickle) + # Retain virtual dispatch for subclasses that reuse this pickle state. + cast(Any, self).__init__(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 8c4b5dde..54b492d2 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -5,18 +5,41 @@ import math import random from collections import OrderedDict -from collections.abc import Iterable +from collections.abc import Callable, Iterable, Mapping, Sequence, Sized from copy import deepcopy +from typing import ( + TYPE_CHECKING, + Any, + Literal, + Protocol, + Self, + SupportsFloat, + TypeAlias, + TypeVar, + cast, +) import numpy as np +import numpy.typing as npt import scipy.spatial from scipy import interpolate from sortedcontainers import SortedKeyList from adaptive.learner.base_learner import BaseLearner, uses_nth_neighbors -from adaptive.learner.triangulation import fast_det +from adaptive.learner.triangulation import ( + _Point, + _PointLike, + _PointsLike, + _Simplex, + _SimplexSet, + fast_det, +) from adaptive.learner.triangulation_backend import ( Triangulation, + TriangulationProtocol, + _BatchedTriangulation, + _SimplicesProxy, + _TriangulationClass, circumsphere, point_in_simplex, resolve_triangulation_class, @@ -31,6 +54,11 @@ restore, ) +if TYPE_CHECKING: + from holoviews.core import Overlay + from holoviews.element import Image, Path + from plotly.graph_objects import Figure, Mesh3d + try: import pandas @@ -40,13 +68,53 @@ with_pandas = False -def to_list(inp): +_Array: TypeAlias = npt.NDArray[Any] +_Value: TypeAlias = float | Sequence[float] | _Array +_Values: TypeAlias = Sequence[_Value] | _Array +_Loss: TypeAlias = Callable[[_Array, _Array, float], SupportsFloat] +_NeighborLoss: TypeAlias = Callable[ + [_Array, _Array, float, list[_Array | None], list[_Value | None]], SupportsFloat +] +_Bounds: TypeAlias = Sequence[Sequence[float]] | scipy.spatial.ConvexHull +_QueueItem: TypeAlias = tuple[float, _Simplex, _Simplex | None] +_T = TypeVar("_T") + + +class _NeighborMetadata(Protocol): + nth_neighbors: int + + +class _CurvatureLoss(_NeighborMetadata, Protocol): + def __call__( + self, + simplex: _PointsLike, + values: _Values, + value_scale: float, + neighbors: Sequence[_PointLike | None], + neighbor_values: Sequence[_Value | None], + ) -> float: ... + + +class _SliceInterpolator(Protocol): + # SciPy supports multiple broadcastable coordinate arguments. + def __call__(self, *coords: float | _Array) -> _Array: ... + + +class _SimplexQueue(Protocol): + """The subset of the untyped SortedKeyList interface used here.""" + + def add(self, value: _QueueItem, /) -> None: ... + def pop(self, index: int = -1, /) -> _QueueItem: ... + def __len__(self) -> int: ... + + +def to_list(inp: _T | Iterable[_T]) -> list[_T]: if isinstance(inp, Iterable): return list(inp) return [inp] -def volume(simplex, ys=None): +def volume(simplex: _PointsLike, ys: object = None) -> float: # Notice the parameter ys is there so you can use this volume method as # as loss function matrix = np.subtract(simplex[:-1], simplex[-1], dtype=float) @@ -57,14 +125,14 @@ def volume(simplex, ys=None): return vol -def orientation(simplex): +def orientation(simplex: _PointsLike) -> float: matrix = np.subtract(simplex[:-1], simplex[-1]) # See https://www.jstor.org/stable/2315353 sign, _logdet = np.linalg.slogdet(matrix) return sign -def uniform_loss(simplex, values, value_scale): +def uniform_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> float: """ Uniform loss. @@ -84,7 +152,7 @@ def uniform_loss(simplex, values, value_scale): return volume(simplex) -def std_loss(simplex, values, value_scale): +def std_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> float: """ Computes the loss of the simplex based on the standard deviation. @@ -102,7 +170,9 @@ def std_loss(simplex, values, value_scale): loss : float """ - r = np.linalg.norm(np.std(values, axis=0)) + # NumPy accepts sequences of array rows at runtime, too. + array_like = cast("Sequence[float] | Sequence[Sequence[float]] | _Array", values) + r = np.linalg.norm(np.std(array_like, axis=0)) vol = volume(simplex) dim = len(simplex) - 1 @@ -110,7 +180,7 @@ def std_loss(simplex, values, value_scale): return r.flat * np.power(vol, 1.0 / dim) + vol -def default_loss(simplex, values, value_scale): +def default_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> float: """ Computes the average of the volumes of the simplex. @@ -128,14 +198,21 @@ def default_loss(simplex, values, value_scale): loss : float """ if isinstance(values[0], Iterable): - pts = [(*x, *y) for x, y in zip(simplex, values)] + vectors = cast("Sequence[_PointLike]", values) + pts = [(*x, *y) for x, y in zip(simplex, vectors)] else: - pts = [(*x, y) for x, y in zip(simplex, values)] + pts = [(*x, y) for x, y in zip(simplex, cast("Sequence[float]", values))] return simplex_volume_in_embedding(pts) @uses_nth_neighbors(1) -def triangle_loss(simplex, values, value_scale, neighbors, neighbor_values): +def triangle_loss( + simplex: _PointsLike, + values: _Values, + value_scale: float, + neighbors: Sequence[_PointLike | None], + neighbor_values: Sequence[_Value | None], +) -> float: """ Computes the average of the volumes of the simplex combined with each neighbouring point. @@ -159,23 +236,29 @@ def triangle_loss(simplex, values, value_scale, neighbors, neighbor_values): loss : float """ - neighbors = [n for n in neighbors if n is not None] - neighbor_values = [v for v in neighbor_values if v is not None] - if len(neighbors) == 0: + known_neighbors = [n for n in neighbors if n is not None] + known_neighbor_values = [v for v in neighbor_values if v is not None] + if len(known_neighbors) == 0: return 0 s = [(*x, *to_list(y)) for x, y in zip(simplex, values)] - n = [(*x, *to_list(y)) for x, y in zip(neighbors, neighbor_values)] + n = [(*x, *to_list(y)) for x, y in zip(known_neighbors, known_neighbor_values)] return sum(simplex_volume_in_embedding([*s, neighbor]) for neighbor in n) / len( - neighbors + known_neighbors ) -def curvature_loss_function(exploration=0.05): +def curvature_loss_function(exploration: float = 0.05) -> _CurvatureLoss: # XXX: add doc-string! @uses_nth_neighbors(1) - def curvature_loss(simplex, values, value_scale, neighbors, neighbor_values): + def curvature_loss( + simplex: _PointsLike, + values: _Values, + value_scale: float, + neighbors: Sequence[_PointLike | None], + neighbor_values: Sequence[_Value | None], + ) -> float: """Compute the curvature loss of a simplex. Parameters @@ -209,7 +292,9 @@ def curvature_loss(simplex, values, value_scale, neighbors, neighbor_values): return curvature_loss -def choose_point_in_simplex(simplex, transform=None): +def choose_point_in_simplex( + simplex: _PointsLike, transform: _Array | None = None +) -> _Array: """Choose a new point in inside a simplex. Pick the center of the simplex if the shape is nice (that is, the @@ -237,12 +322,13 @@ def choose_point_in_simplex(simplex, transform=None): # otherwise: the center the longest edge center, _radius = circumsphere(simplex) if point_in_simplex(center, simplex): - point = np.average(simplex, axis=0) + point = np.average(cast("Sequence[Sequence[float]] | _Array", simplex), axis=0) else: distances = scipy.spatial.distance.pdist(simplex) distance_matrix = scipy.spatial.distance.squareform(distances) i, j = np.unravel_index(np.argmax(distance_matrix), distance_matrix.shape) - point = (simplex[i, :] + simplex[j, :]) / 2 + vertices = cast("_Array", simplex) + point = (vertices[i, :] + vertices[j, :]) / 2 if transform is not None: point = np.linalg.solve(transform.T, point) # undo the transform @@ -250,7 +336,9 @@ def choose_point_in_simplex(simplex, transform=None): return point -def _simplex_evaluation_priority(key): +def _simplex_evaluation_priority( + key: _QueueItem, +) -> tuple[float, _Simplex, _Simplex]: # We round the loss to 8 digits such that losses # are equal up to numerical precision will be considered # to be equal. This is needed because we want the learner @@ -324,32 +412,36 @@ class LearnerND(BaseLearner): # Class-level fallback so that learners restored from pickles made # before `triangulation_backend` existed keep working. - _triangulation_class = Triangulation + _triangulation_class: _TriangulationClass = Triangulation + + data: OrderedDict[_Point, _Value] + pending_points: set[_Point] def __init__( self, - func, - bounds, - loss_per_simplex=None, + func: Callable[[_Point], _Value], + bounds: _Bounds, + loss_per_simplex: _Loss | _NeighborLoss | None = None, *, - anisotropic=False, - triangulation_backend="auto", - ): + anisotropic: bool = False, + triangulation_backend: str | _TriangulationClass = "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 if hasattr(self.loss_per_simplex, "nth_neighbors"): - if self.loss_per_simplex.nth_neighbors > 1: + loss_with_metadata = cast(_NeighborMetadata, self.loss_per_simplex) + if loss_with_metadata.nth_neighbors > 1: raise NotImplementedError( "The provided loss function wants " "next-nearest neighboring simplices for the loss computation, " "this feature is not yet implemented, either use " "nth_neightbors = 0 or 1" ) - self.nth_neighbors = self.loss_per_simplex.nth_neighbors + self.nth_neighbors = loss_with_metadata.nth_neighbors else: self.nth_neighbors = 0 @@ -357,6 +449,8 @@ def __init__( self.pending_points = set() self.bounds = bounds + self._bounds_points: list[_Point] + self._interior: scipy.spatial.Delaunay | None if isinstance(bounds, scipy.spatial.ConvexHull): hull_points = bounds.points[bounds.vertices] self._bounds_points = sorted(map(tuple, hull_points)) @@ -364,7 +458,9 @@ def __init__( self._interior = scipy.spatial.Delaunay(self._bounds_points) else: self._bounds_points = sorted(map(tuple, itertools.product(*bounds))) - self._bbox = tuple(tuple(map(float, b)) for b in bounds) + self._bbox = tuple( + cast("tuple[float, float]", tuple(map(float, b))) for b in bounds + ) self._interior = None self.ndim = len(self._bbox) @@ -377,23 +473,23 @@ def __init__( f"LearnerND only supports dim >= 2 (got ndim={self.ndim})." ) - self.function = func - self._tri = None - self._losses = {} + self.function: Callable[[_Point], _Value] = func + self._tri: TriangulationProtocol | None = None + self._losses: dict[_Simplex, float] = {} - self._pending_to_simplex = {} # vertex → simplex + self._pending_to_simplex: dict[_Point, _Simplex] = {} # vertex → simplex # triangulation of the pending points inside a specific simplex - self._subtriangulations = {} # simplex → triangulation + self._subtriangulations: dict[_Simplex, TriangulationProtocol] = {} # scale to unit hypercube # for the input self._transform = np.linalg.inv(np.diag(np.diff(self._bbox).flat)) # for the output - self._min_value = None - self._max_value = None - self._old_scale = None - self._output_multiplier = ( + self._min_value: float | None = None + self._max_value: float | None = None + self._old_scale: float | None = None + self._output_multiplier: float = ( 1 # If we do not know anything, do not scale the values ) self._recompute_losses_factor = 1.1 @@ -413,25 +509,30 @@ def __init__( # so when popping an item, you should check that the simplex that has # been returned has not been deleted. This checking is done by # _pop_highest_existing_simplex - self._simplex_queue = SortedKeyList(key=_simplex_evaluation_priority) + self._simplex_queue: _SimplexQueue = SortedKeyList( + key=_simplex_evaluation_priority + ) - def new(self) -> LearnerND: + def new(self) -> Self: """Create a new learner with the same function and bounds.""" - return LearnerND( - self.function, - self.bounds, - self.loss_per_simplex, - anisotropic=self.anisotropic, - triangulation_backend=self._triangulation_class, + return cast( + "Self", + LearnerND( + self.function, + self.bounds, + self.loss_per_simplex, + anisotropic=self.anisotropic, + triangulation_backend=self._triangulation_class, + ), ) @property - def npoints(self): + def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) @property - def vdim(self): + def vdim(self) -> int: """Length of the output of ``learner.function``. If the output is unsized (when it's a scalar) then `vdim = 1`. @@ -441,12 +542,12 @@ def vdim(self): if self._vdim is None and self.data: try: value = next(iter(self.data.values())) - self._vdim = len(value) + self._vdim = len(cast(Sized, value)) except TypeError: self._vdim = 1 return self._vdim if self._vdim is not None else 1 - def to_numpy(self): + def to_numpy(self) -> _Array: """Data as NumPy array of size ``(npoints, dim+vdim)``, where ``dim`` is the size of the input dimension and ``vdim`` is the length of the return value of ``learner.function``.""" @@ -457,7 +558,7 @@ def _default_point_names(self) -> tuple[str, ...]: return ("x", "y", "z")[: self.ndim] return tuple(f"x{i}" for i in range(self.ndim)) - def to_dataframe( # type: ignore[override] + def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -507,14 +608,14 @@ def to_dataframe( # type: ignore[override] assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, df: pandas.DataFrame, with_default_function_args: bool = True, function_prefix: str = "function.", point_names: tuple[str, ...] | None = None, value_name: str = "value", - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -545,17 +646,17 @@ def load_dataframe( # type: ignore[override] ) @property - def bounds_are_done(self): + def bounds_are_done(self) -> bool: return all(p in self.data for p in self._bounds_points) - def _ip(self): + def _ip(self) -> interpolate.LinearNDInterpolator: """A `scipy.interpolate.LinearNDInterpolator` instance containing the learner's data.""" # XXX: take our own triangulation into account when generating the _ip return interpolate.LinearNDInterpolator(self.points, self.values) @property - def tri(self): + def tri(self) -> TriangulationProtocol | None: """An `adaptive.learner.triangulation.Triangulation` instance with all the points of the learner.""" if self._tri is not None: @@ -573,16 +674,16 @@ def tri(self): return self._tri @property - def values(self): + def values(self) -> npt.NDArray[np.float64]: """Get the values from `data` as a numpy array.""" return np.array(list(self.data.values()), dtype=float) @property - def points(self): + def points(self) -> npt.NDArray[np.float64]: """Get the points from `data` as a numpy array.""" return np.array(list(self.data.keys()), dtype=float) - def tell(self, point, value): + def tell(self, point: Iterable[float], value: _Value | None) -> None: point = tuple(point) if point in self.data: return # we already know about the point @@ -608,13 +709,13 @@ def tell(self, point, value): to_delete, to_add = tri.add_point(point, simplex, transform=self._transform) self._update_losses(to_delete, to_add) - def get_local_transform_matrix(self, simplex): + def get_local_transform_matrix(self, simplex: _Simplex | None) -> _Array: scale = self._transform - if simplex is None or self.tri is None or not self.anisotropic: + if simplex is None or (tri := self.tri) is None or not self.anisotropic: return scale - neighbors = set.union(*[self.tri.vertex_to_simplices[i] for i in simplex]) + neighbors = set.union(*[tri.vertex_to_simplices[i] for i in simplex]) indices = set.union(set(), *neighbors) points = np.array([self.points[i] for i in indices]) @@ -650,11 +751,11 @@ def get_local_transform_matrix(self, simplex): m = np.dot(scale_along_gradient, scale) return m.T - def _simplex_exists(self, simplex): + def _simplex_exists(self, simplex: Iterable[int]) -> bool: simplex = tuple(sorted(simplex)) - return simplex in self.tri.simplices + return simplex in cast(TriangulationProtocol, self.tri).simplices - def inside_bounds(self, point): + def inside_bounds(self, point: _PointLike) -> bool | np.bool_: """Check whether a point is inside the bounds.""" if self._interior is not None: return self._interior.find_simplex(point, tol=1e-8) >= 0 @@ -664,7 +765,9 @@ def inside_bounds(self, point): (mn - eps) <= p <= (mx + eps) for p, (mn, mx) in zip(point, self._bbox) ) - def tell_pending(self, point, *, simplex=None): + def tell_pending( + self, point: Iterable[float], *, simplex: _Simplex | None = None + ) -> None: point = tuple(point) if not self.inside_bounds(point): return @@ -680,54 +783,67 @@ def tell_pending(self, point, *, simplex=None): continue self._update_subsimplex_losses(simpl, to_add) - def _simplices_containing_point(self, point, simplex=None): + def _simplices_containing_point( + self, point: _Point, simplex: _Simplex | None = None + ) -> list[_Simplex]: """All simplices of the triangulation containing `point`, found from the `simplex` hint when given.""" - if hasattr(self.tri, "simplices_containing"): + tri = cast(TriangulationProtocol, self.tri) + if hasattr(tri, "simplices_containing"): # Rust backend: one call instead of a point_in_simplex loop. - return self.tri.simplices_containing(point, simplex=simplex) + return cast(_BatchedTriangulation, tri).simplices_containing( + point, simplex=simplex + ) - simplex = tuple(simplex or self.tri.locate_point(point)) + simplex = tuple(simplex or tri.locate_point(point)) if not simplex: return [] # Simplex is empty if the pending point is outside the # triangulation, then you do not have subtriangles - simplices = [self.tri.vertex_to_simplices[i] for i in simplex] + simplices = [tri.vertex_to_simplices[i] for i in simplex] neighbors = set.union(*simplices) # Neighbours also includes the simplex itself - return [s for s in neighbors if self.tri.point_in_simplex(point, s)] + return [s for s in neighbors if tri.point_in_simplex(point, s)] - def _add_pending_point_to_simplex(self, point, simplex): + def _add_pending_point_to_simplex( + self, point: _Point, simplex: _Simplex + ) -> tuple[_SimplexSet, _SimplexSet]: """Insert `point` into the subtriangulation of `simplex`, which must contain the point.""" if simplex not in self._subtriangulations: - vertices = self.tri.get_vertices(simplex) + vertices = cast(TriangulationProtocol, self.tri).get_vertices(simplex) self._subtriangulations[simplex] = self._triangulation_class(vertices) self._pending_to_simplex[point] = simplex return self._subtriangulations[simplex].add_point(point) - def _try_adding_pending_point_to_simplex(self, point, simplex): + def _try_adding_pending_point_to_simplex( + self, point: _Point, simplex: _Simplex + ) -> tuple[_SimplexSet, _SimplexSet] | tuple[None, None]: # try to insert it - if not self.tri.point_in_simplex(point, simplex): + if not cast(TriangulationProtocol, self.tri).point_in_simplex(point, simplex): return None, None return self._add_pending_point_to_simplex(point, simplex) - def _update_subsimplex_losses(self, simplex, new_subsimplices): + def _update_subsimplex_losses( + self, simplex: _Simplex, new_subsimplices: Iterable[_Simplex] + ) -> None: loss = self._losses[simplex] - loss_density = loss / self.tri.volume(simplex) + loss_density = loss / cast(TriangulationProtocol, self.tri).volume(simplex) subtriangulation = self._subtriangulations[simplex] for subsimplex in new_subsimplices: subloss = subtriangulation.volume(subsimplex) * loss_density self._simplex_queue.add((subloss, simplex, subsimplex)) - def _ask_and_tell_pending(self, n=1): + def _ask_and_tell_pending(self, n: int = 1) -> tuple[list[_Point], list[float]]: xs, losses = zip(*(self._ask() for _ in range(n))) return list(xs), list(losses) - def ask(self, n, tell_pending=True): + def ask( + self, n: int, tell_pending: bool = True + ) -> tuple[list[_Point], list[float]]: """Chose points for learners.""" if not tell_pending: with restore(self): @@ -735,7 +851,7 @@ def ask(self, n, tell_pending=True): else: return self._ask_and_tell_pending(n) - def _ask_bound_point(self): + def _ask_bound_point(self) -> tuple[_Point, float]: # get the next bound point that is still available new_point = next( p @@ -745,7 +861,7 @@ def _ask_bound_point(self): self.tell_pending(new_point) return new_point, np.inf - def _ask_point_without_known_simplices(self): + def _ask_point_without_known_simplices(self) -> tuple[_Point, float]: assert not self._bounds_available # pick a random point inside the bounds # XXX: change this into picking a point based on volume loss @@ -754,13 +870,12 @@ def _ask_point_without_known_simplices(self): p = None while p is None or not self.inside_bounds(p): r = np.array([self._random.random() for _ in range(self.ndim)]) - p = r * a + b - p = tuple(p) + p = tuple(r * a + b) self.tell_pending(p) return p, np.inf - def _pop_highest_existing_simplex(self): + def _pop_highest_existing_simplex(self) -> _QueueItem: # find the simplex with the highest loss, we do need to check that the # simplex hasn't been deleted yet while len(self._simplex_queue): @@ -768,14 +883,14 @@ def _pop_highest_existing_simplex(self): loss, simplex, subsimplex = self._simplex_queue.pop(0) if ( subsimplex is None - and simplex in self.tri.simplices + and simplex in cast(TriangulationProtocol, self.tri).simplices and simplex not in self._subtriangulations ): return abs(loss), simplex, subsimplex if ( subsimplex is not None and simplex in self._subtriangulations - and simplex in self.tri.simplices + and simplex in cast(TriangulationProtocol, self.tri).simplices and subsimplex in self._subtriangulations[simplex].simplices ): return abs(loss), simplex, subsimplex @@ -787,15 +902,16 @@ def _pop_highest_existing_simplex(self): " be a simplex available if LearnerND.tri() is not None." ) - def _ask_best_point(self): - assert self.tri is not None + def _ask_best_point(self) -> tuple[_Point, float]: + tri = self.tri + assert tri is not None while True: loss, simplex, subsimplex = self._pop_highest_existing_simplex() if subsimplex is None: # We found a real simplex and want to subdivide it - points = self.tri.get_vertices(simplex) + points = tri.get_vertices(simplex) else: # We found a pending simplex and want to subdivide it subtri = self._subtriangulations[simplex] @@ -815,13 +931,13 @@ def _ask_best_point(self): return point_new, loss @property - def _bounds_available(self): + def _bounds_available(self) -> bool: return any( (p not in self.pending_points and p not in self.data) for p in self._bounds_points ) - def _ask(self): + def _ask(self) -> tuple[_Point, float]: if self._bounds_available: return self._ask_bound_point() # O(1) @@ -833,27 +949,33 @@ def _ask(self): return self._ask_best_point() # O(log N) - def _compute_loss(self, simplex): + def _compute_loss(self, simplex: _Simplex) -> float: # get the loss - vertices = self.tri.get_vertices(simplex) + tri = cast(TriangulationProtocol, self.tri) + vertices = tri.get_vertices(simplex) values = [self.data[tuple(v)] for v in vertices] # scale them to a cube with sides 1 - vertices = vertices @ self._transform - values = self._output_multiplier * np.array(values) + scaled_vertices = vertices @ self._transform + scaled_values = self._output_multiplier * np.array(values) if self.nth_neighbors == 0: # compute the loss on the scaled simplex - loss = self.loss_per_simplex(vertices, values, self._output_multiplier) + loss_function = cast("_Loss", self.loss_per_simplex) + loss = loss_function( + scaled_vertices, scaled_values, self._output_multiplier + ) if isinstance(loss, np.ndarray): return float(loss.item()) return float(loss) # We do need the neighbors - neighbors = self.tri.get_opposing_vertices(simplex) + neighbors = 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_vertices = tri.get_vertices(neighbors) + data = cast("Mapping[_Point | None, _Value]", self.data) + neighbor_values = [data.get(x, None) for x in neighbor_vertices] + neighbor_points = cast("list[_Point | _Array | None]", neighbor_vertices) for i, point in enumerate(neighbor_points): if point is not None: @@ -861,21 +983,27 @@ def _compute_loss(self, simplex): for i, value in enumerate(neighbor_values): if value is not None: - neighbor_values[i] = self._output_multiplier * value + # NumPy's scalar multiplication also handles sequence outputs. + neighbor_values[i] = self._output_multiplier * cast( + "float | _Array", value + ) + neighbor_loss_function = cast("_NeighborLoss", self.loss_per_simplex) return float( - self.loss_per_simplex( - vertices, - values, + neighbor_loss_function( + scaled_vertices, + scaled_values, self._output_multiplier, - neighbor_points, + cast("list[_Array | None]", neighbor_points), neighbor_values, ) ) - def _update_losses(self, to_delete: set, to_add: set): + def _update_losses( + self, to_delete: _SimplexSet, to_add: _SimplexSet | _SimplicesProxy + ) -> None: # XXX: add the points outside the triangulation to this as well - pending_points_unbound = set() + pending_points_unbound: set[_Point] = set() for simplex in to_delete: loss = self._losses.pop(simplex, None) @@ -903,9 +1031,9 @@ def _update_losses(self, to_delete: set, to_add: set): if self.nth_neighbors: points_of_added_simplices = set.union(*[set(s) for s in to_add]) + tri = cast(TriangulationProtocol, self.tri) neighbors = ( - self.tri.get_simplices_attached_to_points(points_of_added_simplices) - - to_add + tri.get_simplices_attached_to_points(points_of_added_simplices) - to_add ) for simplex in neighbors: loss = self._compute_loss(simplex) @@ -919,7 +1047,7 @@ def _update_losses(self, to_delete: set, to_add: set): simplex, self._subtriangulations[simplex].simplices ) - def _recompute_all_losses(self): + def _recompute_all_losses(self) -> None: """Recompute all losses and pending losses.""" # amortized O(N) complexity if self.tri is None: @@ -943,11 +1071,11 @@ def _recompute_all_losses(self): ) @property - def _scale(self): + def _scale(self) -> float: # get the output scale - return self._max_value - self._min_value + return cast(float, self._max_value) - cast(float, self._min_value) - def _update_range(self, new_output): + def _update_range(self, new_output: _Value) -> bool: if self._min_value is None or self._max_value is None: # this is the first point, nothing to do, just set the range self._min_value = np.min(new_output) @@ -977,7 +1105,7 @@ def _update_range(self, new_output): if self._old_scale == 0: scale_factor = math.inf if self._scale > 0 else 1 else: - scale_factor = self._scale / self._old_scale + scale_factor = self._scale / cast(float, self._old_scale) if scale_factor > self._recompute_losses_factor: self._old_scale = self._scale self._recompute_all_losses() @@ -985,12 +1113,12 @@ def _update_range(self, new_output): return False @cache_latest - def loss(self, real=True): + def loss(self, real: bool = True) -> float: # XXX: compute pending loss if real == False losses = self._losses if self.tri is not None else {} return max(losses.values()) if losses else float("inf") - def remove_unfinished(self): + def remove_unfinished(self) -> None: # XXX: implement this method self.pending_points = set() self._subtriangulations = {} @@ -1000,7 +1128,7 @@ def remove_unfinished(self): # Plotting related stuff # ########################## - def plot(self, n=None, tri_alpha=0): + def plot(self, n: int | None = None, tri_alpha: float = 0) -> Overlay: """Plot the function we want to learn, only works in 2D. Parameters @@ -1028,7 +1156,8 @@ def plot(self, n=None, tri_alpha=0): # Calculate how many grid points are needed. # factor from A=√3/4 * a² (equilateral triangle) scale_factor = np.prod(np.diag(self._transform)) - a_sq = np.sqrt(np.min(self.tri.volumes()) * scale_factor) + tri = cast(TriangulationProtocol, self.tri) + a_sq = np.sqrt(np.min(tri.volumes()) * scale_factor) n = max(10, int(0.658 / a_sq)) xs = ys = np.linspace(0, 1, n) @@ -1039,9 +1168,8 @@ def plot(self, n=None, tri_alpha=0): im = hv.Image(np.rot90(z), bounds=lbrt) if tri_alpha: - points = np.array( - [self.tri.get_vertices(s) for s in self.tri.simplices] - ) + tri = cast(TriangulationProtocol, self.tri) + points = np.array([tri.get_vertices(s) for s in tri.simplices]) points = np.pad( points[:, [0, 1, 2, 0], :], pad_width=((0, 0), (0, 1), (0, 0)), @@ -1058,7 +1186,9 @@ def plot(self, n=None, tri_alpha=0): line_width=0.5, alpha=tri_alpha, tools=[] ) - def plot_slice(self, cut_mapping, n=None): + def plot_slice( + self, cut_mapping: Mapping[int, float], n: int | None = None + ) -> Image | Overlay | Path: """Plot a 1D or 2D interpolated slice of a N-dimensional function. Parameters @@ -1085,8 +1215,8 @@ def plot_slice(self, cut_mapping, n=None): for i in range(self.ndim) ] ind = next(i for i in range(self.ndim) if i not in cut_mapping) - x = values[ind] - y = self._ip()(*values) + x = cast("_Array", values[ind]) + y = cast(_SliceInterpolator, self._ip())(*values) p = hv.Path((x, y)) # Plot with 5% margins such that the boundary points are visible @@ -1103,7 +1233,8 @@ def plot_slice(self, cut_mapping, n=None): # Calculate how many grid points are needed. # factor from A=√3/4 * a² (equilateral triangle) scale_factor = np.prod(np.diag(self._transform)) - a_sq = np.sqrt(np.min(self.tri.volumes()) * scale_factor) + tri = cast(TriangulationProtocol, self.tri) + a_sq = np.sqrt(np.min(tri.volumes()) * scale_factor) n = max(10, int(0.658 / a_sq)) xs = ys = np.linspace(0, 1, n) @@ -1121,7 +1252,7 @@ def plot_slice(self, cut_mapping, n=None): lbrt = np.reshape(lbrt, (2, 2)).T.flatten().tolist() if len(self.data) >= 4: - z = self._ip()(*values).squeeze() + z = cast(_SliceInterpolator, self._ip())(*values).squeeze() im = hv.Image(np.rot90(z), bounds=lbrt) else: im = hv.Image([], bounds=lbrt) @@ -1130,7 +1261,9 @@ def plot_slice(self, cut_mapping, n=None): else: raise ValueError("Only 1 or 2-dimensional plots can be generated.") - def plot_3D(self, with_triangulation=False, return_fig=False): + def plot_3D( + self, with_triangulation: bool = False, return_fig: bool = False + ) -> Figure | None: """Plot the learner's data in 3D using plotly. Does *not* work with the @@ -1153,10 +1286,13 @@ def plot_3D(self, with_triangulation=False, return_fig=False): plots = [] - vertices = self.tri.vertices + tri = cast(TriangulationProtocol, self.tri) + vertices = tri.vertices if with_triangulation: - Xe, Ye, Ze = [], [], [] - for simplex in self.tri.simplices: + Xe: list[float | None] = [] + Ye: list[float | None] = [] + Ze: list[float | None] = [] + for simplex in tri.simplices: for s in itertools.combinations(simplex, 2): Xe += [vertices[i][0] for i in s] + [None] Ye += [vertices[i][1] for i in s] + [None] @@ -1174,7 +1310,7 @@ def plot_3D(self, with_triangulation=False, return_fig=False): ) Xn, Yn, Zn = zip(*vertices) - colors = [self.data[p] for p in self.tri.vertices] + colors = [self.data[p] for p in vertices] marker = { "symbol": "circle", "size": 3, @@ -1215,7 +1351,9 @@ def plot_3D(self, with_triangulation=False, return_fig=False): return fig if return_fig else plotly.offline.iplot(fig) - def _get_iso(self, level=0.0, which="surface"): + def _get_iso( + self, level: float = 0.0, which: Literal["line", "surface"] = "surface" + ) -> tuple[list[_Array], list[list[int]]]: if which == "surface": if self.ndim != 3 or self.vdim != 1: raise Exception( @@ -1231,15 +1369,17 @@ def _get_iso(self, level=0.0, which="surface"): get_surface = False get_line = True - vertices = [] # index -> (x,y,z) - faces_or_lines = [] # tuple of indices of the corner points + vertices: list[_Array] = [] # index -> (x,y,z) + faces_or_lines: list[list[int]] = [] # indices of the corner points + tri = cast(TriangulationProtocol, self.tri) + data = cast("Mapping[_Point, float]", self.data) # scalar output checked above @functools.lru_cache - def _get_vertex_index(a, b): - vertex_a = self.tri.vertices[a] - vertex_b = self.tri.vertices[b] - value_a = self.data[vertex_a] - value_b = self.data[vertex_b] + def _get_vertex_index(a: int, b: int) -> int: + vertex_a = tri.vertices[a] + vertex_b = tri.vertices[b] + value_a = data[vertex_a] + value_b = data[vertex_b] da = abs(value_a - level) db = abs(value_b - level) @@ -1251,11 +1391,11 @@ def _get_vertex_index(a, b): vertices.append(new_pt) return new_index - for simplex in self.tri.simplices: - plane_or_line = [] + for simplex in tri.simplices: + plane_or_line: list[int] = [] for a, b in itertools.combinations(simplex, 2): - va = self.data[self.tri.vertices[a]] - vb = self.data[self.tri.vertices[b]] + va = data[tri.vertices[a]] + vb = data[tri.vertices[b]] if min(va, vb) < level <= max(va, vb): vi = _get_vertex_index(a, b) should_add = True @@ -1274,8 +1414,8 @@ def _get_vertex_index(a, b): faces_or_lines.append(plane_or_line) if len(faces_or_lines) == 0: - r_min = min(self.data[v] for v in self.tri.vertices) - r_max = max(self.data[v] for v in self.tri.vertices) + r_min = min(data[v] for v in tri.vertices) + r_max = max(data[v] for v in tri.vertices) raise ValueError( f"Could not draw isosurface for level={level}, as" @@ -1285,7 +1425,12 @@ def _get_vertex_index(a, b): return vertices, faces_or_lines - def plot_isoline(self, level=0.0, n=None, tri_alpha=0): + def plot_isoline( + self, + level: float | Iterable[float] = 0.0, + n: int | None = None, + tri_alpha: float = 0, + ) -> Overlay | Path: """Plot the isoline at a specific level, only works in 2D. Parameters @@ -1322,7 +1467,7 @@ def plot_isoline(self, level=0.0, n=None, tri_alpha=0): contour = hv.Path(paths).opts(color="black") return plot * contour - def plot_isosurface(self, level=0.0, hull_opacity=0.2): + def plot_isosurface(self, level: float = 0.0, hull_opacity: float = 0.2) -> None: """Plots a linearly interpolated isosurface. This is the 3D analog of an isoline. Does *not* work with the @@ -1366,21 +1511,20 @@ def plot_isosurface(self, level=0.0, hull_opacity=0.2): hull_mesh = self._get_hull_mesh(opacity=hull_opacity) return plotly.offline.iplot([isosurface, hull_mesh]) - def _get_hull_mesh(self, opacity=0.2): + def _get_hull_mesh(self, opacity: float = 0.2) -> Mesh3d: plotly = ensure_plotly() hull = scipy.spatial.ConvexHull(self._bounds_points) # Find the colors of each plane, giving triangles which are coplanar # the same color, such that a square face has the same color. - color_dict = {} + color_dict: dict[_Simplex, tuple[int, ...]] = {} - def _get_plane_color(simplex): + def _get_plane_color(simplex: Iterable[int]) -> tuple[int, ...]: simplex = tuple(simplex) # If the volume of the two triangles combined is zero then they # belong to the same plane. for simplex_key, color in color_dict.items(): - points = [hull.points[i] for i in set(simplex_key + simplex)] - points = np.array(points) + points = np.array([hull.points[i] for i in set(simplex_key + simplex)]) if np.linalg.matrix_rank(points[1:] - points[0]) < 3: return color if scipy.spatial.ConvexHull(points).volume < 1e-5: @@ -1411,9 +1555,9 @@ def _get_plane_color(simplex): lighting=lighting, ) - def _get_data(self): + def _get_data(self) -> dict[str, Any]: return deepcopy(self.__dict__) - def _set_data(self, state): + def _set_data(self, state: Mapping[str, Any]) -> None: for k, v in state.items(): setattr(self, k, v) diff --git a/adaptive/learner/sequence_learner.py b/adaptive/learner/sequence_learner.py index 2209ff87..65c940fa 100644 --- a/adaptive/learner/sequence_learner.py +++ b/adaptive/learner/sequence_learner.py @@ -1,13 +1,13 @@ from __future__ import annotations from copy import copy -from typing import TYPE_CHECKING, Any, TypeAlias +from typing import TYPE_CHECKING, Any, Self, TypeAlias, cast import cloudpickle +import numpy as np from sortedcontainers import SortedDict, SortedSet from adaptive.learner.base_learner import BaseLearner -from adaptive.types import Int from adaptive.utils import ( assign_defaults, cache_latest, @@ -15,7 +15,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable, Sequence + from collections.abc import Callable, MutableSet, Sequence try: import pandas @@ -26,7 +26,9 @@ with_pandas = False -PointType: TypeAlias = tuple[Int, Any] +# DataFrames can supply NumPy integer indices even though Sequence specifies int. +_Index: TypeAlias = int | np.integer[Any] +PointType: TypeAlias = tuple[_Index, Any] class _IgnoreFirstArgument: @@ -39,18 +41,18 @@ class _IgnoreFirstArgument: pickable. """ - def __init__(self, function): + def __init__(self, function: Callable[..., Any]) -> None: self.function = function - def __call__(self, index_point: PointType, *args, **kwargs): + def __call__(self, index_point: PointType, *args: Any, **kwargs: Any) -> Any: index, point = index_point return self.function(point, *args, **kwargs) - def __getstate__(self): + def __getstate__(self) -> Callable[..., Any]: return self.function - def __setstate__(self, function): - self.__init__(function) + def __setstate__(self, function: Callable[..., Any]) -> None: + type(self).__init__(self, function) class SequenceLearner(BaseLearner): @@ -80,25 +82,28 @@ class SequenceLearner(BaseLearner): the added benefit of having results in the local kernel already. """ + data: dict[_Index, Any] + pending_points: set[_Index] + def __init__( self, function: Callable[[Any], Any], sequence: Sequence[Any], - ): + ) -> None: self._original_function = function self.function = _IgnoreFirstArgument(function) # prefer range(len(...)) over enumerate to avoid slowdowns # when passing lazy sequences indices = range(len(sequence)) - self._to_do_indices = SortedSet(indices) + self._to_do_indices: MutableSet[_Index] = SortedSet(indices) self._ntotal = len(sequence) self.sequence = copy(sequence) self.data = SortedDict() self.pending_points = set() - def new(self) -> SequenceLearner: + def new(self) -> Self: """Return a new `~adaptive.SequenceLearner` without the data.""" - return SequenceLearner(self._original_function, self.sequence) + return cast(Self, SequenceLearner(self._original_function, self.sequence)) def ask( self, n: int, tell_pending: bool = True @@ -109,7 +114,7 @@ def ask( for index in self._to_do_indices: if len(points) >= n: break - point = self.sequence[index] + point = self.sequence[cast(int, index)] indices.append(index) points.append((index, point)) loss_improvements.append(1 / self._ntotal) @@ -154,10 +159,10 @@ 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] + def to_dataframe( self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -200,13 +205,15 @@ def to_dataframe( # type: ignore[override] raise ImportError("pandas is not installed.") import pandas as pd + indices: Sequence[_Index] + ys: Sequence[Any] if full_sequence: indices = list(range(len(self.sequence))) sequence = list(self.sequence) ys = [self.data.get(i, pd.NA) for i in indices] else: - indices, ys = zip(*self.data.items()) if self.data else ([], []) # type: ignore[assignment] - sequence = [self.sequence[i] for i in indices] + indices, ys = zip(*self.data.items()) if self.data else ([], []) + sequence = [self.sequence[cast(int, i)] for i in indices] df = pandas.DataFrame(indices, columns=[index_name]) df[x_name] = sequence @@ -217,7 +224,7 @@ def to_dataframe( # type: ignore[override] assign_defaults(self._original_function, df, function_prefix) return df - def load_dataframe( # type: ignore[override] + def load_dataframe( self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -227,7 +234,7 @@ def load_dataframe( # type: ignore[override] y_name: str = "y", *, full_sequence: bool = False, - ): + ) -> None: """Load data from a `pandas.DataFrame`. If ``with_default_function_args`` is True, then ``learner.function``'s @@ -273,25 +280,26 @@ def load_dataframe( # type: ignore[override] self._original_function, df, function_prefix ) - def _get_data(self) -> dict[int, Any]: + def _get_data(self) -> dict[_Index, Any]: return self.data - def _set_data(self, data: dict[int, Any]) -> None: + def _set_data(self, data: dict[_Index, Any]) -> None: if data: indices, values = zip(*data.items()) # the points aren't used by tell, so we can safely pass None points = [(i, None) for i in indices] self.tell_many(points, values) - def __getstate__(self): + def __getstate__(self) -> tuple[bytes, Sequence[Any], dict[_Index, Any]]: return ( cloudpickle.dumps(self._original_function), self.sequence, self._get_data(), ) - def __setstate__(self, state): - function, sequence, data = state - function = cloudpickle.loads(function) - self.__init__(function, sequence) + def __setstate__( + self, state: tuple[bytes, Sequence[Any], dict[_Index, Any]] + ) -> None: + pickled_function, sequence, data = state + type(self).__init__(self, cloudpickle.loads(pickled_function), sequence) self._set_data(data) diff --git a/adaptive/learner/triangulation.py b/adaptive/learner/triangulation.py index 8cf37724..559df235 100644 --- a/adaptive/learner/triangulation.py +++ b/adaptive/learner/triangulation.py @@ -1,9 +1,13 @@ +from __future__ import annotations + from collections import Counter -from collections.abc import Iterable, Sized +from collections.abc import Iterable, Iterator, Sequence, Sized from itertools import chain, combinations from math import factorial, sqrt +from typing import Any, TypeAlias, overload import numpy as np +import numpy.typing as npt import scipy.spatial from numpy import abs as np_abs from numpy import ( @@ -23,8 +27,16 @@ from numpy.linalg import det as ndet from numpy.linalg import matrix_rank, norm, slogdet, solve +_Point: TypeAlias = tuple[float, ...] +_PointLike: TypeAlias = Sequence[float] | npt.NDArray[Any] +_PointsLike: TypeAlias = Sequence[_PointLike] | npt.NDArray[Any] +_Simplex: TypeAlias = tuple[int, ...] +_SimplexSet: TypeAlias = set[_Simplex] +_SimplexLike: TypeAlias = Sequence[int] | npt.NDArray[np.integer[Any]] +_Circle: TypeAlias = tuple[_Point, float] + -def fast_norm(v): +def fast_norm(v: _PointLike) -> float: """Take the vector norm for len 2, 3 vectors. Defaults to a square root of the dot product for larger vectors. @@ -42,7 +54,9 @@ def fast_norm(v): return sqrt(dot(v, v)) -def fast_2d_point_in_simplex(point, simplex, eps=1e-8): +def fast_2d_point_in_simplex( + point: _PointLike, simplex: _PointsLike, eps: float = 1e-8 +) -> bool | np.bool_: (p0x, p0y), (p1x, p1y), (p2x, p2y) = simplex px, py = point @@ -56,7 +70,9 @@ def fast_2d_point_in_simplex(point, simplex, eps=1e-8): return (t >= -eps) and (s + t <= 1 + eps) -def point_in_simplex(point, simplex, eps=1e-8): +def point_in_simplex( + point: _PointLike, simplex: _PointsLike, eps: float = 1e-8 +) -> bool | np.bool_: if len(point) == 2: return fast_2d_point_in_simplex(point, simplex, eps) @@ -67,7 +83,7 @@ def point_in_simplex(point, simplex, eps=1e-8): return all(alpha > -eps) and sum(alpha) < 1 + eps -def fast_2d_circumcircle(points): +def fast_2d_circumcircle(points: _PointsLike) -> _Circle: """Compute the center and radius of the circumscribed circle of a triangle Parameters @@ -103,7 +119,7 @@ def fast_2d_circumcircle(points): return (x + points[0][0], y + points[0][1]), radius -def fast_3d_circumcircle(points): +def fast_3d_circumcircle(points: _PointsLike) -> _Circle: """Compute the center and radius of the circumscribed sphere of a simplex. Parameters @@ -143,7 +159,7 @@ def fast_3d_circumcircle(points): return center, radius -def fast_det(matrix): +def fast_det(matrix: _PointsLike) -> float: matrix = asarray(matrix, dtype=float) if matrix.shape == (2, 2): return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1] @@ -154,7 +170,7 @@ def fast_det(matrix): return ndet(matrix) -def circumsphere(pts): +def circumsphere(pts: _PointsLike) -> _Circle: """Compute the center and radius of a N dimension sphere which touches each point in pts. Parameters @@ -202,7 +218,7 @@ def circumsphere(pts): return tuple(center), radius -def orientation(face, origin): +def orientation(face: _PointsLike, origin: _PointLike) -> float: """Compute the orientation of the face with respect to a point, origin. Parameters @@ -228,11 +244,11 @@ def orientation(face, origin): return sign -def is_iterable_and_sized(obj): +def is_iterable_and_sized(obj: object) -> bool: return isinstance(obj, Iterable) and isinstance(obj, Sized) -def simplex_volume_in_embedding(vertices) -> float: +def simplex_volume_in_embedding(vertices: _PointsLike) -> float: """Calculate the volume of a simplex in a higher dimensional embedding. That is: dim > len(vertices) - 1. For example if you would like to know the surface area of a triangle in a 3d space. @@ -315,7 +331,7 @@ class Triangulation: or more simplices in the """ - def __init__(self, coords): + def __init__(self, coords: _PointsLike) -> None: if not is_iterable_and_sized(coords): raise TypeError("Please provide a 2-dimensional list of points") coords = list(coords) @@ -335,45 +351,61 @@ def __init__(self, coords): if len(coords) < dim + 1: raise ValueError("Please provide at least one simplex") - coords = list(map(tuple, coords)) - vectors = subtract(coords[1:], coords[0]) + points = list(map(tuple, coords)) + vectors = subtract(points[1:], points[0]) if matrix_rank(vectors) < dim: raise ValueError( "Initial simplex has zero volumes (the points are linearly dependent)" ) - self.vertices = list(coords) - self.simplices = set() + self.vertices: list[_Point] = list(points) + self.simplices: _SimplexSet = set() # initialise empty set for each vertex - self.vertex_to_simplices = [set() for _ in coords] + self.vertex_to_simplices: list[_SimplexSet] = [set() for _ in points] # find a Delaunay triangulation to start with, then we will throw it # away and continue with our own algorithm - initial_tri = scipy.spatial.Delaunay(coords) + initial_tri = scipy.spatial.Delaunay(points) for simplex in initial_tri.simplices: self.add_simplex(simplex) - def delete_simplex(self, simplex): + def delete_simplex(self, simplex: Iterable[int]) -> None: simplex = tuple(sorted(simplex)) self.simplices.remove(simplex) for vertex in simplex: self.vertex_to_simplices[vertex].remove(simplex) - def add_simplex(self, simplex): + def add_simplex(self, simplex: Iterable[int]) -> None: simplex = tuple(sorted(simplex)) self.simplices.add(simplex) for vertex in simplex: self.vertex_to_simplices[vertex].add(simplex) - def get_vertices(self, indices): + @overload + def get_vertices(self, indices: Iterable[int]) -> list[_Point]: ... + + @overload + def get_vertices(self, indices: Iterable[int | None]) -> list[_Point | None]: ... + + def get_vertices( + self, indices: Iterable[int | None] + ) -> list[_Point] | list[_Point | None]: return [self.get_vertex(i) for i in indices] - def get_vertex(self, index): + @overload + def get_vertex(self, index: int) -> _Point: ... + + @overload + def get_vertex(self, index: None) -> None: ... + + def get_vertex(self, index: int | None) -> _Point | None: if index is None: return None return self.vertices[index] - def get_reduced_simplex(self, point, simplex, eps=1e-8) -> list: + def get_reduced_simplex( + self, point: _PointLike, simplex: _SimplexLike, eps: float = 1e-8 + ) -> list[int]: """Check whether vertex lies within a simplex. Returns @@ -398,11 +430,13 @@ def get_reduced_simplex(self, point, simplex, eps=1e-8) -> list: return [simplex[i] for i in result] - def point_in_simplex(self, point, simplex, eps=1e-8): + def point_in_simplex( + self, point: _PointLike, simplex: Iterable[int], eps: float = 1e-8 + ) -> bool | np.bool_: vertices = self.get_vertices(simplex) return point_in_simplex(point, vertices, eps) - def locate_point(self, point): + def locate_point(self, point: _PointLike) -> _Simplex: """Find to which simplex the point belongs. Return indices of the simplex containing the point. @@ -414,10 +448,15 @@ def locate_point(self, point): return () @property - def dim(self): + def dim(self) -> int: return len(self.vertices[0]) - def faces(self, dim=None, simplices=None, vertices=None): + def faces( + self, + dim: int | None = None, + simplices: Iterable[Iterable[int]] | None = None, + vertices: Iterable[int] | None = None, + ) -> Iterator[_Simplex]: """Iterator over faces of a simplex or vertex sequence.""" if dim is None: dim = self.dim @@ -438,11 +477,11 @@ def faces(self, dim=None, simplices=None, vertices=None): else: return faces - def containing(self, face): + def containing(self, face: Iterable[int]) -> _SimplexSet: """Simplices containing a face.""" return set.intersection(*(self.vertex_to_simplices[i] for i in face)) - def _extend_hull(self, new_vertex, eps=1e-8): + def _extend_hull(self, new_vertex: _Point, eps: float = 1e-8) -> _SimplexSet: # count multiplicities in order to get all hull faces multiplicities = Counter(face for face in self.faces()) hull_faces = [face for face, count in multiplicities.items() if count == 1] @@ -482,7 +521,9 @@ def _extend_hull(self, new_vertex, eps=1e-8): return new_simplices - def circumscribed_circle(self, simplex, transform): + def circumscribed_circle( + self, simplex: Iterable[int], transform: _PointsLike + ) -> _Circle: """Compute the center and radius of the circumscribed circle of a simplex. Parameters @@ -498,7 +539,9 @@ def circumscribed_circle(self, simplex, transform): pts = dot(self.get_vertices(simplex), transform) return circumsphere(pts) - def point_in_cicumcircle(self, pt_index, simplex, transform): + def point_in_cicumcircle( + self, pt_index: int, simplex: Iterable[int], transform: _PointsLike + ) -> bool | np.bool_: # return self.fast_point_in_circumcircle(pt_index, simplex, transform) eps = 1e-8 @@ -508,10 +551,15 @@ def point_in_cicumcircle(self, pt_index, simplex, transform): return norm(center - pt) < (radius * (1 + eps)) @property - def default_transform(self): + def default_transform(self) -> npt.NDArray[np.float64]: return eye(self.dim) - def bowyer_watson(self, pt_index, containing_simplex=None, transform=None): + def bowyer_watson( + self, + pt_index: int, + containing_simplex: _Simplex | None = None, + transform: _PointsLike | None = None, + ) -> tuple[_SimplexSet, _SimplexSet]: """Modified Bowyer-Watson point adding algorithm. Create a hole in the triangulation around the new point, @@ -529,8 +577,8 @@ def bowyer_watson(self, pt_index, containing_simplex=None, transform=None): new_simplices : set of tuples Simplices that have been added """ - queue = set() - done_simplices = set() + queue: _SimplexSet = set() + done_simplices: _SimplexSet = set() transform = self.default_transform if transform is None else transform @@ -578,10 +626,10 @@ def bowyer_watson(self, pt_index, containing_simplex=None, transform=None): return deleted_simplices, new_simplices - def _simplex_is_almost_flat(self, simplex): + def _simplex_is_almost_flat(self, simplex: Iterable[int]) -> bool | np.bool_: return self._relative_volume(simplex) < 1e-8 - def _relative_volume(self, simplex): + def _relative_volume(self, simplex: Iterable[int]) -> float: """Compute the volume of a simplex divided by the average (Manhattan) distance of its vertices. The advantage of this is that the relative volume is only dependent on the shape of the simplex and not on the @@ -592,7 +640,12 @@ def _relative_volume(self, simplex): average_edge_length = mean(np_abs(vectors)) return self.volume(simplex) / (average_edge_length**self.dim) - def add_point(self, point, simplex=None, transform=None): + def add_point( + self, + point: _PointLike, + simplex: _Simplex | None = None, + transform: _PointsLike | None = None, + ) -> tuple[_SimplexSet, _SimplexSet]: """Add a new vertex and create simplices as appropriate. Parameters @@ -630,10 +683,8 @@ def add_point(self, point, simplex=None, transform=None): if not reduced_simplex: self.vertex_to_simplices.pop() # revert adding vertex raise ValueError("Point lies outside of the specified simplex.") - else: - simplex = reduced_simplex - if len(simplex) == 1: + if len(reduced_simplex) == 1: self.vertex_to_simplices.pop() # revert adding vertex raise ValueError("Point already in triangulation.") else: @@ -641,16 +692,16 @@ def add_point(self, point, simplex=None, transform=None): self.vertices.append(point) return self.bowyer_watson(pt_index, actual_simplex, transform) - def volume(self, simplex): + def volume(self, simplex: Iterable[int]) -> float: prefactor = factorial(self.dim) vertices = array(self.get_vertices(simplex)) vectors = vertices[1:] - vertices[0] return float(abs(fast_det(vectors)) / prefactor) - def volumes(self): + def volumes(self) -> list[float]: return [self.volume(sim) for sim in self.simplices] - def reference_invariant(self): + def reference_invariant(self) -> bool: """vertex_to_simplices and simplices are compatible.""" for vertex in range(len(self.vertices)): if any(vertex not in tri for tri in self.vertex_to_simplices[vertex]): @@ -660,30 +711,32 @@ def reference_invariant(self): return False return True - def vertex_invariant(self, vertex): + def vertex_invariant(self, vertex: int) -> bool: """Simplices originating from a vertex don't overlap.""" raise NotImplementedError - def get_neighbors_from_vertices(self, simplex): + def get_neighbors_from_vertices(self, simplex: Iterable[int]) -> _SimplexSet: return set.union(*[self.vertex_to_simplices[p] for p in simplex]) - def get_face_sharing_neighbors(self, neighbors, simplex): + def get_face_sharing_neighbors( + self, neighbors: Iterable[_Simplex], simplex: Iterable[int] + ) -> _SimplexSet: """Keep only the simplices sharing a whole face with simplex.""" return { simpl for simpl in neighbors if len(set(simpl) & set(simplex)) == self.dim } # they share a face - def get_simplices_attached_to_points(self, indices): + def get_simplices_attached_to_points(self, indices: Iterable[int]) -> _SimplexSet: # Get all simplices that share at least a point with the simplex neighbors = self.get_neighbors_from_vertices(indices) return self.get_face_sharing_neighbors(neighbors, indices) - def get_opposing_vertices(self, simplex): + def get_opposing_vertices(self, simplex: _Simplex) -> tuple[int | None, ...]: if simplex not in self.simplices: raise ValueError("Provided simplex is not part of the triangulation") neighbors = self.get_simplices_attached_to_points(simplex) - def find_opposing_vertex(vertex): + def find_opposing_vertex(vertex: int) -> int | None: # find the simplex: simp = next((x for x in neighbors if vertex not in x), None) if simp is None: @@ -696,7 +749,7 @@ def find_opposing_vertex(vertex): return result @property - def hull(self): + def hull(self) -> set[int]: """Compute hull from triangulation. Parameters @@ -720,13 +773,15 @@ def hull(self): hull = {point for face, count in counts.items() if count == 1 for point in face} return hull - def convex_invariant(self, vertex): + def convex_invariant(self, vertex: int) -> bool: """Hull is convex.""" raise NotImplementedError class FakeDelaunay(scipy.spatial.Delaunay): - def __init__(self, vertices, simplices): + def __init__( + self, vertices: _PointsLike, simplices: Sequence[_Simplex] | _SimplexSet + ) -> None: """ Throw in a Triangulation object, and receive a brandnew scipy.spatial.Delaunay @@ -754,7 +809,7 @@ def __init__(self, vertices, simplices): # now the hard part: finding the neighbours self.neighbors = -np.ones_like(self.simplices) # set all to -1 - faces_dict = {} + faces_dict: dict[_Simplex, tuple[int, int]] = {} for n, simplex in enumerate(self.simplices): simplex = tuple(simplex) for i, _point in enumerate(simplex): diff --git a/adaptive/learner/triangulation_backend.py b/adaptive/learner/triangulation_backend.py index 1ceae0f3..07a4efc8 100644 --- a/adaptive/learner/triangulation_backend.py +++ b/adaptive/learner/triangulation_backend.py @@ -25,6 +25,88 @@ from __future__ import annotations import os +from collections.abc import Callable, Iterable, Iterator +from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, TypeVar, cast, overload + +import numpy as np +import numpy.typing as npt + +from adaptive.learner.triangulation import ( + _Point, + _PointLike, + _PointsLike, + _Simplex, + _SimplexSet, +) + +_T_co = TypeVar("_T_co", covariant=True) + + +class _Indexable(Protocol[_T_co]): + """A read-only view of a Python list or a Rust vertex proxy.""" + + def __getitem__(self, index: int, /) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __len__(self) -> int: ... + + +class _SimplicesProxy(Protocol): + """The set operations the learners use on the Rust simplices proxy.""" + + def __contains__(self, simplex: _Simplex, /) -> bool: ... + def __rsub__(self, other: _SimplexSet, /) -> _SimplexSet: ... + def __iter__(self) -> Iterator[_Simplex]: ... + def __len__(self) -> int: ... + + +class TriangulationProtocol(Protocol): + """The triangulation interface shared by the learners' backends.""" + + def __init__(self, coords: _PointsLike) -> None: ... + + @property + def vertices(self) -> _Indexable[_Point]: ... + @property + def simplices(self) -> _SimplexSet | _SimplicesProxy: ... + @property + def vertex_to_simplices(self) -> _Indexable[_SimplexSet]: ... + @property + def dim(self) -> int: ... + @property + def hull(self) -> set[int]: ... + + @overload + def get_vertices(self, indices: Iterable[int]) -> list[_Point]: ... + @overload + def get_vertices(self, indices: Iterable[int | None]) -> list[_Point | None]: ... + def locate_point(self, point: _PointLike) -> _Simplex: ... + def point_in_simplex( + self, point: _PointLike, simplex: Iterable[int], eps: float = 1e-8 + ) -> bool | np.bool_: ... + def add_point( + self, + point: _PointLike, + simplex: _Simplex | None = None, + transform: _PointsLike | None = None, + ) -> tuple[_SimplexSet, _SimplexSet]: ... + def volume(self, simplex: Iterable[int]) -> float: ... + def volumes(self) -> list[float]: ... + def get_opposing_vertices(self, simplex: _Simplex) -> tuple[int | None, ...]: ... + def get_simplices_attached_to_points( + self, indices: Iterable[int] + ) -> _SimplexSet: ... + + +class _BatchedTriangulation(TriangulationProtocol, Protocol): + """Optional accelerated query; callers must first check for it.""" + + def simplices_containing( + self, point: _PointLike, /, simplex: _Simplex | None = None + ) -> list[_Simplex]: ... + + +_TriangulationClass: TypeAlias = type[TriangulationProtocol] +_TriangulationType = TypeVar("_TriangulationType", bound=TriangulationProtocol) # Minimal version that is a complete drop-in for the learners: includes the # degenerate-simplex fix for curvature losses, plus the batched @@ -43,7 +125,7 @@ def _rust_version() -> tuple[int, ...] | None: return tuple(int(part) for part in version.split(".")[:3] if part.isdigit()) -def _import_rust_triangulation(): +def _import_rust_triangulation() -> _TriangulationClass: """Import the Rust `Triangulation`, raising a helpful `ImportError`.""" version = _rust_version() if version is None: @@ -61,7 +143,9 @@ def _import_rust_triangulation(): ) from adaptive_triangulation import Triangulation - return Triangulation + # The Rust stubs omit the neighbor-query methods and the None overload + # of get_vertices; the extension implements all of them. + return cast(_TriangulationClass, Triangulation) def _select_backend() -> str: @@ -81,7 +165,19 @@ def _select_backend() -> str: return backend -def resolve_triangulation_class(backend="auto"): +@overload +def resolve_triangulation_class( + backend: type[_TriangulationType], +) -> type[_TriangulationType]: ... + + +@overload +def resolve_triangulation_class(backend: str = "auto") -> _TriangulationClass: ... + + +def resolve_triangulation_class( + backend: str | _TriangulationClass = "auto", +) -> _TriangulationClass: """Return the `Triangulation` class to use for *backend*. Parameters @@ -109,9 +205,12 @@ def resolve_triangulation_class(backend="auto"): TRIANGULATION_BACKEND: str = _select_backend() -if TRIANGULATION_BACKEND == "rust": - from adaptive_triangulation import ( - Triangulation, +Triangulation: _TriangulationClass +rust_default_loss: Callable[[npt.NDArray[Any], npt.NDArray[Any], float], float] | None + +if TYPE_CHECKING or TRIANGULATION_BACKEND != "rust": + # Both backends implement these geometric operations. + from adaptive.learner.triangulation import ( circumsphere, fast_2d_circumcircle, fast_2d_point_in_simplex, @@ -122,14 +221,8 @@ def resolve_triangulation_class(backend="auto"): simplex_volume_in_embedding, ) - # The Rust implementation of `adaptive.learner.learnerND.default_loss`, - # which `LearnerND` prefers when no loss is given. Defined here (rather - # than re-exporting the Python one) to avoid a circular import with - # `learnerND`; ``None`` means "use the pure-Python default". - from adaptive_triangulation import default_loss as rust_default_loss else: - from adaptive.learner.triangulation import ( - Triangulation, + from adaptive_triangulation import ( circumsphere, fast_2d_circumcircle, fast_2d_point_in_simplex, @@ -140,6 +233,23 @@ def resolve_triangulation_class(backend="auto"): simplex_volume_in_embedding, ) +if TRIANGULATION_BACKEND == "rust": + from adaptive_triangulation import Triangulation as _RustTriangulation + + Triangulation = cast(_TriangulationClass, _RustTriangulation) + + # The Rust implementation of `adaptive.learner.learnerND.default_loss`, + # which `LearnerND` prefers when no loss is given. Defined here (rather + # than re-exporting the Python one) to avoid a circular import with + # `learnerND`; ``None`` means "use the pure-Python default". + from adaptive_triangulation import default_loss as _rust_default_loss + + rust_default_loss = _rust_default_loss +else: + from adaptive.learner.triangulation import Triangulation as _PythonTriangulation + + Triangulation = _PythonTriangulation + rust_default_loss = None __all__ = [ diff --git a/adaptive/tests/algorithm_4.py b/adaptive/tests/algorithm_4.py index 8741fdc5..7a4d5a8c 100644 --- a/adaptive/tests/algorithm_4.py +++ b/adaptive/tests/algorithm_4.py @@ -5,13 +5,12 @@ from collections import defaultdict from collections.abc import Callable from fractions import Fraction +from typing import cast import numpy as np from numpy.testing import assert_allclose from scipy.linalg import inv, norm -from adaptive.types import Real - eps = np.spacing(1) @@ -234,18 +233,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 @@ -273,11 +272,11 @@ def calc_igral_and_err(self, c_old: np.ndarray) -> float: c_diff = np.zeros(max(len(c_old), len(c_new))) c_diff[: len(c_old)] = c_old c_diff[: len(c_new)] -= c_new - c_diff = norm(c_diff) + error = cast(float, norm(c_diff)) w = self.b - self.a self.igral = w * c_new[0] * sqrt_one_half - self.err = w * c_diff - return c_diff + self.err = w * error + return error def split( self, f: Callable @@ -306,7 +305,7 @@ def split( return ivals, nr_points - def refine(self, f: Callable) -> tuple[np.ndarray, bool, int]: + def refine(self, f: Callable) -> tuple[np.ndarray, bool | np.bool_, int]: """Increase degree of interval.""" self.depth = depth = self.depth + 1 points = self.points() @@ -360,6 +359,7 @@ def algorithm_4( err_excess: float = 0 i_max: int = 0 + split: bool | np.bool_ for _ in range(N_loops): if ivals[i_max].depth == 3: split = True @@ -451,7 +451,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 cast("float | np.ndarray", abs(x - beta)) ** alpha def F63(x, alpha, beta): @@ -459,7 +459,7 @@ def F63(x, alpha, beta): def fdiv(x: float | np.ndarray) -> float | np.ndarray: - return abs(x - 0.987654321) ** -1.1 + return cast("float | np.ndarray", abs(x - 0.987654321)) ** -1.1 def f_one_with_nan(x): diff --git a/adaptive/types.py b/adaptive/types.py index e2869d46..cc07c289 100644 --- a/adaptive/types.py +++ b/adaptive/types.py @@ -1,3 +1,5 @@ +"""Numeric type aliases retained for backwards compatibility.""" + from typing import TypeAlias import numpy as np From 122d03374e7c6780869207697348ca61dd906972 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 16:46:22 -0800 Subject: [PATCH 3/9] Ship py.typed and check adaptive with ty and strict mypy Check installed scientific dependencies in CI and verify public generic subscriptions and the legacy numeric aliases. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- .github/workflows/typecheck.yml | 26 ++++++++++++++++ adaptive/py.typed | 0 adaptive/tests/test_learners.py | 2 +- adaptive/tests/test_typing.py | 53 +++++++++++++++++++++++++++++++++ pyproject.toml | 25 ++++++++++++++-- 5 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/typecheck.yml create mode 100644 adaptive/py.typed create mode 100644 adaptive/tests/test_typing.py diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml new file mode 100644 index 00000000..dea771ba --- /dev/null +++ b/.github/workflows/typecheck.yml @@ -0,0 +1,26 @@ +name: Type checking + +on: + pull_request: + push: + branches: [main] + +jobs: + typecheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: Install uv + uses: astral-sh/setup-uv@v6 + - name: Install dependencies and type checkers + run: | + uv venv --python 3.13 + uv pip install '.[test,other,notebook]' scipy-stubs pandas-stubs ty mypy==2.4.1 + - name: Run ty + run: .venv/bin/ty check --error-on-warning --python .venv adaptive + - name: Run mypy + run: .venv/bin/mypy adaptive diff --git a/adaptive/py.typed b/adaptive/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/adaptive/tests/test_learners.py b/adaptive/tests/test_learners.py index 71189160..3da985c7 100644 --- a/adaptive/tests/test_learners.py +++ b/adaptive/tests/test_learners.py @@ -545,7 +545,7 @@ def test_learner_performance_is_invariant_under_scaling( l_kwargs = dict(learner_kwargs) bounds = xscale * np.array(l_kwargs["bounds"]) - bounds = tuple((bounds).tolist()) # to satisfy typeguard tests + bounds = tuple((bounds).tolist()) l_kwargs["bounds"] = bounds def scale_x(x): diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py new file mode 100644 index 00000000..2d0c2c29 --- /dev/null +++ b/adaptive/tests/test_typing.py @@ -0,0 +1,53 @@ +import inspect +from importlib.resources import files +from typing import TYPE_CHECKING, assert_type, get_args, get_origin + +import numpy as np +import pytest + +from adaptive import AsyncRunner, BalancingLearner, BlockingRunner, DataSaver, Learner1D +from adaptive import types as legacy_types +from adaptive.learner.base_learner import uses_nth_neighbors +from adaptive.runner import BaseRunner, Runner + +if TYPE_CHECKING: + + def check_learner_inference(learner: Learner1D) -> None: + assert_type(Runner(learner).learner, Learner1D) + assert_type(BlockingRunner(learner).learner, Learner1D) + assert_type(DataSaver(learner, lambda data: data).learner, Learner1D) + assert_type(BalancingLearner([learner]).learners[0], Learner1D) + + +def test_py_typed_marker() -> None: + assert files("adaptive").joinpath("py.typed").is_file() + + +def test_legacy_numeric_aliases(): + assert legacy_types.__all__ == ["Float", "Bool", "Int", "Real"] + assert legacy_types.Float == float | np.float64 + assert legacy_types.Bool == bool | np.bool_ + assert legacy_types.Int == int | np.int_ + assert legacy_types.Real == legacy_types.Float | legacy_types.Int + + +@pytest.mark.parametrize( + "cls", + [BaseRunner, Runner, AsyncRunner, BlockingRunner, DataSaver, BalancingLearner], +) +def test_runtime_subscription(cls): + specialized = cls[Learner1D] + assert get_origin(specialized) is cls + assert get_args(specialized) == (Learner1D,) + + +def test_uses_nth_neighbors_preserves_signature_and_identity() -> None: + def loss(xs: list[float], *, scale: float = 1) -> float: + """Scale the width.""" + return scale * (xs[-1] - xs[0]) + + annotated = uses_nth_neighbors(2)(loss) + assert annotated is loss + assert annotated.nth_neighbors == 2 + assert inspect.signature(annotated) == inspect.signature(loss) + assert annotated([1, 3], scale=2) == 4 diff --git a/pyproject.toml b/pyproject.toml index 5f3e672c..bc9dc6af 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -91,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=" @@ -114,6 +117,26 @@ output = ".coverage.xml" [tool.mypy] ignore_missing_imports = true python_version = "3.11" +check_untyped_defs = true +disallow_untyped_defs = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[[tool.mypy.overrides]] +module = ["adaptive.tests.*"] +disallow_untyped_defs = false +check_untyped_defs = false + +[tool.ty.environment] +python-version = "3.11" + +[tool.ty.src] +exclude = ["adaptive/tests/**"] + +[tool.ty.analysis] +respect-type-ignore-comments = true +allowed-unresolved-imports = ["adaptive_triangulation", "mpi4py.**", "uvloop"] [tool.ruff] line-length = 88 @@ -123,10 +146,8 @@ 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} "D402", # First line should not be the function's signature "PLW0603", # Using the global statement to update `X` is discouraged "D401", # First line of docstring should be in imperative mood From 96f60919ebe24d5a3eecb8fa2e2f902a4110ffbc Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 17:08:16 -0800 Subject: [PATCH 4/9] Preserve downstream typing and runtime annotation compatibility Scope the mypy hook to the package, type learner constructors and new() honestly, and retain the legacy BaseLearner contract. Check downstream calls and annotation resolution without loading optional plotting libraries. Keep the downstream fixture outside the package and its runtime coverage measurements. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- .github/workflows/typecheck.yml | 4 +- .pre-commit-config.yaml | 2 +- adaptive/learner/average_learner.py | 39 +++--- adaptive/learner/average_learner1D.py | 56 ++++----- adaptive/learner/balancing_learner.py | 34 +++--- adaptive/learner/base_learner.py | 160 ++++++++++--------------- adaptive/learner/data_saver.py | 19 ++- adaptive/learner/integrator_learner.py | 24 ++-- adaptive/learner/learner1D.py | 87 ++++++-------- adaptive/learner/learner2D.py | 32 ++--- adaptive/learner/learnerND.py | 55 +++++---- adaptive/learner/sequence_learner.py | 23 ++-- adaptive/notebook_integration.py | 35 +++--- adaptive/tests/test_typing.py | 49 +++++++- adaptive/utils.py | 22 ++-- tests/typing_contract.py | 148 +++++++++++++++++++++++ 16 files changed, 479 insertions(+), 310 deletions(-) create mode 100644 tests/typing_contract.py diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index dea771ba..4a417699 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -21,6 +21,6 @@ jobs: uv venv --python 3.13 uv pip install '.[test,other,notebook]' scipy-stubs pandas-stubs ty mypy==2.4.1 - name: Run ty - run: .venv/bin/ty check --error-on-warning --python .venv adaptive + run: .venv/bin/ty check --error-on-warning --python .venv adaptive tests/typing_contract.py - name: Run mypy - run: .venv/bin/mypy adaptive + run: .venv/bin/mypy adaptive tests/typing_contract.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c1c4264b..a6028d09 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,4 +26,4 @@ repos: rev: "v2.4.1" hooks: - id: mypy - exclude: ipynb_filter.py + files: ^adaptive/ diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index d506797c..232f29ac 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -1,13 +1,13 @@ from __future__ import annotations -from collections.abc import Callable from math import sqrt -from typing import TYPE_CHECKING, Any, Self, TypeAlias, cast +from typing import TYPE_CHECKING, Any, TypeAlias, cast import cloudpickle import numpy as np +from numpy.typing import NDArray -from adaptive.learner.base_learner import BaseLearner +from adaptive.learner.base_learner import BaseLearner, _LearningFunction from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import ( assign_defaults, @@ -17,7 +17,8 @@ if TYPE_CHECKING: from holoviews.element import Histogram - from numpy.typing import NDArray +else: + Histogram = Any try: import pandas @@ -61,17 +62,11 @@ class AverageLearner(BaseLearner): data: dict[_Seed, _Sample] pending_points: set[_Seed] - if TYPE_CHECKING: - # Keep this a writable instance attribute at runtime. - @property - def npoints(self) -> int: ... - - @npoints.setter - def npoints(self, value: int) -> None: ... + npoints: int def __init__( self, - function: Callable[[int], _Sample], + function: _LearningFunction[int, _Sample], atol: float | None = None, rtol: float | None = None, min_npoints: int = 2, @@ -85,7 +80,7 @@ def __init__( self.data = {} self.pending_points = set() - self.function: Callable[[int], _Sample] = function + self.function: _LearningFunction[int, _Sample] = function self.atol = atol self.rtol = rtol self.npoints = 0 @@ -94,11 +89,9 @@ def __init__( self.sum_f: _Sample = 0.0 self.sum_f_sq: _Sample = 0.0 - def new(self) -> Self: + def new(self) -> AverageLearner: """Create a copy of `~adaptive.AverageLearner` without the data.""" - return cast( - Self, AverageLearner(self.function, self.atol, self.rtol, self.min_npoints) - ) + return AverageLearner(self.function, self.atol, self.rtol, self.min_npoints) @property def n_requested(self) -> int: @@ -108,7 +101,7 @@ def to_numpy(self) -> NDArray[Any]: """Data as NumPy array of size (npoints, 2) with seeds and values.""" return np.array(sorted(self.data.items())) - def to_dataframe( + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -148,7 +141,7 @@ def to_dataframe( assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -199,7 +192,9 @@ 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: _Seed, value: _Sample) -> None: + def tell( + self, n: _Seed, value: _Sample + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] if n in self.data: # The point has already been added before. return @@ -210,7 +205,9 @@ def tell(self, n: _Seed, value: _Sample) -> None: self.sum_f_sq += value**2 self.npoints += 1 - def tell_pending(self, n: _Seed) -> None: + def tell_pending( + self, n: _Seed + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] self.pending_points.add(n) @property diff --git a/adaptive/learner/average_learner1D.py b/adaptive/learner/average_learner1D.py index 095a722c..5279c3ff 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -3,22 +3,24 @@ import math import sys from collections import defaultdict -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Iterable, Sequence from copy import deepcopy from math import hypot -from typing import TYPE_CHECKING, Any, Self, TypeAlias, cast +from typing import TYPE_CHECKING, Any, TypeAlias, cast import numpy as np import scipy.stats from numpy.typing import NDArray +from adaptive.learner.base_learner import _LearningFunction from adaptive.learner.learner1D import ( Interval, - IntervalLoss, ItemSortedDict, Learner1D, SortedDict, + _Bounds, _get_intervals, + _IntervalLossCallback, _SampleData, _StoredData, ) @@ -34,11 +36,12 @@ with_pandas = False if TYPE_CHECKING: - import holoviews + from holoviews.core import Overlay +else: + Overlay = Any Point: TypeAlias = tuple[int, float] Points: TypeAlias = list[Point] -ScalarIntervalLoss: TypeAlias = Callable[[Sequence[float], Sequence[float]], float] __all__: list[str] = ["AverageLearner1D"] @@ -89,15 +92,15 @@ class AverageLearner1D(Learner1D): # The public sampling interface uses (seed, x) rather than x, while # the inherited interval calculations still use the real coordinate x. if TYPE_CHECKING: - function: Callable[[Point], float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] + function: _LearningFunction[Point, float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] pending_points: set[Point] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] data: dict[float, float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] def __init__( self, - function: Callable[[Point], float], - bounds: tuple[float, float], - loss_per_interval: ScalarIntervalLoss | None = None, + function: _LearningFunction[Point, float], + bounds: _Bounds, + loss_per_interval: _IntervalLossCallback | None = None, delta: float = 0.2, alpha: float = 0.005, neighbor_sampling: float = 0.3, @@ -119,9 +122,9 @@ def __init__( # The shared initializer only stores the function; the loss is # evaluated on scalar means, never on vector-valued observations. super().__init__( - cast("Callable[[float], float]", function), + cast("_LearningFunction[float, float]", function), bounds, - cast("IntervalLoss | None", loss_per_interval), + loss_per_interval, ) self.delta = delta @@ -149,21 +152,18 @@ def __init__( # {xii: error[xii]/min(_distances[xi], _distances[xii], ...} self.rescaled_error = decreasing_dict() - def new(self) -> Self: + def new(self) -> AverageLearner1D: """Create a copy of `~adaptive.AverageLearner1D` without the data.""" - return cast( - "Self", - AverageLearner1D( - self.function, - self.bounds, - self.loss_per_interval, - self.delta, - self.alpha, - self.neighbor_sampling, - self.min_samples, - self.max_samples, - self.min_error, - ), + return AverageLearner1D( + self.function, + self.bounds, + self.loss_per_interval, + self.delta, + self.alpha, + self.neighbor_sampling, + self.min_samples, + self.max_samples, + self.min_error, ) @property @@ -320,8 +320,8 @@ def _ask_for_more_samples(self, x: float, n: int) -> tuple[Points, list[float]]: n_existing = self._number_samples.get(x, 0) points = [(seed + n_existing, x) for seed in range(n)] xl, xr = self.neighbors_combined[x] - loss_left = self.losses_combined.get((xl, x), float("inf")) - loss_right = self.losses_combined.get((x, xr), float("inf")) + loss_left = self.losses_combined.get(cast(Interval, (xl, x)), float("inf")) + loss_right = self.losses_combined.get(cast(Interval, (x, xr)), float("inf")) loss = (loss_left + loss_right) / 2 if math.isinf(loss): loss_improvement = float("inf") @@ -613,7 +613,7 @@ def _set_data(self, data: _StoredData) -> None: for x, samples in cast("_SampleData", data).items(): self.tell_many_at_point(x, samples) - def plot(self) -> holoviews.Overlay: # type: ignore[override] # ty: ignore[incompatible-method-override] + def plot(self) -> Overlay: # type: ignore[override] # ty: ignore[incompatible-method-override] """Returns a plot of the evaluated data with error bars. This is only implemented for scalar functions, i.e., it requires ``vdim=1``. diff --git a/adaptive/learner/balancing_learner.py b/adaptive/learner/balancing_learner.py index 67f7641a..d6aa3d7b 100644 --- a/adaptive/learner/balancing_learner.py +++ b/adaptive/learner/balancing_learner.py @@ -6,14 +6,14 @@ from contextlib import suppress from functools import partial from operator import itemgetter -from typing import TYPE_CHECKING, Any, Generic, Literal, Self, TypeAlias, cast +from os import PathLike +from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, cast from adaptive.learner.base_learner import BaseLearner, LearnerType from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import cache_latest, named_product, restore if TYPE_CHECKING: - from os import PathLike from typing import Protocol, SupportsIndex from holoviews.core import Dimensioned, DynamicMap, HoloMap @@ -25,6 +25,10 @@ def nsamples(self) -> int: ... class _Plottable(Protocol): def plot(self) -> Dimensioned: ... +else: + # Plotting remains optional, including when resolving the annotations. + Dimensioned = DynamicMap = HoloMap = Any + try: import pandas @@ -45,8 +49,7 @@ def dispatch(child_functions: list[Callable[..., Any]], arg: _Point) -> Any: _NamedDimensions: TypeAlias = tuple[Sequence[str], Iterable[tuple[Any, ...]]] CDIMS_TYPE: TypeAlias = Sequence[dict[str, Any]] | _NamedDimensions | None -if TYPE_CHECKING: - _Filename: TypeAlias = str | PathLike[str] +_Filename: TypeAlias = str | PathLike[str] class BalancingLearner(BaseLearner, Generic[LearnerType]): @@ -124,33 +127,30 @@ def __init__( self.strategy: STRATEGY_TYPE = strategy - def new(self) -> Self: + def new(self) -> BalancingLearner[BaseLearner]: """Create a new `BalancingLearner` with the same parameters.""" - return cast( - Self, - BalancingLearner( - [learner.new() for learner in self.learners], - cdims=self._cdims_default, - strategy=self.strategy, - ), + return BalancingLearner( + [learner.new() for learner in self.learners], + cdims=self._cdims_default, + strategy=self.strategy, ) @property - def data(self) -> dict[_Point, Any]: + def data(self) -> dict[_Point, Any]: # ty: ignore[incompatible-property-override] data = {} for i, lrn in enumerate(self.learners): data.update({(i, p): v for p, v in lrn.data.items()}) return data @property - def pending_points(self) -> set[_Point]: + def pending_points(self) -> set[_Point]: # type: ignore[override] # ty: ignore[incompatible-property-override] pending_points: set[_Point] = set() for i, lrn in enumerate(self.learners): pending_points.update({(i, p) for p in lrn.pending_points}) return pending_points @property - def npoints(self) -> int: + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] return sum(lrn.npoints for lrn in self.learners) @property @@ -497,7 +497,7 @@ def from_product( learners.append(learner) return cls(learners, cdims=arguments) - def to_dataframe( + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, index_name: str = "learner_index", **kwargs: Any ) -> pandas.DataFrame: """Return the data as a concatenated `pandas.DataFrame` from child learners. @@ -531,7 +531,7 @@ def to_dataframe( df = pandas.concat(dfs, axis=0, ignore_index=True) return df - def load_dataframe( + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, index_name: str = "learner_index", **kwargs: Any ) -> None: """Load the data from a `pandas.DataFrame` into the child learners. diff --git a/adaptive/learner/base_learner.py b/adaptive/learner/base_learner.py index f98d5758..bd2bb12f 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -1,9 +1,9 @@ from __future__ import annotations import abc -from collections.abc import Callable +from collections.abc import Awaitable, Callable from contextlib import suppress -from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, Self, TypeVar, cast +from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, TypeAlias, TypeVar, cast import cloudpickle @@ -81,6 +81,9 @@ def _wrapped(loss_per_interval: Callable[_P, _R_co]) -> _NeighborLoss[_P, _R_co] DataType = dict[Any, Any] +_Input = TypeVar("_Input") +_Output = TypeVar("_Output") +_LearningFunction: TypeAlias = Callable[[_Input], _Output | Awaitable[_Output]] class BaseLearner(abc.ABC): @@ -106,49 +109,28 @@ class BaseLearner(abc.ABC): function: Callable[..., Any] - if TYPE_CHECKING: - # Subclasses can expose these through attributes or read-only properties. - # Keep runtime attribute-based subclasses working, too. - @property - def data(self) -> DataType: ... + data: Any + pending_points: set[Any] + npoints: int - @property - def pending_points(self) -> set[Any]: ... + def tell(self, x: Any, y: Any) -> None: + """Tell the learner about a single value. - @property - @abc.abstractmethod - def npoints(self) -> int: ... - - # Subclasses need not use these parameter names. Keep accepting the - # historical keywords at runtime on the base implementation. - def tell(self, x: Any, y: Any, /) -> None: ... - - @abc.abstractmethod - def tell_pending(self, x: Any, /) -> None: ... - - @abc.abstractmethod - def _set_data(self, data: Any, /) -> None: ... - - else: - - def tell(self, x: Any, y: Any) -> None: - """Tell the learner about a single value. - - Parameters - ---------- - x : A value from the function domain - y : A value from the function image - """ - self.tell_many([x], [y]) + Parameters + ---------- + x : A value from the function domain + y : A value from the function image + """ + self.tell_many([x], [y]) - @abc.abstractmethod - def tell_pending(self, x: Any) -> None: - """Tell the learner that 'x' has been requested such - that it's not suggested again.""" + @abc.abstractmethod + def tell_pending(self, x: Any) -> None: + """Tell the learner that 'x' has been requested such + that it's not suggested again.""" - @abc.abstractmethod - def _set_data(self, data: Any) -> None: - pass + @abc.abstractmethod + def _set_data(self, data: Any) -> None: + pass def tell_many(self, xs: Any, ys: Any) -> None: """Tell the learner about some values. @@ -196,7 +178,7 @@ def _get_data(self) -> Any: pass @abc.abstractmethod - def new(self) -> Self: + def new(self) -> BaseLearner: """Return a new learner with the same function and parameters.""" pass @@ -239,59 +221,47 @@ def load(self, fname: Any, compress: bool = True) -> None: data = load(fname, compress) self._set_data(data) - if TYPE_CHECKING: - # Each learner defines its own dataframe options and argument order. - @abc.abstractmethod - def to_dataframe(self, *args: Any, **kwargs: Any) -> pandas.DataFrame: ... - - @abc.abstractmethod - def load_dataframe( - self, df: pandas.DataFrame, *args: Any, **kwargs: Any - ) -> None: ... - - else: - - @abc.abstractmethod - def to_dataframe( - self, - with_default_function_args: bool = True, - function_prefix: str = "function.", - **kwargs: Any, - ) -> pandas.DataFrame: - """Return the data as a `pandas.DataFrame`. - - Parameters - ---------- - with_default_function_args : bool, optional - Include the ``learner.function``'s default arguments as a - column, by default True - function_prefix : str, optional - Prefix to the ``learner.function``'s default arguments' names, - by default "function." - x_name : str, optional - Name of the input value, by default "x" - y_name : str, optional - Name of the output value, by default "y" - - Returns - ------- - pandas.DataFrame - """ - - @abc.abstractmethod - def load_dataframe( - self, - df: pandas.DataFrame, - with_default_function_args: bool = True, - function_prefix: str = "function.", - **kwargs: Any, - ) -> None: - """Load data from a `pandas.DataFrame`. - - If ``with_default_function_args`` is True, then ``learner.function``'s - default arguments are set (using `functools.partial`) from the values - in the `pandas.DataFrame`. - """ + @abc.abstractmethod + def to_dataframe( + self, + with_default_function_args: bool = True, + function_prefix: str = "function.", + **kwargs: Any, + ) -> pandas.DataFrame: + """Return the data as a `pandas.DataFrame`. + + Parameters + ---------- + with_default_function_args : bool, optional + Include the ``learner.function``'s default arguments as a + column, by default True + function_prefix : str, optional + Prefix to the ``learner.function``'s default arguments' names, + by default "function." + x_name : str, optional + Name of the input value, by default "x" + y_name : str, optional + Name of the output value, by default "y" + + Returns + ------- + pandas.DataFrame + """ + + @abc.abstractmethod + def load_dataframe( + self, + df: pandas.DataFrame, + with_default_function_args: bool = True, + function_prefix: str = "function.", + **kwargs: Any, + ) -> None: + """Load data from a `pandas.DataFrame`. + + If ``with_default_function_args`` is True, then ``learner.function``'s + default arguments are set (using `functools.partial`) from the values + in the `pandas.DataFrame`. + """ def __getstate__(self) -> Any: return cloudpickle.dumps(self.__dict__) diff --git a/adaptive/learner/data_saver.py b/adaptive/learner/data_saver.py index e0a812c0..d0ce742e 100644 --- a/adaptive/learner/data_saver.py +++ b/adaptive/learner/data_saver.py @@ -3,14 +3,12 @@ import functools from collections import OrderedDict from collections.abc import Callable -from typing import TYPE_CHECKING, Any, Generic, Self, cast +from os import PathLike +from typing import Any, Generic from adaptive.learner.base_learner import BaseLearner, LearnerType from adaptive.utils import copy_docstring_from -if TYPE_CHECKING: - from os import PathLike - try: import pandas @@ -44,20 +42,15 @@ class DataSaver(BaseLearner, Generic[LearnerType]): >>> learner = DataSaver(_learner, arg_picker=itemgetter('y')) """ - if TYPE_CHECKING: - # This attribute is read from the wrapped learner via __getattr__. - @property - def npoints(self) -> int: ... - def __init__(self, learner: LearnerType, arg_picker: Callable[[Any], Any]) -> None: self.learner = learner self.extra_data: OrderedDict[Any, Any] = OrderedDict() self.function = learner.function self.arg_picker = arg_picker - def new(self) -> Self: + def new(self) -> DataSaver[BaseLearner]: """Return a new `DataSaver` with the same `arg_picker` and `learner`.""" - return cast(Self, DataSaver(self.learner.new(), self.arg_picker)) + return DataSaver(self.learner.new(), self.arg_picker) @copy_docstring_from(BaseLearner.ask) def ask(self, *args: Any, **kwargs: Any) -> tuple[list[Any], list[float]]: @@ -75,7 +68,9 @@ def __getattr__(self, attr: str) -> Any: return getattr(self.learner, attr) @copy_docstring_from(BaseLearner.tell) - def tell(self, x: Any, result: Any) -> None: + def tell( + self, x: Any, result: Any + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] y = self.arg_picker(result) self.extra_data[x] = result self.learner.tell(x, y) diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index bf6da370..fa8628b4 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, Iterable, Iterator +from collections.abc import Iterable, Iterator from math import sqrt from operator import attrgetter -from typing import TYPE_CHECKING, Any, Protocol, Self, TypeAlias, cast +from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, cast import cloudpickle import numpy as np @@ -15,7 +15,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, _LearningFunction from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import assign_defaults, cache_latest, restore @@ -34,6 +34,8 @@ class _IntervalSet(Protocol): def __iter__(self) -> Iterator[_Interval]: ... def add(self, value: _Interval, /) -> None: ... def update(self, values: Iterable[_Interval], /) -> None: ... +else: + Path = Any def _downdate( @@ -369,7 +371,7 @@ class IntegratorLearner(BaseLearner): def __init__( self, - function: Callable[[float], float], + function: _LearningFunction[float, float], bounds: tuple[float, float], tol: float, ) -> None: @@ -422,16 +424,18 @@ def __init__( self.add_ival(ival) self.first_ival = ival - def new(self) -> Self: + def new(self) -> IntegratorLearner: """Create a copy without the data.""" - return cast(Self, IntegratorLearner(self.function, self.bounds, self.tol)) + return IntegratorLearner(self.function, self.bounds, self.tol) @property def approximating_intervals(self) -> set[_Interval]: assert self.first_ival.done_leaves is not None return self.first_ival.done_leaves - def tell(self, point: float, value: float) -> None: + def tell( + self, point: float, value: float + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] if point not in self.x_mapping: raise ValueError(f"Point {point} doesn't belong to any interval") self.data[point] = value @@ -561,7 +565,7 @@ def _fill_stack(self) -> list[float]: return self._stack @property - def npoints(self) -> int: + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] """Number of evaluated points.""" return len(self.data) @@ -606,7 +610,7 @@ def to_numpy(self) -> NDArray[np.floating | np.integer]: """Data as NumPy array of size (npoints, 2).""" return np.array(sorted(self.data.items())) - def to_dataframe( + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -646,7 +650,7 @@ def to_dataframe( assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, diff --git a/adaptive/learner/learner1D.py b/adaptive/learner/learner1D.py index 59742183..640db847 100644 --- a/adaptive/learner/learner1D.py +++ b/adaptive/learner/learner1D.py @@ -5,13 +5,17 @@ import math from collections.abc import Callable, Mapping, Sequence from copy import copy, deepcopy -from typing import TYPE_CHECKING, Any, Self, TypeAlias, TypeVar, cast +from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar, cast import cloudpickle import numpy as np from numpy.typing import NDArray -from adaptive.learner.base_learner import BaseLearner, uses_nth_neighbors +from adaptive.learner.base_learner import ( + BaseLearner, + _LearningFunction, + 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 @@ -34,47 +38,20 @@ _Value = TypeVar("_Value") if TYPE_CHECKING: - from collections.abc import Iterator, KeysView, MutableMapping - from typing import overload - - import holoviews + from collections.abc import KeysView - _Default = TypeVar("_Default") + from holoviews.core import Overlay # The sorted mapping libraries are not typed. Their classes extend dict, # but keys() also supports indexing and slicing in sorted order. class _SortedKeys(KeysView[_Key], Sequence[_Key]): ... - class SortedDict(MutableMapping[_Key, _Value]): - def __init__(self, mapping: Mapping[_Key, _Value] = ...) -> None: ... - def __getitem__(self, key: _Key) -> _Value: ... - def __setitem__(self, key: _Key, value: _Value) -> None: ... - def __delitem__(self, key: _Key) -> None: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[_Key]: ... - def __reversed__(self) -> Iterator[_Key]: ... - def keys(self) -> _SortedKeys[_Key]: ... + class SortedDict(dict[_Key, _Value]): + def keys(self) -> _SortedKeys[_Key]: ... # type: ignore[override] # ty: ignore[incompatible-method-override] def bisect_left(self, key: _Key) -> int: ... def index(self, key: _Key) -> int: ... def peekitem(self, index: int = -1) -> tuple[_Key, _Value]: ... - # Lookups can safely miss, including for absent neighbor sentinels. - @overload - def get(self, key: object, default: None = None, /) -> _Value | None: ... - @overload - def get(self, key: object, default: _Value, /) -> _Value: ... - @overload - def get(self, key: object, default: _Default, /) -> _Value | _Default: ... - def get(self, key: object, default: object = None, /) -> object: ... - - @overload - def pop(self, key: _Key, /) -> _Value: ... - @overload - def pop(self, key: object, default: _Value, /) -> _Value: ... - @overload - def pop(self, key: object, default: _Default, /) -> _Value | _Default: ... - def pop(self, key: object, default: object = ..., /) -> object: ... - class ItemSortedDict(SortedDict[_Key, _Value]): def __init__( self, @@ -82,6 +59,8 @@ def __init__( mapping: Mapping[_Key, _Value] = ..., ) -> None: ... else: + Overlay = Any + from sortedcollections.recipes import ItemSortedDict from sortedcontainers.sorteddict import SortedDict @@ -93,6 +72,10 @@ def __init__( _ScaledValue: TypeAlias = float | NDArray[Any] # The bulk tell path can store user-supplied sequences without conversion. Value: TypeAlias = _ScaledValue | Sequence[float] +_Bounds: TypeAlias = Sequence[float] | NDArray[Any] +# Callers may specialize the tuples for their configured neighbor count and +# scalar or vector output; the learner does not know either statically. +_IntervalLossCallback: TypeAlias = Callable[[Any, Any], float] IntervalLoss: TypeAlias = Callable[[Sequence[float], Sequence[_ScaledValue]], float] NeighborLoss: TypeAlias = Callable[ [Sequence[float | None], Sequence[_ScaledValue | None]], float @@ -104,7 +87,7 @@ def __init__( _PickleState: TypeAlias = tuple[ bytes, tuple[float, ...], - IntervalLoss, + _IntervalLossCallback, dict[Interval, float], dict[Interval, float], _StoredData, @@ -333,14 +316,16 @@ class Learner1D(BaseLearner): def __init__( self, - function: Callable[[float], Value], - bounds: tuple[float, float], - loss_per_interval: IntervalLoss | None = None, + function: _LearningFunction[float, Value], + bounds: _Bounds, + loss_per_interval: _IntervalLossCallback | None = None, ) -> None: - self.function: Callable[[float], Value] = function + self.function: _LearningFunction[float, Value] = function self.nth_neighbors: int = getattr(loss_per_interval, "nth_neighbors", 0) - self.loss_per_interval: IntervalLoss = loss_per_interval or default_loss + self.loss_per_interval: _IntervalLossCallback = ( + loss_per_interval or default_loss + ) # When the scale changes by a factor 2, the losses are # recomputed. This is tunable such that we can test @@ -376,11 +361,9 @@ def __init__( self._vdim: int | None = None - def new(self) -> Self: + def new(self) -> Learner1D: """Create a copy of `~adaptive.Learner1D` without the data.""" - return cast( - "Self", Learner1D(self.function, self.bounds, self.loss_per_interval) - ) + return Learner1D(self.function, self.bounds, self.loss_per_interval) @property def vdim(self) -> int: @@ -408,7 +391,7 @@ def to_numpy(self) -> NDArray[Any]: """ return np.array([(x, *np.atleast_1d(y)) for x, y in sorted(self.data.items())]) - def to_dataframe( + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -450,7 +433,7 @@ def to_dataframe( assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -488,7 +471,7 @@ def load_dataframe( ) @property - def npoints(self) -> int: + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] """Number of evaluated points.""" return len(self.data) @@ -577,7 +560,7 @@ def _update_losses(self, x: float, real: bool = True) -> None: a, b = self._find_neighbors(x, self.neighbors_combined) # (a, b) is splitted into (a, x) and (x, b) so if (a, b) exists - self.losses_combined.pop((a, b), None) + self.losses_combined.pop(cast(Interval, (a, b)), None) if real: # We need to update all interpolated losses in the interval @@ -589,7 +572,7 @@ def _update_losses(self, x: float, real: bool = True) -> None: # Since 'x' is in between (x_left, x_right), # we get rid of the interval. - old_interval = (x_left, x_right) + old_interval = cast(Interval, (x_left, x_right)) self.losses.pop(old_interval, None) self.losses_combined.pop(old_interval, None) elif x_left is not None and x_right is not None: @@ -626,9 +609,11 @@ def _update_neighbors(self, x: float, neighbors: NeighborsType) -> None: if x not in neighbors: # The point is new x_left, x_right = self._find_neighbors(x, neighbors) neighbors[x] = [x_left, x_right] - left: list[float | None] = neighbors.get(x_left, [None, None]) + left: list[float | None] = neighbors.get(cast(float, x_left), [None, None]) left[1] = x - right: list[float | None] = neighbors.get(x_right, [None, None]) + right: list[float | None] = neighbors.get( + cast(float, x_right), [None, None] + ) right[0] = x def _update_scale(self, x: float, y: _ScaledValue) -> None: @@ -884,7 +869,7 @@ def _loss( loss = mapping[ival] return finite_loss(ival, loss, self._scale[0]) - def plot(self, *, scatter_or_line: str = "scatter") -> holoviews.Overlay: + def plot(self, *, scatter_or_line: str = "scatter") -> Overlay: """Returns a plot of the evaluated data. Parameters diff --git a/adaptive/learner/learner2D.py b/adaptive/learner/learner2D.py index 859f0006..c47046ec 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -6,7 +6,7 @@ from collections.abc import Callable, Iterable, Sequence, Sized from copy import copy from math import sqrt -from typing import TYPE_CHECKING, Any, Protocol, Self, TypeAlias, cast +from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, cast import cloudpickle import numpy as np @@ -15,7 +15,7 @@ from scipy.interpolate import CloughTocher2DInterpolator, LinearNDInterpolator from scipy.spatial import Delaunay -from adaptive.learner.base_learner import BaseLearner +from adaptive.learner.base_learner import BaseLearner, _LearningFunction from adaptive.learner.triangulation_backend import simplex_volume_in_embedding from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import ( @@ -43,9 +43,7 @@ | Iterable[float] | NDArray[np.floating | np.integer] ) -_TriangleLoss: TypeAlias = Callable[ - [LinearNDInterpolator], NDArray[np.float64] | list[float] -] +_TriangleLoss: TypeAlias = Callable[[Any], NDArray[np.floating] | list[float]] _State: TypeAlias = tuple[ bytes, tuple[_Point, _Point], @@ -76,6 +74,8 @@ class _CloughTocherData(Protocol): class _HasMax(Protocol): def max(self) -> float: ... +else: + HoloMap = Overlay = Any # Learner2D and helper functions. @@ -489,8 +489,8 @@ class Learner2D(BaseLearner): def __init__( self, - function: Callable[[_Point], _Value], - bounds: Sequence[Sequence[float | np.floating | np.integer]], + function: _LearningFunction[_Point, _Value], + bounds: Sequence[Sequence[float | np.floating | np.integer]] | NDArray[Any], loss_per_triangle: _TriangleLoss | None = None, ) -> None: self.ndim = len(bounds) @@ -516,8 +516,8 @@ def __init__( self.stack_size = 10 - def new(self) -> Self: - return cast(Self, Learner2D(self.function, self.bounds, self.loss_per_triangle)) + def new(self) -> Learner2D: + return Learner2D(self.function, self.bounds, self.loss_per_triangle) @property def xy_scale(self) -> NDArray[np.float64]: @@ -535,7 +535,7 @@ def to_numpy(self) -> NDArray[np.floating | np.integer]: [(x, y, *np.atleast_1d(z)) for (x, y), z in sorted(self.data.items())] ) - def to_dataframe( + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -581,7 +581,7 @@ def to_dataframe( assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -626,7 +626,7 @@ def _unscale(self, points: ArrayLike) -> NDArray[np.float64]: return np.asarray(points, dtype=float) * self.xy_scale + self.xy_mean @property - def npoints(self) -> int: + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] """Number of evaluated points.""" return len(self.data) @@ -782,7 +782,9 @@ def inside_bounds(self, xy: _PointInput) -> bool | np.bool_: (xmin, xmax), (ymin, ymax) = self.bounds return xmin <= x <= xmax and ymin <= y <= ymax - def tell(self, point: _PointInput, value: _Value) -> None: + def tell( + self, point: _PointInput, value: _Value + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] xy = cast(_Point, tuple(point)) self.data[xy] = value if not self.inside_bounds(xy): @@ -792,7 +794,9 @@ def tell(self, point: _PointInput, value: _Value) -> None: self._ip_combined = None self._stack.pop(xy, None) - def tell_pending(self, point: _PointInput) -> None: + def tell_pending( + self, point: _PointInput + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] xy = cast(_Point, tuple(point)) if not self.inside_bounds(xy): return diff --git a/adaptive/learner/learnerND.py b/adaptive/learner/learnerND.py index 54b492d2..d30e6a55 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -12,7 +12,6 @@ Any, Literal, Protocol, - Self, SupportsFloat, TypeAlias, TypeVar, @@ -25,7 +24,11 @@ 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, + _LearningFunction, + uses_nth_neighbors, +) from adaptive.learner.triangulation import ( _Point, _PointLike, @@ -58,6 +61,8 @@ from holoviews.core import Overlay from holoviews.element import Image, Path from plotly.graph_objects import Figure, Mesh3d +else: + Overlay = Image = Path = Figure = Mesh3d = Any try: import pandas @@ -75,7 +80,12 @@ _NeighborLoss: TypeAlias = Callable[ [_Array, _Array, float, list[_Array | None], list[_Value | None]], SupportsFloat ] -_Bounds: TypeAlias = Sequence[Sequence[float]] | scipy.spatial.ConvexHull +# The user can specialize the simplex and neighbor types for their function. +_SimplexLossCallback: TypeAlias = ( + Callable[[Any, Any, float], SupportsFloat] + | Callable[[Any, Any, float, Any, Any], SupportsFloat] +) +_Bounds: TypeAlias = Sequence[Sequence[float]] | _Array | scipy.spatial.ConvexHull _QueueItem: TypeAlias = tuple[float, _Simplex, _Simplex | None] _T = TypeVar("_T") @@ -419,9 +429,9 @@ class LearnerND(BaseLearner): def __init__( self, - func: Callable[[_Point], _Value], + func: _LearningFunction[_Point, _Value], bounds: _Bounds, - loss_per_simplex: _Loss | _NeighborLoss | None = None, + loss_per_simplex: _SimplexLossCallback | None = None, *, anisotropic: bool = False, triangulation_backend: str | _TriangulationClass = "auto", @@ -473,7 +483,7 @@ def __init__( f"LearnerND only supports dim >= 2 (got ndim={self.ndim})." ) - self.function: Callable[[_Point], _Value] = func + self.function: _LearningFunction[_Point, _Value] = func self._tri: TriangulationProtocol | None = None self._losses: dict[_Simplex, float] = {} @@ -513,21 +523,18 @@ def __init__( key=_simplex_evaluation_priority ) - def new(self) -> Self: + def new(self) -> LearnerND: """Create a new learner with the same function and bounds.""" - return cast( - "Self", - LearnerND( - self.function, - self.bounds, - self.loss_per_simplex, - anisotropic=self.anisotropic, - triangulation_backend=self._triangulation_class, - ), + return LearnerND( + self.function, + self.bounds, + self.loss_per_simplex, + anisotropic=self.anisotropic, + triangulation_backend=self._triangulation_class, ) @property - def npoints(self) -> int: + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] """Number of evaluated points.""" return len(self.data) @@ -558,7 +565,7 @@ def _default_point_names(self) -> tuple[str, ...]: return ("x", "y", "z")[: self.ndim] return tuple(f"x{i}" for i in range(self.ndim)) - def to_dataframe( + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -608,7 +615,7 @@ def to_dataframe( assign_defaults(self.function, df, function_prefix) return df - def load_dataframe( + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, @@ -683,7 +690,9 @@ def points(self) -> npt.NDArray[np.float64]: """Get the points from `data` as a numpy array.""" return np.array(list(self.data.keys()), dtype=float) - def tell(self, point: Iterable[float], value: _Value | None) -> None: + def tell( + self, point: Iterable[float], value: _Value | None + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] point = tuple(point) if point in self.data: return # we already know about the point @@ -765,7 +774,7 @@ def inside_bounds(self, point: _PointLike) -> bool | np.bool_: (mn - eps) <= p <= (mx + eps) for p, (mn, mx) in zip(point, self._bbox) ) - def tell_pending( + def tell_pending( # ty: ignore[lost-keyword-for-regular-parameter] self, point: Iterable[float], *, simplex: _Simplex | None = None ) -> None: point = tuple(point) @@ -1558,6 +1567,8 @@ def _get_plane_color(simplex: Iterable[int]) -> tuple[int, ...]: def _get_data(self) -> dict[str, Any]: return deepcopy(self.__dict__) - def _set_data(self, state: Mapping[str, Any]) -> None: + def _set_data( + self, state: Mapping[str, Any] + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] for k, v in state.items(): setattr(self, k, v) diff --git a/adaptive/learner/sequence_learner.py b/adaptive/learner/sequence_learner.py index 65c940fa..89118f7a 100644 --- a/adaptive/learner/sequence_learner.py +++ b/adaptive/learner/sequence_learner.py @@ -1,7 +1,8 @@ from __future__ import annotations +from collections.abc import Callable, Sequence from copy import copy -from typing import TYPE_CHECKING, Any, Self, TypeAlias, cast +from typing import TYPE_CHECKING, Any, TypeAlias, cast import cloudpickle import numpy as np @@ -15,7 +16,7 @@ ) if TYPE_CHECKING: - from collections.abc import Callable, MutableSet, Sequence + from collections.abc import MutableSet try: import pandas @@ -101,9 +102,9 @@ def __init__( self.data = SortedDict() self.pending_points = set() - def new(self) -> Self: + def new(self) -> SequenceLearner: """Return a new `~adaptive.SequenceLearner` without the data.""" - return cast(Self, SequenceLearner(self._original_function, self.sequence)) + return SequenceLearner(self._original_function, self.sequence) def ask( self, n: int, tell_pending: bool = True @@ -138,13 +139,17 @@ def remove_unfinished(self) -> None: self._to_do_indices.add(i) self.pending_points = set() - def tell(self, point: PointType, value: Any) -> None: + def tell( + self, point: PointType, value: Any + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] index, _ = point self.data[index] = value self.pending_points.discard(index) self._to_do_indices.discard(index) - def tell_pending(self, point: PointType) -> None: + def tell_pending( + self, point: PointType + ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] index, _ = point self.pending_points.add(index) self._to_do_indices.discard(index) @@ -159,10 +164,10 @@ def result(self) -> list[Any]: return list(self.data.values()) @property - def npoints(self) -> int: + def npoints(self) -> int: # type: ignore[override] # ty: ignore[incompatible-property-override] return len(self.data) - def to_dataframe( + def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, with_default_function_args: bool = True, function_prefix: str = "function.", @@ -224,7 +229,7 @@ def to_dataframe( assign_defaults(self._original_function, df, function_prefix) return df - def load_dataframe( + def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, df: pandas.DataFrame, with_default_function_args: bool = True, diff --git a/adaptive/notebook_integration.py b/adaptive/notebook_integration.py index cb564fc9..4989e4cb 100644 --- a/adaptive/notebook_integration.py +++ b/adaptive/notebook_integration.py @@ -5,26 +5,26 @@ import importlib import random import warnings -from collections.abc import Hashable +from collections.abc import Callable, Hashable from contextlib import suppress from types import ModuleType -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING, Any, cast + +import adaptive +from adaptive.learner.base_learner import LearnerType if TYPE_CHECKING: - from collections.abc import Callable, Iterator, Mapping + from collections.abc import Iterator, Mapping from typing import Protocol - import holoviews - import ipywidgets - - from adaptive.learner.base_learner import LearnerType - from adaptive.runner import AsyncRunner + from holoviews import DynamicMap, Element + from ipywidgets import HTML # IPython supplies this as a builtin; it is absent outside IPython. get_ipython: Callable[[], object] class _Plottable(Protocol): - def plot(self) -> holoviews.Element: ... + def plot(self) -> Element: ... class _HasSamples(Protocol): @property @@ -34,6 +34,9 @@ class _HasLossCache(Protocol): @property def _cache(self) -> Mapping[str, float]: ... +else: + DynamicMap = Element = HTML = Any + _holoviews_enabled = False _ipywidgets_enabled = False @@ -119,13 +122,13 @@ def in_ipynb() -> bool: def live_plot( - runner: AsyncRunner[LearnerType], + runner: adaptive.AsyncRunner[LearnerType], *, - plotter: Callable[[LearnerType], holoviews.Element] | None = None, + plotter: Callable[[LearnerType], Element] | None = None, update_interval: float = 2, name: Hashable = None, normalize: bool = True, -) -> holoviews.DynamicMap: +) -> DynamicMap: """Live plotting of the learner's data. Parameters @@ -160,7 +163,7 @@ def live_plot( if name in active_plotting_tasks: active_plotting_tasks[name].cancel() - def plot_generator() -> Iterator[holoviews.Element]: + def plot_generator() -> Iterator[Element]: while True: if not plotter: yield cast("_Plottable", runner.learner).plot() @@ -209,7 +212,7 @@ def cancel(_: object) -> None: return dm -def should_update(status: ipywidgets.HTML) -> bool: +def should_update(status: HTML) -> bool: try: # Get the length of the write buffer size buffer_size = len(status.comm.kernel.iopub_thread._events) @@ -228,7 +231,7 @@ def should_update(status: ipywidgets.HTML) -> bool: def live_info( - runner: AsyncRunner[LearnerType], *, update_interval: float = 0.5 + runner: adaptive.AsyncRunner[LearnerType], *, update_interval: float = 0.5 ) -> None: """Display live information about the runner. @@ -275,7 +278,7 @@ def _table_row(i: int, key: str, value: object) -> str: return f'{key}{value}' -def _info_html(runner: AsyncRunner[LearnerType]) -> str: +def _info_html(runner: adaptive.AsyncRunner[LearnerType]) -> str: status = runner.status() color = { diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index 2d0c2c29..5c2e6805 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -1,13 +1,27 @@ import inspect from importlib.resources import files -from typing import TYPE_CHECKING, assert_type, get_args, get_origin +from typing import TYPE_CHECKING, assert_type, get_args, get_origin, get_type_hints import numpy as np import pytest -from adaptive import AsyncRunner, BalancingLearner, BlockingRunner, DataSaver, Learner1D +from adaptive import ( + AsyncRunner, + AverageLearner, + AverageLearner1D, + BalancingLearner, + BlockingRunner, + DataSaver, + IntegratorLearner, + Learner1D, + Learner2D, + LearnerND, + live_plot, + utils, +) from adaptive import types as legacy_types from adaptive.learner.base_learner import uses_nth_neighbors +from adaptive.notebook_integration import live_info, should_update from adaptive.runner import BaseRunner, Runner if TYPE_CHECKING: @@ -51,3 +65,34 @@ def loss(xs: list[float], *, scale: float = 1) -> float: assert annotated.nth_neighbors == 2 assert inspect.signature(annotated) == inspect.signature(loss) assert annotated([1, 3], scale=2) == 4 + + +@pytest.mark.parametrize( + "public_api", + [ + utils.save, + utils.load, + BalancingLearner.plot, + BalancingLearner.save, + BalancingLearner.load, + DataSaver.save, + DataSaver.load, + AverageLearner.plot, + AverageLearner.to_numpy, + AverageLearner1D.plot, + IntegratorLearner.plot, + Learner1D.plot, + Learner2D.plot, + LearnerND.plot, + LearnerND.plot_3D, + LearnerND.plot_isoline, + LearnerND.plot_slice, + live_info, + live_plot, + should_update, + utils.assign_defaults, + utils.partial_function_from_dataframe, + ], +) +def test_public_annotations_resolve(public_api): + assert get_type_hints(public_api) diff --git a/adaptive/utils.py b/adaptive/utils.py index 8ae024f1..7517b858 100644 --- a/adaptive/utils.py +++ b/adaptive/utils.py @@ -11,15 +11,16 @@ from contextlib import contextmanager from functools import wraps from itertools import product +from os import PathLike from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, TypeVar, cast import cloudpickle if TYPE_CHECKING: - from os import PathLike - - import pandas from dask.distributed import Client as AsyncDaskClient + from pandas import DataFrame +else: + AsyncDaskClient = DataFrame = Any P = ParamSpec("P") @@ -61,14 +62,15 @@ def cache_latest(f: Callable[P, T]) -> Callable[P, T]: """Cache the latest return value of the function and add it as 'self._cache[f.__name__]'.""" + name = cast(_HasName, f).__name__ + @functools.wraps(f) - def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: - self = cast(_HasCache, args[0]) + def wrapper(*args: Any, **kwargs: Any) -> T: + self: _HasCache = args[0] if not hasattr(self, "_cache"): self._cache = {} - named = cast(_HasName, f) - self._cache[named.__name__] = f(*args, **kwargs) - return self._cache[named.__name__] + self._cache[name] = f(*args, **kwargs) + return self._cache[name] return wrapper @@ -133,7 +135,7 @@ def _default_parameters( def assign_defaults( function: Callable[..., Any], - df: pandas.DataFrame, + df: DataFrame, function_prefix: str = "function.", ) -> None: defaults = _default_parameters(function, function_prefix) @@ -142,7 +144,7 @@ def assign_defaults( def partial_function_from_dataframe( - function: Callable[..., T], df: pandas.DataFrame, function_prefix: str = "function." + function: Callable[..., T], df: DataFrame, function_prefix: str = "function." ) -> Callable[..., T]: if function_prefix == "": raise ValueError( diff --git a/tests/typing_contract.py b/tests/typing_contract.py new file mode 100644 index 00000000..ca8ef24c --- /dev/null +++ b/tests/typing_contract.py @@ -0,0 +1,148 @@ +"""Public API fixture checked by mypy and ty, not executed by pytest.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any, assert_type + +import numpy as np +from scipy.interpolate import LinearNDInterpolator +from scipy.spatial import ConvexHull + +from adaptive import ( + AverageLearner, + AverageLearner1D, + BalancingLearner, + BaseLearner, + DataSaver, + IntegratorLearner, + Learner1D, + Learner2D, + LearnerND, + SequenceLearner, +) +from adaptive.learner.base_learner import uses_nth_neighbors + + +async def evaluate(x: float) -> float: + return x**2 + + +async def evaluate_point(point: tuple[float, ...]) -> float: + return sum(point) + + +async def sample(seed_x: tuple[int, float]) -> float: + seed, x = seed_x + return seed + x + + +def tuple_loss(xs: tuple[float, float], ys: tuple[float, float]) -> float: + return xs[1] - xs[0] + abs(ys[1] - ys[0]) + + +def scalar_loss(xs: Sequence[float], ys: Sequence[float]) -> float: + return xs[-1] - xs[0] + abs(ys[-1] - ys[0]) + + +@uses_nth_neighbors(1) +def neighbor_loss(xs: tuple[float | None, ...], ys: tuple[float | None, ...]) -> float: + return float(sum(y is not None for y in ys)) + + +def triangle_loss(ip: LinearNDInterpolator) -> list[float]: + return [1.0] + + +def simplex_loss( + simplex: tuple[tuple[float, ...], ...], values: tuple[float, ...], scale: float +) -> float: + return len(simplex) * sum(values) / scale + + +@uses_nth_neighbors(1) +def neighboring_simplex_loss( + simplex: tuple[tuple[float, ...], ...], + values: tuple[float, ...], + scale: float, + neighbors: list[np.ndarray | None], + neighbor_values: list[float | None], +) -> float: + return simplex_loss(simplex, values, scale) + + +def check_constructors() -> None: + Learner1D(evaluate, [0.0, 1.0], loss_per_interval=tuple_loss) + learner = Learner1D(evaluate, np.array([0.0, 1.0]), loss_per_interval=scalar_loss) + Learner1D(evaluate, (0.0, 1.0), loss_per_interval=neighbor_loss) + learner.tell(x=0.5, y=0.25) + + bounds = [[0.0, 1.0], [0.0, 1.0]] + xy = np.array(bounds) + Learner2D(evaluate_point, bounds, loss_per_triangle=triangle_loss) + Learner2D(evaluate_point, xy) + LearnerND(evaluate_point, bounds, loss_per_simplex=simplex_loss) + LearnerND(evaluate_point, xy, loss_per_simplex=neighboring_simplex_loss) + LearnerND(evaluate_point, ConvexHull(np.array([[0, 0], [0, 1], [1, 0]]))) + + AverageLearner(evaluate, rtol=0.01) + AverageLearner1D(sample, [0.0, 1.0], loss_per_interval=tuple_loss) + IntegratorLearner(evaluate, (0.0, 1.0), tol=0.01) + SequenceLearner(evaluate, [0.0, 1.0]) + + +class ExternalLearner(BaseLearner): + def __init__(self) -> None: + self.npoints = 0 + self.data = {} + self.pending_points = set() + self.function = abs + + def tell(self, x: Any, y: Any) -> None: + self.data[x] = y + self.npoints += 1 + + def tell_pending(self, x: Any) -> None: + self.pending_points.add(x) + + def remove_unfinished(self) -> None: + self.pending_points.clear() + + def loss(self, real: bool = True) -> float: + return 1.0 + + def ask(self, n: int, tell_pending: bool = True) -> tuple[list[Any], list[float]]: + return [], [] + + def _get_data(self) -> Any: + return self.data + + def _set_data(self, data: Any) -> None: + self.data = data + + def new(self) -> ExternalLearner: + return ExternalLearner() + + def to_dataframe(self, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError + + def load_dataframe(self, df: Any, *args: Any, **kwargs: Any) -> None: + raise NotImplementedError + + +class TaggedLearner1D(Learner1D): + def tag(self) -> str: + return "tagged" + + +def check_base_keywords(learner: BaseLearner) -> None: + learner.npoints = 0 + learner.tell(x=0, y=0) + + +def check_new() -> None: + check_base_keywords(ExternalLearner()) + tagged = TaggedLearner1D(evaluate, (0.0, 1.0)) + assert_type(tagged.new(), Learner1D) + assert_type(DataSaver(tagged, abs).new(), DataSaver[BaseLearner]) + assert_type(BalancingLearner([tagged]).new(), BalancingLearner[BaseLearner]) From ce6b1e6c63e71bc161039707fa1b7c1d80bcce85 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 17:20:56 -0800 Subject: [PATCH 5/9] Preserve typed learner callback round trips Accept sync and async callbacks without weakening the type of evaluated results passed to tell. Accept sequence and NumPy integrator bounds and keep the original container in pickle state. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/learner/average_learner.py | 7 ++-- adaptive/learner/average_learner1D.py | 12 +++--- adaptive/learner/base_learner.py | 9 ++--- adaptive/learner/integrator_learner.py | 14 ++++--- adaptive/learner/learner1D.py | 5 +-- adaptive/learner/learner2D.py | 4 +- adaptive/learner/learnerND.py | 5 +-- adaptive/tests/test_typing.py | 49 +++++++++++++++++++++++- tests/typing_contract.py | 52 ++++++++++++++++++++++++++ 9 files changed, 127 insertions(+), 30 deletions(-) diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index 232f29ac..e3c56996 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections.abc import Callable from math import sqrt from typing import TYPE_CHECKING, Any, TypeAlias, cast @@ -7,7 +8,7 @@ import numpy as np from numpy.typing import NDArray -from adaptive.learner.base_learner import BaseLearner, _LearningFunction +from adaptive.learner.base_learner import BaseLearner from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import ( assign_defaults, @@ -66,7 +67,7 @@ class AverageLearner(BaseLearner): def __init__( self, - function: _LearningFunction[int, _Sample], + function: Callable[[int], Any], atol: float | None = None, rtol: float | None = None, min_npoints: int = 2, @@ -80,7 +81,7 @@ def __init__( self.data = {} self.pending_points = set() - self.function: _LearningFunction[int, _Sample] = function + self.function: Callable[[int], Any] = function self.atol = atol self.rtol = rtol self.npoints = 0 diff --git a/adaptive/learner/average_learner1D.py b/adaptive/learner/average_learner1D.py index 5279c3ff..729bbe29 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -3,7 +3,7 @@ import math import sys from collections import defaultdict -from collections.abc import Iterable, Sequence +from collections.abc import Callable, Iterable, Sequence from copy import deepcopy from math import hypot from typing import TYPE_CHECKING, Any, TypeAlias, cast @@ -12,7 +12,6 @@ import scipy.stats from numpy.typing import NDArray -from adaptive.learner.base_learner import _LearningFunction from adaptive.learner.learner1D import ( Interval, ItemSortedDict, @@ -92,13 +91,13 @@ class AverageLearner1D(Learner1D): # The public sampling interface uses (seed, x) rather than x, while # the inherited interval calculations still use the real coordinate x. if TYPE_CHECKING: - function: _LearningFunction[Point, float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] + function: Callable[[Point], Any] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] pending_points: set[Point] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] data: dict[float, float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] def __init__( self, - function: _LearningFunction[Point, float], + function: Callable[[Point], Any], bounds: _Bounds, loss_per_interval: _IntervalLossCallback | None = None, delta: float = 0.2, @@ -119,10 +118,9 @@ def __init__( if min_samples > max_samples: raise ValueError("max_samples should be larger than min_samples.") - # The shared initializer only stores the function; the loss is - # evaluated on scalar means, never on vector-valued observations. + # The shared initializer stores the callback without calling it. super().__init__( - cast("_LearningFunction[float, float]", function), + cast("Callable[[float], Any]", function), bounds, loss_per_interval, ) diff --git a/adaptive/learner/base_learner.py b/adaptive/learner/base_learner.py index bd2bb12f..e648e1d9 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -1,9 +1,9 @@ from __future__ import annotations import abc -from collections.abc import Awaitable, Callable +from collections.abc import Callable from contextlib import suppress -from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, TypeAlias, TypeVar, cast +from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, TypeVar, cast import cloudpickle @@ -81,9 +81,6 @@ def _wrapped(loss_per_interval: Callable[_P, _R_co]) -> _NeighborLoss[_P, _R_co] DataType = dict[Any, Any] -_Input = TypeVar("_Input") -_Output = TypeVar("_Output") -_LearningFunction: TypeAlias = Callable[[_Input], _Output | Awaitable[_Output]] class BaseLearner(abc.ABC): @@ -107,6 +104,8 @@ class BaseLearner(abc.ABC): and returns a holoviews plot. """ + # Learners expose either a synchronous or an asynchronous callback. + # Its return type is independent of the evaluated values passed to tell(). function: Callable[..., Any] data: Any diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index fa8628b4..3110f275 100644 --- a/adaptive/learner/integrator_learner.py +++ b/adaptive/learner/integrator_learner.py @@ -3,7 +3,7 @@ import sys from collections import defaultdict -from collections.abc import Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator, Sequence from math import sqrt from operator import attrgetter from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, cast @@ -15,7 +15,7 @@ from sortedcontainers import SortedSet from adaptive.learner import integrator_coeffs as coeff -from adaptive.learner.base_learner import BaseLearner, _LearningFunction +from adaptive.learner.base_learner import BaseLearner from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import assign_defaults, cache_latest, restore @@ -353,6 +353,7 @@ def __repr__(self) -> str: return " ".join(lst) +_Bounds: TypeAlias = Sequence[float] | NDArray[Any] _Data: TypeAlias = tuple[ list[_Interval], dict[float, float], @@ -362,7 +363,7 @@ def __repr__(self) -> str: set[_Interval], _Interval, ] -_State: TypeAlias = tuple[bytes, tuple[float, float], float, _Data] +_State: TypeAlias = tuple[bytes, _Bounds, float, _Data] class IntegratorLearner(BaseLearner): @@ -371,8 +372,8 @@ class IntegratorLearner(BaseLearner): def __init__( self, - function: _LearningFunction[float, float], - bounds: tuple[float, float], + function: Callable[[float], Any], + bounds: _Bounds, tol: float, ) -> None: """ @@ -420,7 +421,8 @@ def __init__( lambda: SortedSet([], key=attrgetter("rdepth")) ) self.ivals: set[_Interval] = set() - ival = _Interval.make_first(*self.bounds) + # Bounds are documented as a pair; preserve the original container. + ival = _Interval.make_first(*cast("tuple[float, float]", self.bounds)) self.add_ival(ival) self.first_ival = ival diff --git a/adaptive/learner/learner1D.py b/adaptive/learner/learner1D.py index 640db847..5fd08def 100644 --- a/adaptive/learner/learner1D.py +++ b/adaptive/learner/learner1D.py @@ -13,7 +13,6 @@ from adaptive.learner.base_learner import ( BaseLearner, - _LearningFunction, uses_nth_neighbors, ) from adaptive.learner.learnerND import volume @@ -316,11 +315,11 @@ class Learner1D(BaseLearner): def __init__( self, - function: _LearningFunction[float, Value], + function: Callable[[float], Any], bounds: _Bounds, loss_per_interval: _IntervalLossCallback | None = None, ) -> None: - self.function: _LearningFunction[float, Value] = function + self.function: Callable[[float], Any] = function self.nth_neighbors: int = getattr(loss_per_interval, "nth_neighbors", 0) self.loss_per_interval: _IntervalLossCallback = ( diff --git a/adaptive/learner/learner2D.py b/adaptive/learner/learner2D.py index c47046ec..5523c928 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -15,7 +15,7 @@ from scipy.interpolate import CloughTocher2DInterpolator, LinearNDInterpolator from scipy.spatial import Delaunay -from adaptive.learner.base_learner import BaseLearner, _LearningFunction +from adaptive.learner.base_learner import BaseLearner from adaptive.learner.triangulation_backend import simplex_volume_in_embedding from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import ( @@ -489,7 +489,7 @@ class Learner2D(BaseLearner): def __init__( self, - function: _LearningFunction[_Point, _Value], + function: Callable[[_Point], Any], bounds: Sequence[Sequence[float | np.floating | np.integer]] | NDArray[Any], loss_per_triangle: _TriangleLoss | None = None, ) -> None: diff --git a/adaptive/learner/learnerND.py b/adaptive/learner/learnerND.py index d30e6a55..b752a9eb 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -26,7 +26,6 @@ from adaptive.learner.base_learner import ( BaseLearner, - _LearningFunction, uses_nth_neighbors, ) from adaptive.learner.triangulation import ( @@ -429,7 +428,7 @@ class LearnerND(BaseLearner): def __init__( self, - func: _LearningFunction[_Point, _Value], + func: Callable[[_Point], Any], bounds: _Bounds, loss_per_simplex: _SimplexLossCallback | None = None, *, @@ -483,7 +482,7 @@ def __init__( f"LearnerND only supports dim >= 2 (got ndim={self.ndim})." ) - self.function: _LearningFunction[_Point, _Value] = func + self.function: Callable[[_Point], Any] = func self._tri: TriangulationProtocol | None = None self._losses: dict[_Simplex, float] = {} diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index 5c2e6805..060488b5 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -1,21 +1,27 @@ import inspect +import pickle +from collections.abc import Callable, Sequence +from functools import partial from importlib.resources import files -from typing import TYPE_CHECKING, assert_type, get_args, get_origin, get_type_hints +from typing import TYPE_CHECKING, Any, assert_type, get_args, get_origin, get_type_hints import numpy as np import pytest +from numpy.typing import NDArray from adaptive import ( AsyncRunner, AverageLearner, AverageLearner1D, BalancingLearner, + BaseLearner, BlockingRunner, DataSaver, IntegratorLearner, Learner1D, Learner2D, LearnerND, + SequenceLearner, live_plot, utils, ) @@ -96,3 +102,44 @@ def loss(xs: list[float], *, scale: float = 1) -> float: ) def test_public_annotations_resolve(public_api): assert get_type_hints(public_api) + + +def _square(x: float) -> float: + return x**2 + + +@pytest.mark.parametrize( + "make_learner", + [ + pytest.param(partial(Learner1D, _square, (0.0, 1.0)), id="1d"), + pytest.param(partial(Learner2D, sum, ((0.0, 1.0), (0.0, 1.0))), id="2d"), + pytest.param(partial(LearnerND, sum, ((0.0, 1.0), (0.0, 1.0))), id="nd"), + pytest.param(partial(AverageLearner, _square, rtol=0.01), id="average"), + pytest.param( + partial(AverageLearner1D, lambda point: _square(point[1]), (0.0, 1.0)), + id="average1d", + ), + pytest.param( + partial(IntegratorLearner, _square, (0.0, 1.0), tol=0.01), id="integrator" + ), + pytest.param(partial(SequenceLearner, _square, [0.0, 0.5, 1.0]), id="sequence"), + ], +) +def test_synchronous_round_trip(make_learner: Callable[[], BaseLearner]) -> None: + learner = make_learner() + points, _ = learner.ask(3) + assert len(points) == 3 + for point in points: + learner.tell(point, learner.function(point)) + assert learner.npoints > 0 + + +@pytest.mark.parametrize( + "bounds", [[0.0, 1.0], np.array([0.0, 1.0])], ids=["list", "array"] +) +def test_integrator_bounds(bounds: Sequence[float] | NDArray[Any]) -> None: + learner = IntegratorLearner(_square, bounds, tol=0.01) + assert learner.bounds is bounds + restored = pickle.loads(pickle.dumps(learner)) + assert type(restored.bounds) is type(bounds) + np.testing.assert_array_equal(restored.bounds, bounds) diff --git a/tests/typing_contract.py b/tests/typing_contract.py index ca8ef24c..739713f2 100644 --- a/tests/typing_contract.py +++ b/tests/typing_contract.py @@ -91,6 +91,58 @@ def check_constructors() -> None: SequenceLearner(evaluate, [0.0, 1.0]) +def square(x: float) -> float: + return x**2 + + +def sample_point(seed_x: tuple[int, float]) -> float: + return square(seed_x[1]) + + +def check_synchronous_round_trips() -> None: + bounds = (0.0, 1.0) + planar_bounds = (bounds, bounds) + + learner1d = Learner1D(square, bounds) + for x in learner1d.ask(3)[0]: + learner1d.tell(x, learner1d.function(x)) + + learner2d = Learner2D(sum, planar_bounds) + for xy in learner2d.ask(3)[0]: + learner2d.tell(xy, learner2d.function(xy)) + + learner_nd = LearnerND(sum, planar_bounds) + for point in learner_nd.ask(3)[0]: + learner_nd.tell(point, learner_nd.function(point)) + + average = AverageLearner(square, rtol=0.01) + for seed in average.ask(3)[0]: + average.tell(seed, average.function(seed)) + + average1d = AverageLearner1D(sample_point, bounds) + for seed_x in average1d.ask(3)[0]: + average1d.tell(seed_x, average1d.function(seed_x)) + + for integrator in ( + IntegratorLearner(square, [0.0, 1.0], tol=0.01), + IntegratorLearner(square, np.array(bounds), tol=0.01), + ): + for x in integrator.ask(3)[0]: + integrator.tell(x, integrator.function(x)) + + sequence = SequenceLearner(square, [0.0, 0.5, 1.0]) + for index_point in sequence.ask(3)[0]: + sequence.tell(index_point, sequence.function(index_point)) + + wrapped = DataSaver(Learner1D(square, bounds), abs) + for x in wrapped.ask(3)[0]: + wrapped.tell(x, wrapped.function(x)) + + balancing = BalancingLearner([Learner1D(square, bounds)]) + for indexed_x in balancing.ask(3)[0]: + balancing.tell(indexed_x, balancing.function(indexed_x)) + + class ExternalLearner(BaseLearner): def __init__(self) -> None: self.npoints = 0 From 5f03e0168ff88b0c59fb6700ece26b025df9847e Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 17:38:03 -0800 Subject: [PATCH 6/9] Fix public typing and backend compatibility from stage two review Cover NumPy bounds, notebook plotting, the optional Rust backend, and legacy imports in the typed public contract. Simplify local typing adapters and pin the CI checkers and stubs. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- .github/workflows/typecheck.yml | 2 +- adaptive/__init__.py | 3 +- adaptive/learner/_sorted_types.py | 32 +++++++++ adaptive/learner/average_learner.py | 8 +-- adaptive/learner/average_learner1D.py | 27 ++++---- adaptive/learner/balancing_learner.py | 25 ++++--- adaptive/learner/base_learner.py | 4 +- adaptive/learner/data_saver.py | 4 +- adaptive/learner/integrator_learner.py | 10 ++- adaptive/learner/learner1D.py | 67 ++++++------------- adaptive/learner/learner2D.py | 16 ++--- adaptive/learner/learnerND.py | 80 ++++++++++++----------- adaptive/learner/sequence_learner.py | 20 +++--- adaptive/learner/triangulation_backend.py | 20 +++--- adaptive/notebook_integration.py | 10 +-- adaptive/runner.py | 21 +++--- adaptive/tests/test_typing.py | 30 +++++++++ adaptive/utils.py | 38 +++++------ pyproject.toml | 3 + tests/typing_contract.py | 79 +++++++++++++++++++++- 20 files changed, 308 insertions(+), 191 deletions(-) create mode 100644 adaptive/learner/_sorted_types.py diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index 4a417699..f02bb89a 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -19,7 +19,7 @@ jobs: - name: Install dependencies and type checkers run: | uv venv --python 3.13 - uv pip install '.[test,other,notebook]' scipy-stubs pandas-stubs ty mypy==2.4.1 + uv pip install '.[test,other,notebook]' scipy-stubs==1.18.1.1 pandas-stubs==3.1.2.261202 ty==1.2.0 mypy==2.4.1 - name: Run ty run: .venv/bin/ty check --error-on-warning --python .venv adaptive tests/typing_contract.py - name: Run mypy diff --git a/adaptive/__init__.py b/adaptive/__init__.py index 47742d34..bae0e1aa 100644 --- a/adaptive/__init__.py +++ b/adaptive/__init__.py @@ -19,11 +19,12 @@ ) from adaptive.runner import AsyncRunner, BlockingRunner, Runner -from adaptive import learner, notebook_integration, runner, utils # isort:skip +from adaptive import learner, notebook_integration, runner, types, utils # isort:skip __all__ = [ "learner", "runner", + "types", "utils", "__version__", "AverageLearner", diff --git a/adaptive/learner/_sorted_types.py b/adaptive/learner/_sorted_types.py new file mode 100644 index 00000000..fa75ef47 --- /dev/null +++ b/adaptive/learner/_sorted_types.py @@ -0,0 +1,32 @@ +"""Static interfaces for the untyped sorted mapping dependencies.""" + +from collections.abc import Callable, KeysView, Mapping, Sequence +from typing import TYPE_CHECKING, TypeVar + +_Key = TypeVar("_Key") +_Value = TypeVar("_Value") + +if TYPE_CHECKING: + from collections.abc import KeysView + + # The sorted mapping libraries are not typed. Their classes extend dict, + # but keys() also supports indexing and slicing in sorted order. + class _SortedKeys(KeysView[_Key], Sequence[_Key]): ... + + class SortedDict(dict[_Key, _Value]): + def keys(self) -> _SortedKeys[_Key]: ... # type: ignore[override] # ty: ignore[incompatible-method-override] + def bisect_left(self, key: _Key) -> int: ... + def index(self, key: _Key) -> int: ... + def peekitem(self, index: int = -1) -> tuple[_Key, _Value]: ... + + class ItemSortedDict(SortedDict[_Key, _Value]): + def __init__( + self, + key: Callable[[_Key, _Value], object], + mapping: Mapping[_Key, _Value] = ..., + ) -> None: ... +else: + from sortedcollections.recipes import ItemSortedDict + from sortedcontainers.sorteddict import SortedDict + +__all__ = ["ItemSortedDict", "SortedDict"] diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index e3c56996..374ca73a 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -193,9 +193,7 @@ def ask(self, n: int, tell_pending: bool = True) -> tuple[list[int], list[float] self.tell_pending(p) return points, loss_improvements - def tell( - self, n: _Seed, value: _Sample - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell(self, n: _Seed, value: _Sample) -> None: if n in self.data: # The point has already been added before. return @@ -206,9 +204,7 @@ def tell( self.sum_f_sq += value**2 self.npoints += 1 - def tell_pending( - self, n: _Seed - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell_pending(self, n: _Seed) -> None: self.pending_points.add(n) @property diff --git a/adaptive/learner/average_learner1D.py b/adaptive/learner/average_learner1D.py index 729bbe29..86c41dc5 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -12,11 +12,9 @@ import scipy.stats from numpy.typing import NDArray +from adaptive.learner._sorted_types import ItemSortedDict, SortedDict from adaptive.learner.learner1D import ( - Interval, - ItemSortedDict, Learner1D, - SortedDict, _Bounds, _get_intervals, _IntervalLossCallback, @@ -318,8 +316,16 @@ def _ask_for_more_samples(self, x: float, n: int) -> tuple[Points, list[float]]: n_existing = self._number_samples.get(x, 0) points = [(seed + n_existing, x) for seed in range(n)] xl, xr = self.neighbors_combined[x] - loss_left = self.losses_combined.get(cast(Interval, (xl, x)), float("inf")) - loss_right = self.losses_combined.get(cast(Interval, (x, xr)), float("inf")) + loss_left = ( + float("inf") + if xl is None + else self.losses_combined.get((xl, x), float("inf")) + ) + loss_right = ( + float("inf") + if xr is None + else self.losses_combined.get((x, xr), float("inf")) + ) loss = (loss_left + loss_right) / 2 if math.isinf(loss): loss_improvement = float("inf") @@ -386,7 +392,8 @@ def _update_rescaled_error_in_mean(self, x: float, point_type: str) -> None: self.rescaled_error[x_left] = self.error[x_left] / norm if x_right is None: - d_right = dists[cast(float, x_left)] + assert x_left is not None + d_right = dists[x_left] else: d_right = dists[x] if x_right in self.rescaled_error: @@ -498,7 +505,7 @@ def _update_losses_resampling(self, x: float, real: bool = True) -> None: # 'x' happens to be in between two real points, # so we can interpolate the losses. # Combined neighbors exist when there are real neighbors. - a, b = cast("Interval", (a, b)) + assert a is not None and b is not None dx = x_right - x_left loss = self.losses[x_left, x_right] self.losses_combined[a, x] = (x - a) * loss / dx @@ -530,11 +537,7 @@ def tell_many( # type: ignore[override] # ty: ignore[incompatible-method-overr "x value out of bounds, remove x or enlarge the bounds of the learner" ) - # Create a mapping of points to a list of samples - # We only assign to this inner defaultdict; the factory is not used. - mapping: defaultdict[float, dict[int, float]] = defaultdict( - lambda: cast("dict[int, float]", defaultdict(dict)) - ) + mapping: defaultdict[float, dict[int, float]] = 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 d6aa3d7b..e9aea93f 100644 --- a/adaptive/learner/balancing_learner.py +++ b/adaptive/learner/balancing_learner.py @@ -9,6 +9,8 @@ from os import PathLike from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, cast +import numpy as np + from adaptive.learner.base_learner import BaseLearner, LearnerType from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import cache_latest, named_product, restore @@ -17,6 +19,7 @@ from typing import Protocol, SupportsIndex from holoviews.core import Dimensioned, DynamicMap, HoloMap + from pandas import DataFrame class _HasNSamples(Protocol): @property @@ -38,14 +41,20 @@ def plot(self) -> Dimensioned: ... with_pandas = False -def dispatch(child_functions: list[Callable[..., Any]], arg: _Point) -> Any: +if not TYPE_CHECKING: + DataFrame = pandas.DataFrame if with_pandas else Any + + +def dispatch(child_functions: list[Callable[..., Any]], arg: _PointInput) -> Any: index, x = arg return child_functions[index](x) STRATEGY_TYPE: TypeAlias = Literal["loss_improvements", "loss", "npoints", "cycle"] +_Index: TypeAlias = int | np.integer[Any] _Point: TypeAlias = tuple[int, Any] +_PointInput: TypeAlias = tuple[_Index, Any] _NamedDimensions: TypeAlias = tuple[Sequence[str], Iterable[tuple[Any, ...]]] CDIMS_TYPE: TypeAlias = Sequence[dict[str, Any]] | _NamedDimensions | None @@ -117,9 +126,9 @@ def __init__( # pickle the whole learner. self.function = partial(dispatch, [lrn.function for lrn in self.learners]) - self._ask_cache: dict[int, tuple[list[Any], list[float]]] = {} - self._loss: dict[int, float] = {} - self._pending_loss: dict[int, float] = {} + self._ask_cache: dict[_Index, tuple[list[Any], list[float]]] = {} + self._loss: dict[_Index, float] = {} + self._pending_loss: dict[_Index, float] = {} self._cdims_default = cdims if len({learner.__class__ for learner in self.learners}) > 1: @@ -314,14 +323,14 @@ def ask( else: return self._ask_and_tell(n) - def tell(self, x: _Point, y: Any) -> None: + def tell(self, x: _PointInput, y: Any) -> None: index, x_ = x self._ask_cache.pop(index, None) self._loss.pop(index, None) self._pending_loss.pop(index, None) self.learners[index].tell(x_, y) - def tell_pending(self, x: _Point) -> None: + def tell_pending(self, x: _PointInput) -> None: index, x_ = x self._ask_cache.pop(index, None) self._loss.pop(index, None) @@ -499,7 +508,7 @@ def from_product( def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] self, index_name: str = "learner_index", **kwargs: Any - ) -> pandas.DataFrame: + ) -> DataFrame: """Return the data as a concatenated `pandas.DataFrame` from child learners. Parameters @@ -532,7 +541,7 @@ def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-ov return df def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override] - self, df: pandas.DataFrame, index_name: str = "learner_index", **kwargs: Any + self, df: DataFrame, index_name: str = "learner_index", **kwargs: Any ) -> None: """Load the data from a `pandas.DataFrame` into the child learners. diff --git a/adaptive/learner/base_learner.py b/adaptive/learner/base_learner.py index e648e1d9..95a2bbd1 100644 --- a/adaptive/learner/base_learner.py +++ b/adaptive/learner/base_learner.py @@ -3,9 +3,10 @@ import abc from collections.abc import Callable from contextlib import suppress -from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, TypeVar, cast +from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, TypeAlias, TypeVar, cast import cloudpickle +import numpy as np from adaptive.utils import load, save @@ -81,6 +82,7 @@ def _wrapped(loss_per_interval: Callable[_P, _R_co]) -> _NeighborLoss[_P, _R_co] DataType = dict[Any, Any] +_Bound: TypeAlias = float | np.floating[Any] | np.integer[Any] class BaseLearner(abc.ABC): diff --git a/adaptive/learner/data_saver.py b/adaptive/learner/data_saver.py index d0ce742e..65d2fd32 100644 --- a/adaptive/learner/data_saver.py +++ b/adaptive/learner/data_saver.py @@ -68,9 +68,7 @@ def __getattr__(self, attr: str) -> Any: return getattr(self.learner, attr) @copy_docstring_from(BaseLearner.tell) - def tell( - self, x: Any, result: Any - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell(self, x: Any, result: Any) -> None: y = self.arg_picker(result) self.extra_data[x] = result self.learner.tell(x, y) diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index 3110f275..beaf34b9 100644 --- a/adaptive/learner/integrator_learner.py +++ b/adaptive/learner/integrator_learner.py @@ -15,7 +15,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, _Bound from adaptive.notebook_integration import ensure_holoviews from adaptive.utils import assign_defaults, cache_latest, restore @@ -353,7 +353,7 @@ def __repr__(self) -> str: return " ".join(lst) -_Bounds: TypeAlias = Sequence[float] | NDArray[Any] +_Bounds: TypeAlias = Sequence[_Bound] | NDArray[Any] _Data: TypeAlias = tuple[ list[_Interval], dict[float, float], @@ -435,9 +435,7 @@ def approximating_intervals(self) -> set[_Interval]: assert self.first_ival.done_leaves is not None return self.first_ival.done_leaves - def tell( - self, point: float, value: float - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell(self, point: float, value: float) -> None: if point not in self.x_mapping: raise ValueError(f"Point {point} doesn't belong to any interval") self.data[point] = value @@ -729,5 +727,5 @@ def __setstate__(self, state: _State) -> None: function_pickle, bounds, tol, data = state function = cloudpickle.loads(function_pickle) # Retain virtual dispatch for subclasses that reuse this pickle state. - cast(Any, 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 5fd08def..4b4baf3b 100644 --- a/adaptive/learner/learner1D.py +++ b/adaptive/learner/learner1D.py @@ -11,8 +11,10 @@ import numpy as np from numpy.typing import NDArray +from adaptive.learner._sorted_types import ItemSortedDict, SortedDict from adaptive.learner.base_learner import ( BaseLearner, + _Bound, uses_nth_neighbors, ) from adaptive.learner.learnerND import volume @@ -33,36 +35,11 @@ with_pandas = False -_Key = TypeVar("_Key") -_Value = TypeVar("_Value") - if TYPE_CHECKING: - from collections.abc import KeysView - from holoviews.core import Overlay - - # The sorted mapping libraries are not typed. Their classes extend dict, - # but keys() also supports indexing and slicing in sorted order. - class _SortedKeys(KeysView[_Key], Sequence[_Key]): ... - - class SortedDict(dict[_Key, _Value]): - def keys(self) -> _SortedKeys[_Key]: ... # type: ignore[override] # ty: ignore[incompatible-method-override] - def bisect_left(self, key: _Key) -> int: ... - def index(self, key: _Key) -> int: ... - def peekitem(self, index: int = -1) -> tuple[_Key, _Value]: ... - - class ItemSortedDict(SortedDict[_Key, _Value]): - def __init__( - self, - key: Callable[[_Key, _Value], object], - mapping: Mapping[_Key, _Value] = ..., - ) -> None: ... else: Overlay = Any - from sortedcollections.recipes import ItemSortedDict - from sortedcontainers.sorteddict import SortedDict - Interval: TypeAlias = tuple[float, float] _Qual: TypeAlias = tuple[float, float, int] _IntervalKey = TypeVar("_IntervalKey", bound=Interval | _Qual) @@ -71,7 +48,7 @@ def __init__( _ScaledValue: TypeAlias = float | NDArray[Any] # The bulk tell path can store user-supplied sequences without conversion. Value: TypeAlias = _ScaledValue | Sequence[float] -_Bounds: TypeAlias = Sequence[float] | NDArray[Any] +_Bounds: TypeAlias = Sequence[_Bound] | NDArray[Any] # Callers may specialize the tuples for their configured neighbor count and # scalar or vector output; the learner does not know either statically. _IntervalLossCallback: TypeAlias = Callable[[Any, Any], float] @@ -319,6 +296,8 @@ def __init__( bounds: _Bounds, loss_per_interval: _IntervalLossCallback | None = None, ) -> None: + # NumPy bounds participate in the same arithmetic without coercion. + bounds = cast("Sequence[float]", bounds) self.function: Callable[[float], Any] = function self.nth_neighbors: int = getattr(loss_per_interval, "nth_neighbors", 0) @@ -520,16 +499,12 @@ 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)] - # The key lookup misses for an absent neighbor, represented by None. - ys = [self.data.get(cast(float, 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) - # The loss's nth_neighbors metadata determines whether the tuples - # include optional neighboring points, or just the interval itself. - loss = cast("NeighborLoss", self.loss_per_interval) - return loss(xs_scaled, ys_scaled) + return self.loss_per_interval(xs_scaled, ys_scaled) def _update_interpolated_loss_in_interval( self, x_left: float | None, x_right: float | None @@ -545,7 +520,8 @@ def _update_interpolated_loss_in_interval( a, b = x_left, None dx = x_right - x_left while b != x_right: - b = cast(float, self.neighbors_combined[a][1]) + b = self.neighbors_combined[a][1] + assert b is not None self.losses_combined[a, b] = (b - a) * loss / dx a = b @@ -559,7 +535,8 @@ def _update_losses(self, x: float, real: bool = True) -> None: a, b = self._find_neighbors(x, self.neighbors_combined) # (a, b) is splitted into (a, x) and (x, b) so if (a, b) exists - self.losses_combined.pop(cast(Interval, (a, b)), None) + if a is not None and b is not None: + self.losses_combined.pop((a, b), None) if real: # We need to update all interpolated losses in the interval @@ -571,14 +548,14 @@ def _update_losses(self, x: float, real: bool = True) -> None: # Since 'x' is in between (x_left, x_right), # we get rid of the interval. - old_interval = cast(Interval, (x_left, x_right)) - self.losses.pop(old_interval, None) - self.losses_combined.pop(old_interval, None) + if x_left is not None and x_right is not None: + self.losses.pop((x_left, x_right), None) + self.losses_combined.pop((x_left, x_right), None) elif x_left is not None and x_right is not None: # 'x' happens to be in between two real points, # so we can interpolate the losses. # Combined neighbors exist when there are real neighbors. - a, b = cast("Interval", (a, b)) + assert a is not None and b is not None dx = x_right - x_left loss = self.losses[x_left, x_right] self.losses_combined[a, x] = (x - a) * loss / dx @@ -608,12 +585,10 @@ def _update_neighbors(self, x: float, neighbors: NeighborsType) -> None: if x not in neighbors: # The point is new x_left, x_right = self._find_neighbors(x, neighbors) neighbors[x] = [x_left, x_right] - left: list[float | None] = neighbors.get(cast(float, x_left), [None, None]) - left[1] = x - right: list[float | None] = neighbors.get( - cast(float, x_right), [None, None] - ) - right[0] = x + if x_left is not None: + neighbors[x_left][1] = x + if x_right is not None: + neighbors[x_right][0] = x def _update_scale(self, x: float, y: _ScaledValue) -> None: """Update the scale with which the x and y-values are scaled. @@ -730,7 +705,7 @@ def tell_many( # Find the intervals for which the losses should be calculated. intervals, intervals_combined = ( - [(x_m, cast(float, x_r)) for x_m, (_, x_r) in neighbors.items()][:-1] + [(x_m, x_r) for x_m, (_, x_r) in neighbors.items() if x_r is not None] for neighbors in (self.neighbors, self.neighbors_combined) ) @@ -932,7 +907,7 @@ def __setstate__(self, state: _PickleState) -> None: function_bytes, bounds, loss_per_interval, losses, losses_combined, data = state function = cloudpickle.loads(function_bytes) # Retain virtual dispatch for AverageLearner1D and other subclasses. - cast(Any, 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) diff --git a/adaptive/learner/learner2D.py b/adaptive/learner/learner2D.py index 5523c928..4d91bc3f 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -71,9 +71,6 @@ def __call__(self, *coords: NDArray[np.float64]) -> NDArray[np.float64]: ... class _CloughTocherData(Protocol): grad: NDArray[np.float64] - class _HasMax(Protocol): - def max(self) -> float: ... - else: HoloMap = Overlay = Any @@ -782,9 +779,7 @@ def inside_bounds(self, xy: _PointInput) -> bool | np.bool_: (xmin, xmax), (ymin, ymax) = self.bounds return xmin <= x <= xmax and ymin <= y <= ymax - def tell( - self, point: _PointInput, value: _Value - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell(self, point: _PointInput, value: _Value) -> None: xy = cast(_Point, tuple(point)) self.data[xy] = value if not self.inside_bounds(xy): @@ -794,9 +789,7 @@ def tell( self._ip_combined = None self._stack.pop(xy, None) - def tell_pending( - self, point: _PointInput - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell_pending(self, point: _PointInput) -> None: xy = cast(_Point, tuple(point)) if not self.inside_bounds(xy): return @@ -884,8 +877,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) - # Unlike point selection, loss reporting expects an array result. - return cast("_HasMax", losses).max() + return float(np.max(losses)) def remove_unfinished(self) -> None: self.pending_points = set() @@ -983,6 +975,6 @@ def __setstate__(self, state: _State) -> None: function_pickle, bounds, loss_per_triangle, _stack, data = state function = cloudpickle.loads(function_pickle) # Retain virtual dispatch for subclasses that reuse this pickle state. - cast(Any, 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 b752a9eb..860ada09 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -26,6 +26,7 @@ from adaptive.learner.base_learner import ( BaseLearner, + _Bound, uses_nth_neighbors, ) from adaptive.learner.triangulation import ( @@ -75,16 +76,16 @@ _Array: TypeAlias = npt.NDArray[Any] _Value: TypeAlias = float | Sequence[float] | _Array _Values: TypeAlias = Sequence[_Value] | _Array -_Loss: TypeAlias = Callable[[_Array, _Array, float], SupportsFloat] +_Loss: TypeAlias = Callable[[_Array, _Array, float], SupportsFloat | _Array] _NeighborLoss: TypeAlias = Callable[ [_Array, _Array, float, list[_Array | None], list[_Value | None]], SupportsFloat ] # The user can specialize the simplex and neighbor types for their function. _SimplexLossCallback: TypeAlias = ( - Callable[[Any, Any, float], SupportsFloat] + Callable[[Any, Any, float], SupportsFloat | _Array] | Callable[[Any, Any, float, Any, Any], SupportsFloat] ) -_Bounds: TypeAlias = Sequence[Sequence[float]] | _Array | scipy.spatial.ConvexHull +_Bounds: TypeAlias = Sequence[Sequence[_Bound]] | _Array | scipy.spatial.ConvexHull _QueueItem: TypeAlias = tuple[float, _Simplex, _Simplex | None] _T = TypeVar("_T") @@ -161,7 +162,7 @@ def uniform_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> f return volume(simplex) -def std_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> float: +def std_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> _Array: """ Computes the loss of the simplex based on the standard deviation. @@ -176,7 +177,7 @@ def std_loss(simplex: _PointsLike, values: _Values, value_scale: float) -> float Returns ------- - loss : float + loss : numpy.ndarray """ # NumPy accepts sequences of array rows at runtime, too. @@ -428,12 +429,12 @@ class LearnerND(BaseLearner): def __init__( self, - func: Callable[[_Point], Any], + func: Callable[[Any], Any], bounds: _Bounds, loss_per_simplex: _SimplexLossCallback | None = None, *, anisotropic: bool = False, - triangulation_backend: str | _TriangulationClass = "auto", + triangulation_backend: str | type[Any] = "auto", ) -> None: self._triangulation_class = resolve_triangulation_class(triangulation_backend) self._vdim: int | None = None @@ -679,6 +680,11 @@ def tri(self) -> TriangulationProtocol | None: self._update_losses(set(), self._tri.simplices) return self._tri + def _require_tri(self) -> TriangulationProtocol: + tri = self.tri + assert tri is not None + return tri + @property def values(self) -> npt.NDArray[np.float64]: """Get the values from `data` as a numpy array.""" @@ -689,9 +695,7 @@ def points(self) -> npt.NDArray[np.float64]: """Get the points from `data` as a numpy array.""" return np.array(list(self.data.keys()), dtype=float) - def tell( - self, point: Iterable[float], value: _Value | None - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell(self, point: Iterable[float], value: _Value | None) -> None: point = tuple(point) if point in self.data: return # we already know about the point @@ -761,7 +765,7 @@ def get_local_transform_matrix(self, simplex: _Simplex | None) -> _Array: def _simplex_exists(self, simplex: Iterable[int]) -> bool: simplex = tuple(sorted(simplex)) - return simplex in cast(TriangulationProtocol, self.tri).simplices + return simplex in self._require_tri().simplices def inside_bounds(self, point: _PointLike) -> bool | np.bool_: """Check whether a point is inside the bounds.""" @@ -773,7 +777,7 @@ def inside_bounds(self, point: _PointLike) -> bool | np.bool_: (mn - eps) <= p <= (mx + eps) for p, (mn, mx) in zip(point, self._bbox) ) - def tell_pending( # ty: ignore[lost-keyword-for-regular-parameter] + def tell_pending( self, point: Iterable[float], *, simplex: _Simplex | None = None ) -> None: point = tuple(point) @@ -796,7 +800,7 @@ def _simplices_containing_point( ) -> list[_Simplex]: """All simplices of the triangulation containing `point`, found from the `simplex` hint when given.""" - tri = cast(TriangulationProtocol, self.tri) + tri = self._require_tri() if hasattr(tri, "simplices_containing"): # Rust backend: one call instead of a point_in_simplex loop. return cast(_BatchedTriangulation, tri).simplices_containing( @@ -820,7 +824,7 @@ def _add_pending_point_to_simplex( """Insert `point` into the subtriangulation of `simplex`, which must contain the point.""" if simplex not in self._subtriangulations: - vertices = cast(TriangulationProtocol, self.tri).get_vertices(simplex) + vertices = self._require_tri().get_vertices(simplex) self._subtriangulations[simplex] = self._triangulation_class(vertices) self._pending_to_simplex[point] = simplex @@ -830,7 +834,7 @@ def _try_adding_pending_point_to_simplex( self, point: _Point, simplex: _Simplex ) -> tuple[_SimplexSet, _SimplexSet] | tuple[None, None]: # try to insert it - if not cast(TriangulationProtocol, self.tri).point_in_simplex(point, simplex): + if not self._require_tri().point_in_simplex(point, simplex): return None, None return self._add_pending_point_to_simplex(point, simplex) @@ -839,7 +843,7 @@ def _update_subsimplex_losses( ) -> None: loss = self._losses[simplex] - loss_density = loss / cast(TriangulationProtocol, self.tri).volume(simplex) + loss_density = loss / self._require_tri().volume(simplex) subtriangulation = self._subtriangulations[simplex] for subsimplex in new_subsimplices: subloss = subtriangulation.volume(subsimplex) * loss_density @@ -891,14 +895,14 @@ def _pop_highest_existing_simplex(self) -> _QueueItem: loss, simplex, subsimplex = self._simplex_queue.pop(0) if ( subsimplex is None - and simplex in cast(TriangulationProtocol, self.tri).simplices + and simplex in self._require_tri().simplices and simplex not in self._subtriangulations ): return abs(loss), simplex, subsimplex if ( subsimplex is not None and simplex in self._subtriangulations - and simplex in cast(TriangulationProtocol, self.tri).simplices + and simplex in self._require_tri().simplices and subsimplex in self._subtriangulations[simplex].simplices ): return abs(loss), simplex, subsimplex @@ -959,7 +963,7 @@ def _ask(self) -> tuple[_Point, float]: def _compute_loss(self, simplex: _Simplex) -> float: # get the loss - tri = cast(TriangulationProtocol, self.tri) + tri = self._require_tri() vertices = tri.get_vertices(simplex) values = [self.data[tuple(v)] for v in vertices] @@ -981,13 +985,13 @@ def _compute_loss(self, simplex: _Simplex) -> float: neighbors = tri.get_opposing_vertices(simplex) neighbor_vertices = tri.get_vertices(neighbors) - data = cast("Mapping[_Point | None, _Value]", self.data) - neighbor_values = [data.get(x, None) for x in neighbor_vertices] - neighbor_points = cast("list[_Point | _Array | None]", neighbor_vertices) - - for i, point in enumerate(neighbor_points): - if point is not None: - neighbor_points[i] = point @ self._transform + neighbor_values = [ + self.data.get(x) if x is not None else None for x in neighbor_vertices + ] + neighbor_points = [ + point @ self._transform if point is not None else None + for point in neighbor_vertices + ] for i, value in enumerate(neighbor_values): if value is not None: @@ -1002,7 +1006,7 @@ def _compute_loss(self, simplex: _Simplex) -> float: scaled_vertices, scaled_values, self._output_multiplier, - cast("list[_Array | None]", neighbor_points), + neighbor_points, neighbor_values, ) ) @@ -1039,7 +1043,7 @@ def _update_losses( if self.nth_neighbors: points_of_added_simplices = set.union(*[set(s) for s in to_add]) - tri = cast(TriangulationProtocol, self.tri) + tri = self._require_tri() neighbors = ( tri.get_simplices_attached_to_points(points_of_added_simplices) - to_add ) @@ -1081,7 +1085,8 @@ def _recompute_all_losses(self) -> None: @property def _scale(self) -> float: # get the output scale - return cast(float, self._max_value) - cast(float, self._min_value) + assert self._max_value is not None and self._min_value is not None + return self._max_value - self._min_value def _update_range(self, new_output: _Value) -> bool: if self._min_value is None or self._max_value is None: @@ -1110,10 +1115,11 @@ def _update_range(self, new_output: _Value) -> bool: self._output_multiplier = scale_multiplier + assert self._old_scale is not None if self._old_scale == 0: scale_factor = math.inf if self._scale > 0 else 1 else: - scale_factor = self._scale / cast(float, self._old_scale) + scale_factor = self._scale / self._old_scale if scale_factor > self._recompute_losses_factor: self._old_scale = self._scale self._recompute_all_losses() @@ -1164,7 +1170,7 @@ def plot(self, n: int | None = None, tri_alpha: float = 0) -> Overlay: # Calculate how many grid points are needed. # factor from A=√3/4 * a² (equilateral triangle) scale_factor = np.prod(np.diag(self._transform)) - tri = cast(TriangulationProtocol, self.tri) + tri = self._require_tri() a_sq = np.sqrt(np.min(tri.volumes()) * scale_factor) n = max(10, int(0.658 / a_sq)) @@ -1176,7 +1182,7 @@ def plot(self, n: int | None = None, tri_alpha: float = 0) -> Overlay: im = hv.Image(np.rot90(z), bounds=lbrt) if tri_alpha: - tri = cast(TriangulationProtocol, self.tri) + tri = self._require_tri() points = np.array([tri.get_vertices(s) for s in tri.simplices]) points = np.pad( points[:, [0, 1, 2, 0], :], @@ -1241,7 +1247,7 @@ def plot_slice( # Calculate how many grid points are needed. # factor from A=√3/4 * a² (equilateral triangle) scale_factor = np.prod(np.diag(self._transform)) - tri = cast(TriangulationProtocol, self.tri) + tri = self._require_tri() a_sq = np.sqrt(np.min(tri.volumes()) * scale_factor) n = max(10, int(0.658 / a_sq)) @@ -1294,7 +1300,7 @@ def plot_3D( plots = [] - tri = cast(TriangulationProtocol, self.tri) + tri = self._require_tri() vertices = tri.vertices if with_triangulation: Xe: list[float | None] = [] @@ -1379,7 +1385,7 @@ def _get_iso( vertices: list[_Array] = [] # index -> (x,y,z) faces_or_lines: list[list[int]] = [] # indices of the corner points - tri = cast(TriangulationProtocol, self.tri) + tri = self._require_tri() data = cast("Mapping[_Point, float]", self.data) # scalar output checked above @functools.lru_cache @@ -1566,8 +1572,6 @@ def _get_plane_color(simplex: Iterable[int]) -> tuple[int, ...]: def _get_data(self) -> dict[str, Any]: return deepcopy(self.__dict__) - def _set_data( - self, state: Mapping[str, Any] - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def _set_data(self, state: Mapping[str, Any]) -> None: for k, v in state.items(): setattr(self, k, v) diff --git a/adaptive/learner/sequence_learner.py b/adaptive/learner/sequence_learner.py index 89118f7a..15c1157d 100644 --- a/adaptive/learner/sequence_learner.py +++ b/adaptive/learner/sequence_learner.py @@ -31,6 +31,12 @@ _Index: TypeAlias = int | np.integer[Any] PointType: TypeAlias = tuple[_Index, Any] +if TYPE_CHECKING: + + class _IndexedSequence(Sequence[Any]): + # Built-in sequences accept NumPy integers through __index__. + def __getitem__(self, index: _Index | slice, /) -> Any: ... + class _IgnoreFirstArgument: """Remove the first argument from the call signature. @@ -98,7 +104,7 @@ def __init__( indices = range(len(sequence)) self._to_do_indices: MutableSet[_Index] = SortedSet(indices) self._ntotal = len(sequence) - self.sequence = copy(sequence) + self.sequence = cast("_IndexedSequence", copy(sequence)) self.data = SortedDict() self.pending_points = set() @@ -115,7 +121,7 @@ def ask( for index in self._to_do_indices: if len(points) >= n: break - point = self.sequence[cast(int, index)] + point = self.sequence[index] indices.append(index) points.append((index, point)) loss_improvements.append(1 / self._ntotal) @@ -139,17 +145,13 @@ def remove_unfinished(self) -> None: self._to_do_indices.add(i) self.pending_points = set() - def tell( - self, point: PointType, value: Any - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell(self, point: PointType, value: Any) -> None: index, _ = point self.data[index] = value self.pending_points.discard(index) self._to_do_indices.discard(index) - def tell_pending( - self, point: PointType - ) -> None: # ty: ignore[lost-keyword-for-regular-parameter] + def tell_pending(self, point: PointType) -> None: index, _ = point self.pending_points.add(index) self._to_do_indices.discard(index) @@ -218,7 +220,7 @@ def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-ov ys = [self.data.get(i, pd.NA) for i in indices] else: indices, ys = zip(*self.data.items()) if self.data else ([], []) - sequence = [self.sequence[cast(int, i)] for i in indices] + sequence = [self.sequence[i] for i in indices] df = pandas.DataFrame(indices, columns=[index_name]) df[x_name] = sequence diff --git a/adaptive/learner/triangulation_backend.py b/adaptive/learner/triangulation_backend.py index 07a4efc8..3a15d996 100644 --- a/adaptive/learner/triangulation_backend.py +++ b/adaptive/learner/triangulation_backend.py @@ -106,7 +106,7 @@ def simplices_containing( _TriangulationClass: TypeAlias = type[TriangulationProtocol] -_TriangulationType = TypeVar("_TriangulationType", bound=TriangulationProtocol) +_TriangulationType = TypeVar("_TriangulationType") # Minimal version that is a complete drop-in for the learners: includes the # degenerate-simplex fix for curvature losses, plus the batched @@ -176,8 +176,8 @@ def resolve_triangulation_class(backend: str = "auto") -> _TriangulationClass: . def resolve_triangulation_class( - backend: str | _TriangulationClass = "auto", -) -> _TriangulationClass: + backend: str | type[Any] = "auto", +) -> type[Any]: """Return the `Triangulation` class to use for *backend*. Parameters @@ -205,7 +205,6 @@ def resolve_triangulation_class( TRIANGULATION_BACKEND: str = _select_backend() -Triangulation: _TriangulationClass rust_default_loss: Callable[[npt.NDArray[Any], npt.NDArray[Any], float], float] | None if TYPE_CHECKING or TRIANGULATION_BACKEND != "rust": @@ -233,10 +232,11 @@ def resolve_triangulation_class( simplex_volume_in_embedding, ) -if TRIANGULATION_BACKEND == "rust": - from adaptive_triangulation import Triangulation as _RustTriangulation - - Triangulation = cast(_TriangulationClass, _RustTriangulation) +if TYPE_CHECKING: + # Both implementations expose the Python class's core interface. + from adaptive.learner.triangulation import Triangulation as Triangulation +elif TRIANGULATION_BACKEND == "rust": + from adaptive_triangulation import Triangulation # The Rust implementation of `adaptive.learner.learnerND.default_loss`, # which `LearnerND` prefers when no loss is given. Defined here (rather @@ -246,9 +246,7 @@ def resolve_triangulation_class( rust_default_loss = _rust_default_loss else: - from adaptive.learner.triangulation import Triangulation as _PythonTriangulation - - Triangulation = _PythonTriangulation + from adaptive.learner.triangulation import Triangulation rust_default_loss = None diff --git a/adaptive/notebook_integration.py b/adaptive/notebook_integration.py index 4989e4cb..c8f3def1 100644 --- a/adaptive/notebook_integration.py +++ b/adaptive/notebook_integration.py @@ -17,14 +17,14 @@ from collections.abc import Iterator, Mapping from typing import Protocol - from holoviews import DynamicMap, Element + from holoviews.core import Dimensioned, DynamicMap from ipywidgets import HTML # IPython supplies this as a builtin; it is absent outside IPython. get_ipython: Callable[[], object] class _Plottable(Protocol): - def plot(self) -> Element: ... + def plot(self) -> Dimensioned: ... class _HasSamples(Protocol): @property @@ -35,7 +35,7 @@ class _HasLossCache(Protocol): def _cache(self) -> Mapping[str, float]: ... else: - DynamicMap = Element = HTML = Any + DynamicMap = Dimensioned = HTML = Any _holoviews_enabled = False @@ -124,7 +124,7 @@ def in_ipynb() -> bool: def live_plot( runner: adaptive.AsyncRunner[LearnerType], *, - plotter: Callable[[LearnerType], Element] | None = None, + plotter: Callable[[LearnerType], Dimensioned] | None = None, update_interval: float = 2, name: Hashable = None, normalize: bool = True, @@ -163,7 +163,7 @@ def live_plot( if name in active_plotting_tasks: active_plotting_tasks[name].cancel() - def plot_generator() -> Iterator[Element]: + def plot_generator() -> Iterator[Dimensioned]: while True: if not plotter: yield cast("_Plottable", runner.learner).plot() diff --git a/adaptive/runner.py b/adaptive/runner.py index 962579cc..b6e39af3 100644 --- a/adaptive/runner.py +++ b/adaptive/runner.py @@ -19,7 +19,13 @@ from adaptive import BalancingLearner, DataSaver, IntegratorLearner, SequenceLearner from adaptive.learner.base_learner import BaseLearner, LearnerType -from adaptive.notebook_integration import in_ipynb, live_info, live_plot +from adaptive.notebook_integration import ( + Dimensioned, + DynamicMap, + in_ipynb, + live_info, + live_plot, +) from adaptive.utils import SequentialExecutor FutureTypes: TypeAlias = concurrent.Future | asyncio.Future @@ -29,7 +35,6 @@ from typing import Protocol import distributed.cfexecutor - import holoviews import ipyparallel.client.view import mpi4py.futures @@ -292,8 +297,8 @@ def _process_futures( self._to_retry.pop(pid, None) self._tracebacks.pop(pid, None) x = self._id_to_point.pop(pid) - if self.do_log: - cast("list[_LogEntry]", self.log).append(("tell", x, y)) + if self.log is not None: + self.log.append(("tell", x, y)) self.learner.tell(x, y) def _get_futures( @@ -304,8 +309,8 @@ def _get_futures( # that have started since the last iteration. n_new_tasks = max(0, self._get_max_tasks() - len(self._pending_tasks)) - if self.do_log: - cast("list[_LogEntry]", self.log).append(("ask", n_new_tasks)) + if self.log is not None: + self.log.append(("ask", n_new_tasks)) pids, _ = self._ask(n_new_tasks) @@ -705,11 +710,11 @@ def block_until_done(self) -> None: def live_plot( self, *, - plotter: Callable[[LearnerType], holoviews.Element] | None = None, + plotter: Callable[[LearnerType], Dimensioned] | 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 diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index 060488b5..bce7a467 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -1,5 +1,7 @@ import inspect import pickle +import subprocess +import sys from collections.abc import Callable, Sequence from functools import partial from importlib.resources import files @@ -27,6 +29,8 @@ ) from adaptive import types as legacy_types from adaptive.learner.base_learner import uses_nth_neighbors +from adaptive.learner.learner2D import triangle_loss +from adaptive.learner.learnerND import std_loss from adaptive.notebook_integration import live_info, should_update from adaptive.runner import BaseRunner, Runner @@ -43,6 +47,14 @@ def test_py_typed_marker() -> None: assert files("adaptive").joinpath("py.typed").is_file() +def test_legacy_types_attribute_in_fresh_interpreter() -> None: + subprocess.run( + [sys.executable, "-c", "import adaptive; assert adaptive.types.Real"], + check=True, + timeout=20, + ) + + def test_legacy_numeric_aliases(): assert legacy_types.__all__ == ["Float", "Bool", "Int", "Real"] assert legacy_types.Float == float | np.float64 @@ -79,6 +91,8 @@ def loss(xs: list[float], *, scale: float = 1) -> float: utils.save, utils.load, BalancingLearner.plot, + BalancingLearner.to_dataframe, + BalancingLearner.load_dataframe, BalancingLearner.save, BalancingLearner.load, DataSaver.save, @@ -143,3 +157,19 @@ def test_integrator_bounds(bounds: Sequence[float] | NDArray[Any]) -> None: restored = pickle.loads(pickle.dumps(learner)) assert type(restored.bounds) is type(bounds) np.testing.assert_array_equal(restored.bounds, bounds) + + +def test_learner2d_loss_accepts_list_results() -> None: + learner = Learner2D(sum, [(0.0, 1.0), (0.0, 1.0)], loss_per_triangle=triangle_loss) + points, _ = learner.ask(4) + assert len(points) == 4 + for point in points: + learner.tell(point, learner.function(point)) + assert isinstance(learner.loss(), float) + assert np.isfinite(learner.loss()) + + +def test_std_loss_returns_array() -> None: + result = std_loss([(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)], [1.0, 2.0, 3.0], 1.0) + assert isinstance(result, np.ndarray) + assert result.shape == (1,) diff --git a/adaptive/utils.py b/adaptive/utils.py index 7517b858..a3a69f01 100644 --- a/adaptive/utils.py +++ b/adaptive/utils.py @@ -187,23 +187,15 @@ class SequentialExecutor(concurrent.Executor): This executor is mainly for testing. """ - if TYPE_CHECKING: - - def submit( - self, fn: Callable[P, T], /, *args: P.args, **kwargs: P.kwargs - ) -> concurrent.Future[T]: ... - - else: - - def submit( - 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: - fut.set_exception(e) - return fut + 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: + fut.set_exception(e) + return fut def map( self, @@ -230,21 +222,21 @@ def daskify( from dask import delayed def _daskify(func: Callable[P, T]) -> Callable[P, Awaitable[T]]: - if cache: - setattr(func, "cache", {}) # noqa: B010 + futures: dict[str, Awaitable[T]] | None = {} if cache else None + if futures is not None: + vars(func)["cache"] = futures delayed_func = delayed(func) @wraps(func) async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: - if cache: + if futures is not None: key = _cache_key(args, kwargs) - cached: dict[str, Awaitable[T]] = getattr(func, "cache") # noqa: B009 - future = cached.get(key) + future = futures.get(key) if future is None: future = client.compute(delayed_func(*args, **kwargs)) - getattr(func, "cache")[key] = future # noqa: B009 + futures[key] = future else: future = client.compute(delayed_func(*args, **kwargs)) diff --git a/pyproject.toml b/pyproject.toml index bc9dc6af..6d983da0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -134,6 +134,9 @@ python-version = "3.11" [tool.ty.src] exclude = ["adaptive/tests/**"] +[tool.ty.rules] +lost-keyword-for-regular-parameter = "ignore" + [tool.ty.analysis] respect-type-ignore-comments = true allowed-unresolved-imports = ["adaptive_triangulation", "mpi4py.**", "uvloop"] diff --git a/tests/typing_contract.py b/tests/typing_contract.py index 739713f2..93f87bea 100644 --- a/tests/typing_contract.py +++ b/tests/typing_contract.py @@ -3,13 +3,16 @@ from __future__ import annotations from collections.abc import Sequence -from typing import Any, assert_type +from typing import Any, assert_type, get_type_hints import numpy as np +from numpy.typing import NDArray from scipy.interpolate import LinearNDInterpolator from scipy.spatial import ConvexHull +import adaptive from adaptive import ( + AsyncRunner, AverageLearner, AverageLearner1D, BalancingLearner, @@ -20,8 +23,13 @@ Learner2D, LearnerND, SequenceLearner, + live_plot, ) +from adaptive.learner import triangulation_backend from adaptive.learner.base_learner import uses_nth_neighbors +from adaptive.learner.learner2D import triangle_loss as triangle_volume_loss +from adaptive.learner.learnerND import std_loss +from adaptive.utils import SequentialExecutor async def evaluate(x: float) -> float: @@ -143,6 +151,75 @@ def check_synchronous_round_trips() -> None: balancing.tell(indexed_x, balancing.function(indexed_x)) +def sphere(point: tuple[float, float, float]) -> float: + x, y, z = point + return x**2 + y**2 + z**2 + + +def check_numpy_scalar_inputs() -> None: + axis = (np.int64(0), np.float32(1)) + learner = Learner1D(square, axis) + AverageLearner1D(sample_point, axis) + IntegratorLearner(square, axis, tol=0.01) + LearnerND(sphere, [axis] * 3) + balancing = BalancingLearner([learner]) + balancing.tell((np.int64(0), 0.5), 0.25) + + +def check_plotter(runner: AsyncRunner[Learner1D]) -> None: + live_plot(runner, plotter=lambda learner: learner.plot()) + runner.live_plot(plotter=lambda learner: learner.plot()) + + +def check_triangulation_type(tri: triangulation_backend.Triangulation) -> None: + assert tri.simplices + + +def check_backend() -> None: + points = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)] + check_triangulation_type(triangulation_backend.Triangulation(points)) + + +def check_rust_backend() -> None: + from adaptive_triangulation import Triangulation as RustTriangulation + + rust_class: type[RustTriangulation] = ( + triangulation_backend.resolve_triangulation_class(RustTriangulation) + ) + assert rust_class is RustTriangulation + learner = LearnerND( + sphere, [(0.0, 1.0)] * 3, triangulation_backend=RustTriangulation + ) + for point in learner.ask(8)[0]: + learner.tell(point, learner.function(point)) + tri: object = learner.tri + assert isinstance(tri, RustTriangulation) + + +def identity(x: int) -> int: + return x + + +def legacy_real_alias() -> object: + return adaptive.types.Real + + +def check_dataframe_annotations() -> None: + assert get_type_hints(BalancingLearner.to_dataframe) + + +def check_keyword_submit_and_loss() -> None: + assert_type(SequentialExecutor().submit(fn=identity, x=7).result(), int) + points = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)] + assert_type(std_loss(points, [1.0, 2.0, 3.0], 1.0), NDArray[Any]) + LearnerND(sum, [(0.0, 1.0)] * 2, loss_per_simplex=std_loss) + + learner = Learner2D(sum, [(0.0, 1.0)] * 2, loss_per_triangle=triangle_volume_loss) + for point in learner.ask(4)[0]: + learner.tell(point, learner.function(point)) + assert_type(learner.loss(), float) + + class ExternalLearner(BaseLearner): def __init__(self) -> None: self.npoints = 0 From 2a0ee38cb74b3777063ec6f2ad84ce7e70d6a6d1 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 17:49:37 -0800 Subject: [PATCH 7/9] Preserve dynamic triangulation and dask cache contracts Type the selected backend as a concrete constructor returning the shared instance protocol. Keep Dask cache lookups on the original callback and retain the legacy types attribute without exporting it from wildcard imports. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/__init__.py | 3 +- adaptive/learner/_sorted_types.py | 12 ++--- adaptive/learner/learnerND.py | 18 +++---- adaptive/learner/triangulation_backend.py | 52 ++++++++++++-------- adaptive/tests/test_typing.py | 58 ++++++++++++++++++++++- adaptive/utils.py | 16 ++++--- tests/typing_contract.py | 24 ++++++++-- 7 files changed, 133 insertions(+), 50 deletions(-) diff --git a/adaptive/__init__.py b/adaptive/__init__.py index bae0e1aa..5dae0fe1 100644 --- a/adaptive/__init__.py +++ b/adaptive/__init__.py @@ -19,12 +19,11 @@ ) from adaptive.runner import AsyncRunner, BlockingRunner, Runner -from adaptive import learner, notebook_integration, runner, types, utils # isort:skip +from adaptive import learner, notebook_integration, runner, types as types, utils # isort:skip __all__ = [ "learner", "runner", - "types", "utils", "__version__", "AverageLearner", diff --git a/adaptive/learner/_sorted_types.py b/adaptive/learner/_sorted_types.py index fa75ef47..fdb4cab8 100644 --- a/adaptive/learner/_sorted_types.py +++ b/adaptive/learner/_sorted_types.py @@ -1,13 +1,13 @@ """Static interfaces for the untyped sorted mapping dependencies.""" -from collections.abc import Callable, KeysView, Mapping, Sequence -from typing import TYPE_CHECKING, TypeVar - -_Key = TypeVar("_Key") -_Value = TypeVar("_Value") +from typing import TYPE_CHECKING if TYPE_CHECKING: - from collections.abc import KeysView + from collections.abc import Callable, KeysView, Mapping, Sequence + from typing import TypeVar + + _Key = TypeVar("_Key") + _Value = TypeVar("_Value") # The sorted mapping libraries are not typed. Their classes extend dict, # but keys() also supports indexing and slicing in sorted order. diff --git a/adaptive/learner/learnerND.py b/adaptive/learner/learnerND.py index 860ada09..0486a8a0 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -39,10 +39,9 @@ ) from adaptive.learner.triangulation_backend import ( Triangulation, - TriangulationProtocol, _BatchedTriangulation, + _LearnerTriangulation, _SimplicesProxy, - _TriangulationClass, circumsphere, point_in_simplex, resolve_triangulation_class, @@ -422,7 +421,7 @@ class LearnerND(BaseLearner): # Class-level fallback so that learners restored from pickles made # before `triangulation_backend` existed keep working. - _triangulation_class: _TriangulationClass = Triangulation + _triangulation_class = cast("type[_LearnerTriangulation]", Triangulation) data: OrderedDict[_Point, _Value] pending_points: set[_Point] @@ -436,7 +435,10 @@ def __init__( anisotropic: bool = False, triangulation_backend: str | type[Any] = "auto", ) -> None: - self._triangulation_class = resolve_triangulation_class(triangulation_backend) + self._triangulation_class = cast( + "type[_LearnerTriangulation]", + resolve_triangulation_class(triangulation_backend), + ) self._vdim: int | None = None # Prefer the Rust implementation of the default loss when the Rust # backend is active; it computes the same embedded simplex volume. @@ -484,13 +486,13 @@ def __init__( ) self.function: Callable[[_Point], Any] = func - self._tri: TriangulationProtocol | None = None + self._tri: _LearnerTriangulation | None = None self._losses: dict[_Simplex, float] = {} self._pending_to_simplex: dict[_Point, _Simplex] = {} # vertex → simplex # triangulation of the pending points inside a specific simplex - self._subtriangulations: dict[_Simplex, TriangulationProtocol] = {} + self._subtriangulations: dict[_Simplex, _LearnerTriangulation] = {} # scale to unit hypercube # for the input @@ -663,7 +665,7 @@ def _ip(self) -> interpolate.LinearNDInterpolator: return interpolate.LinearNDInterpolator(self.points, self.values) @property - def tri(self) -> TriangulationProtocol | None: + def tri(self) -> _LearnerTriangulation | None: """An `adaptive.learner.triangulation.Triangulation` instance with all the points of the learner.""" if self._tri is not None: @@ -680,7 +682,7 @@ def tri(self) -> TriangulationProtocol | None: self._update_losses(set(), self._tri.simplices) return self._tri - def _require_tri(self) -> TriangulationProtocol: + def _require_tri(self) -> _LearnerTriangulation: tri = self.tri assert tri is not None return tri diff --git a/adaptive/learner/triangulation_backend.py b/adaptive/learner/triangulation_backend.py index 3a15d996..344503e5 100644 --- a/adaptive/learner/triangulation_backend.py +++ b/adaptive/learner/triangulation_backend.py @@ -19,14 +19,16 @@ Note that the pure-Python implementation in `adaptive.learner.triangulation` is always importable under its own name, regardless of the selected backend, -so pickles that reference it keep working. +so pickles that reference it keep working. Use ``Triangulation`` to construct +an instance of the selected backend, and ``TriangulationProtocol`` to annotate +instances from either backend. """ from __future__ import annotations import os -from collections.abc import Callable, Iterable, Iterator -from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, TypeVar, cast, overload +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, TypeVar, overload import numpy as np import numpy.typing as npt @@ -50,24 +52,25 @@ def __iter__(self) -> Iterator[_T_co]: ... def __len__(self) -> int: ... -class _SimplicesProxy(Protocol): - """The set operations the learners use on the Rust simplices proxy.""" - +class _SimplexCollection(Protocol): def __contains__(self, simplex: _Simplex, /) -> bool: ... - def __rsub__(self, other: _SimplexSet, /) -> _SimplexSet: ... def __iter__(self) -> Iterator[_Simplex]: ... def __len__(self) -> int: ... +class _SimplicesProxy(_SimplexCollection, Protocol): + def __rsub__(self, other: _SimplexSet, /) -> _SimplexSet: ... + + class TriangulationProtocol(Protocol): - """The triangulation interface shared by the learners' backends.""" + """The common instance interface, including Rust's read-only views.""" def __init__(self, coords: _PointsLike) -> None: ... @property def vertices(self) -> _Indexable[_Point]: ... @property - def simplices(self) -> _SimplexSet | _SimplicesProxy: ... + def simplices(self) -> _SimplexCollection: ... @property def vertex_to_simplices(self) -> _Indexable[_SimplexSet]: ... @property @@ -75,13 +78,10 @@ def dim(self) -> int: ... @property def hull(self) -> set[int]: ... - @overload - def get_vertices(self, indices: Iterable[int]) -> list[_Point]: ... - @overload - def get_vertices(self, indices: Iterable[int | None]) -> list[_Point | None]: ... + def get_vertices(self, indices: Sequence[int]) -> list[_Point]: ... def locate_point(self, point: _PointLike) -> _Simplex: ... def point_in_simplex( - self, point: _PointLike, simplex: Iterable[int], eps: float = 1e-8 + self, point: _PointLike, simplex: Sequence[int], eps: float = 1e-8 ) -> bool | np.bool_: ... def add_point( self, @@ -89,15 +89,26 @@ def add_point( simplex: _Simplex | None = None, transform: _PointsLike | None = None, ) -> tuple[_SimplexSet, _SimplexSet]: ... - def volume(self, simplex: Iterable[int]) -> float: ... + def volume(self, simplex: Sequence[int]) -> float: ... def volumes(self) -> list[float]: ... + + +class _LearnerTriangulation(TriangulationProtocol, Protocol): + # These operations work at runtime but are absent from the Rust 0.3.1 stubs. + @property + def simplices(self) -> _SimplexSet | _SimplicesProxy: ... + + @overload + def get_vertices(self, indices: Iterable[int]) -> list[_Point]: ... + @overload + def get_vertices(self, indices: Iterable[int | None]) -> list[_Point | None]: ... def get_opposing_vertices(self, simplex: _Simplex) -> tuple[int | None, ...]: ... def get_simplices_attached_to_points( self, indices: Iterable[int] ) -> _SimplexSet: ... -class _BatchedTriangulation(TriangulationProtocol, Protocol): +class _BatchedTriangulation(_LearnerTriangulation, Protocol): """Optional accelerated query; callers must first check for it.""" def simplices_containing( @@ -143,9 +154,7 @@ def _import_rust_triangulation() -> _TriangulationClass: ) from adaptive_triangulation import Triangulation - # The Rust stubs omit the neighbor-query methods and the None overload - # of get_vertices; the extension implements all of them. - return cast(_TriangulationClass, Triangulation) + return Triangulation def _select_backend() -> str: @@ -233,8 +242,8 @@ def resolve_triangulation_class( ) if TYPE_CHECKING: - # Both implementations expose the Python class's core interface. - from adaptive.learner.triangulation import Triangulation as Triangulation + # The runtime binding is one of two concrete classes, not the protocol. + Triangulation: _TriangulationClass elif TRIANGULATION_BACKEND == "rust": from adaptive_triangulation import Triangulation @@ -253,6 +262,7 @@ def resolve_triangulation_class( __all__ = [ "TRIANGULATION_BACKEND", "Triangulation", + "TriangulationProtocol", "resolve_triangulation_class", "circumsphere", "fast_2d_circumcircle", diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index bce7a467..fa307129 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -1,11 +1,23 @@ +from __future__ import annotations + +import asyncio import inspect import pickle import subprocess import sys from collections.abc import Callable, Sequence +from dataclasses import dataclass from functools import partial from importlib.resources import files -from typing import TYPE_CHECKING, Any, assert_type, get_args, get_origin, get_type_hints +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + assert_type, + get_args, + get_origin, + get_type_hints, +) import numpy as np import pytest @@ -48,8 +60,15 @@ def test_py_typed_marker() -> None: def test_legacy_types_attribute_in_fresh_interpreter() -> None: + code = ( + "import adaptive, types; " + "assert adaptive.types.Real; " + "stdlib_types = types; " + "from adaptive import *; " + "assert types is stdlib_types" + ) subprocess.run( - [sys.executable, "-c", "import adaptive; assert adaptive.types.Real"], + [sys.executable, "-c", code], check=True, timeout=20, ) @@ -173,3 +192,38 @@ def test_std_loss_returns_array() -> None: result = std_loss([(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)], [1.0, 2.0, 3.0], 1.0) assert isinstance(result, np.ndarray) assert result.shape == (1,) + + +def test_daskify_caches_class_callbacks_and_honors_cache_replacement() -> None: + pytest.importorskip("dask") + + @dataclass + class Result: + x: int + cache: ClassVar[dict[str, asyncio.Future[Result]]] + + class Client: + calls = 0 + + def compute(self, job: Any) -> asyncio.Future[Result]: + self.calls += 1 + future: asyncio.Future[Result] = asyncio.get_running_loop().create_future() + future.set_result(job.compute(scheduler="synchronous")) + return future + + async def run() -> None: + client: Any = Client() + wrapped = utils.daskify(client, cache=True)(Result) + assert await wrapped(7) == Result(7) + cache = Result.cache + assert len(cache) == 1 + assert await wrapped(7) == Result(7) + assert client.calls == 1 + + Result.cache = {} + assert await wrapped(7) == Result(7) + assert client.calls == 2 + assert Result.cache.keys() == cache.keys() + assert Result.cache["7"] is not cache["7"] + + asyncio.run(run()) diff --git a/adaptive/utils.py b/adaptive/utils.py index a3a69f01..ca65a5a1 100644 --- a/adaptive/utils.py +++ b/adaptive/utils.py @@ -216,27 +216,31 @@ def _cache_key(args: tuple[Any, ...], kwargs: dict[str, Any]) -> str: return "_".join(arg_strings + kwarg_strings) +class _DaskCache(Protocol[T]): + cache: dict[str, Awaitable[T]] + + def daskify( client: AsyncDaskClient, cache: bool = False ) -> Callable[[Callable[P, T]], Callable[P, Awaitable[T]]]: from dask import delayed def _daskify(func: Callable[P, T]) -> Callable[P, Awaitable[T]]: - futures: dict[str, Awaitable[T]] | None = {} if cache else None - if futures is not None: - vars(func)["cache"] = futures + cached_func = cast("_DaskCache[T]", func) + if cache: + cached_func.cache = {} delayed_func = delayed(func) @wraps(func) async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: - if futures is not None: + if cache: key = _cache_key(args, kwargs) - future = futures.get(key) + future = cached_func.cache.get(key) if future is None: future = client.compute(delayed_func(*args, **kwargs)) - futures[key] = future + cached_func.cache[key] = future else: future = client.compute(delayed_func(*args, **kwargs)) diff --git a/tests/typing_contract.py b/tests/typing_contract.py index 93f87bea..9d3cce30 100644 --- a/tests/typing_contract.py +++ b/tests/typing_contract.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Sequence -from typing import Any, assert_type, get_type_hints +from typing import TYPE_CHECKING, Any, assert_type, get_type_hints import numpy as np from numpy.typing import NDArray @@ -25,7 +25,7 @@ SequenceLearner, live_plot, ) -from adaptive.learner import triangulation_backend +from adaptive.learner import triangulation, triangulation_backend from adaptive.learner.base_learner import uses_nth_neighbors from adaptive.learner.learner2D import triangle_loss as triangle_volume_loss from adaptive.learner.learnerND import std_loss @@ -171,13 +171,24 @@ def check_plotter(runner: AsyncRunner[Learner1D]) -> None: runner.live_plot(plotter=lambda learner: learner.plot()) -def check_triangulation_type(tri: triangulation_backend.Triangulation) -> None: - assert tri.simplices +def triangulation_dim(tri: triangulation_backend.TriangulationProtocol) -> int: + return tri.dim def check_backend() -> None: points = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)] - check_triangulation_type(triangulation_backend.Triangulation(points)) + assert triangulation_dim(triangulation_backend.Triangulation(points)) == 2 + assert ( + triangulation_dim(triangulation_backend.resolve_triangulation_class()(points)) + == 2 + ) + assert triangulation_dim(triangulation.Triangulation(points)) == 2 + + if TYPE_CHECKING: + # The active backend may expose a read-only proxy, not a list. The + # unused-ignore checks must fail if copy() ever becomes accepted. + triangulation_backend.Triangulation(points).vertices.copy() # type: ignore[attr-defined] # ty: ignore[missing-attribute] + triangulation_backend.resolve_triangulation_class()(points).vertices.copy() # type: ignore[attr-defined] # ty: ignore[missing-attribute] def check_rust_backend() -> None: @@ -187,6 +198,9 @@ def check_rust_backend() -> None: triangulation_backend.resolve_triangulation_class(RustTriangulation) ) assert rust_class is RustTriangulation + points = [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)] + assert triangulation_dim(RustTriangulation(points)) == 2 + assert triangulation_dim(rust_class(points)) == 2 learner = LearnerND( sphere, [(0.0, 1.0)] * 3, triangulation_backend=RustTriangulation ) From 738bf0802b4164caa6e4c6b7f497d98a6e4ef2f1 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 18:04:19 -0800 Subject: [PATCH 8/9] Preserve stored callback signatures and accept integer triangle losses Keep scalar constructor contracts without restricting calls to stored callbacks. Normalize only loss results that cannot be marked with negative infinity during point selection. Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/learner/average_learner.py | 2 +- adaptive/learner/average_learner1D.py | 1 - adaptive/learner/integrator_learner.py | 2 +- adaptive/learner/learner1D.py | 2 +- adaptive/learner/learner2D.py | 17 +++++++++++++---- adaptive/learner/learnerND.py | 2 +- adaptive/learner/sequence_learner.py | 2 +- adaptive/tests/test_typing.py | 15 +++++++++++++-- tests/typing_contract.py | 26 ++++++++++++++++++++++++++ 9 files changed, 57 insertions(+), 12 deletions(-) diff --git a/adaptive/learner/average_learner.py b/adaptive/learner/average_learner.py index 374ca73a..11da98c7 100644 --- a/adaptive/learner/average_learner.py +++ b/adaptive/learner/average_learner.py @@ -81,7 +81,7 @@ def __init__( self.data = {} self.pending_points = set() - self.function: Callable[[int], Any] = function + self.function: Callable[..., Any] = function self.atol = atol self.rtol = rtol self.npoints = 0 diff --git a/adaptive/learner/average_learner1D.py b/adaptive/learner/average_learner1D.py index 86c41dc5..95df938e 100644 --- a/adaptive/learner/average_learner1D.py +++ b/adaptive/learner/average_learner1D.py @@ -89,7 +89,6 @@ class AverageLearner1D(Learner1D): # The public sampling interface uses (seed, x) rather than x, while # the inherited interval calculations still use the real coordinate x. if TYPE_CHECKING: - function: Callable[[Point], Any] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] pending_points: set[Point] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] data: dict[float, float] # type: ignore[assignment] # ty: ignore[incompatible-attribute-override] diff --git a/adaptive/learner/integrator_learner.py b/adaptive/learner/integrator_learner.py index beaf34b9..824cfdda 100644 --- a/adaptive/learner/integrator_learner.py +++ b/adaptive/learner/integrator_learner.py @@ -409,7 +409,7 @@ def __init__( plot : hv.Scatter Plots all the points that are evaluated. """ - self.function = function + self.function: Callable[..., Any] = function self.bounds = bounds self.tol = tol self.max_ivals = 1000 diff --git a/adaptive/learner/learner1D.py b/adaptive/learner/learner1D.py index 4b4baf3b..344e3468 100644 --- a/adaptive/learner/learner1D.py +++ b/adaptive/learner/learner1D.py @@ -298,7 +298,7 @@ def __init__( ) -> None: # NumPy bounds participate in the same arithmetic without coercion. bounds = cast("Sequence[float]", bounds) - self.function: Callable[[float], Any] = function + self.function: Callable[..., Any] = function self.nth_neighbors: int = getattr(loss_per_interval, "nth_neighbors", 0) self.loss_per_interval: _IntervalLossCallback = ( diff --git a/adaptive/learner/learner2D.py b/adaptive/learner/learner2D.py index 4d91bc3f..982bfbe9 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -3,7 +3,7 @@ import itertools import warnings from collections import OrderedDict -from collections.abc import Callable, Iterable, Sequence, Sized +from collections.abc import Callable, Iterable, MutableSequence, Sequence, Sized from copy import copy from math import sqrt from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, cast @@ -43,7 +43,9 @@ | Iterable[float] | NDArray[np.floating | np.integer] ) -_TriangleLoss: TypeAlias = Callable[[Any], NDArray[np.floating] | list[float]] +_TriangleLoss: TypeAlias = Callable[ + [Any], NDArray[np.floating[Any] | np.integer[Any]] | Sequence[float] +] _State: TypeAlias = tuple[ bytes, tuple[_Point, _Point], @@ -507,7 +509,7 @@ def __init__( self._bounds_points = cast(list[_Point], list(itertools.product(*bounds))) self._stack.update(dict.fromkeys(self._bounds_points, np.inf)) - self.function = function + self.function: Callable[..., Any] = function self._ip: LinearNDInterpolator | None = None self._ip_combined: LinearNDInterpolator | None = None @@ -805,6 +807,13 @@ def _fill_stack(self, stack_till: int = 1) -> tuple[list[_Point], list[float]]: ip = self._interpolator_combined() losses = self.loss_per_triangle(ip) + # Point selection marks used triangles with -inf. Copy only results + # that cannot be updated in place. + if isinstance(losses, np.ndarray): + if losses.dtype.kind in "iu" or not losses.flags.writeable: + losses = losses.astype(float) + elif not isinstance(losses, MutableSequence): + losses = list(losses) interp = cast("_LinearInterpolatorData", ip) # np.clip results in numerical precision problems @@ -815,7 +824,7 @@ def clip(x: float, lo: float, up: float) -> float: points_new = [] losses_new = [] for _j, _ in enumerate(losses): - jsimplex = np.argmax(losses) + jsimplex = int(np.argmax(losses)) tri = interp.tri triangle = tri.points[tri.simplices[jsimplex]] point = choose_point_in_triangle(triangle, max_badness=5) diff --git a/adaptive/learner/learnerND.py b/adaptive/learner/learnerND.py index 0486a8a0..28587ccb 100644 --- a/adaptive/learner/learnerND.py +++ b/adaptive/learner/learnerND.py @@ -485,7 +485,7 @@ def __init__( f"LearnerND only supports dim >= 2 (got ndim={self.ndim})." ) - self.function: Callable[[_Point], Any] = func + self.function: Callable[..., Any] = func self._tri: _LearnerTriangulation | None = None self._losses: dict[_Simplex, float] = {} diff --git a/adaptive/learner/sequence_learner.py b/adaptive/learner/sequence_learner.py index 15c1157d..cae7833e 100644 --- a/adaptive/learner/sequence_learner.py +++ b/adaptive/learner/sequence_learner.py @@ -98,7 +98,7 @@ def __init__( sequence: Sequence[Any], ) -> None: self._original_function = function - self.function = _IgnoreFirstArgument(function) + self.function: Callable[..., Any] = _IgnoreFirstArgument(function) # prefer range(len(...)) over enumerate to avoid slowdowns # when passing lazy sequences indices = range(len(sequence)) diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index fa307129..dfb6b76e 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -178,14 +178,25 @@ def test_integrator_bounds(bounds: Sequence[float] | NDArray[Any]) -> None: np.testing.assert_array_equal(restored.bounds, bounds) -def test_learner2d_loss_accepts_list_results() -> None: - learner = Learner2D(sum, [(0.0, 1.0), (0.0, 1.0)], loss_per_triangle=triangle_loss) +@pytest.mark.parametrize( + "loss_per_triangle", + [triangle_loss, lambda _: np.array([2, 1], dtype=np.int64), lambda _: (2.0, 1.0)], + ids=["list", "integer-array", "tuple"], +) +def test_learner2d_accepts_custom_loss_results( + loss_per_triangle: Callable[..., Any], +) -> None: + learner = Learner2D( + sum, [(0.0, 1.0), (0.0, 1.0)], loss_per_triangle=loss_per_triangle + ) points, _ = learner.ask(4) assert len(points) == 4 for point in points: learner.tell(point, learner.function(point)) assert isinstance(learner.loss(), float) assert np.isfinite(learner.loss()) + points, _ = learner.ask(2) + assert len(points) == 2 def test_std_loss_returns_array() -> None: diff --git a/tests/typing_contract.py b/tests/typing_contract.py index 9d3cce30..af43e7d2 100644 --- a/tests/typing_contract.py +++ b/tests/typing_contract.py @@ -103,6 +103,32 @@ def square(x: float) -> float: return x**2 +def vectorized_square( + x: float | NDArray[np.float64], *, scale: float = 1.0 +) -> float | NDArray[np.float64]: + return scale * x**2 + + +def check_callback_arguments() -> None: + learner = Learner1D(vectorized_square, (0.0, 1.0)) + xs = np.linspace(0.0, 1.0, 5) + assert np.allclose(learner.function(xs), xs**2) + assert learner.function(0.5, scale=2.0) == 0.5 + + +def integer_triangle_loss(ip: LinearNDInterpolator) -> NDArray[np.int64]: + return np.array([2, 1], dtype=np.int64) + + +def check_integer_triangle_loss() -> None: + learner = Learner2D(sum, [(0.0, 1.0)] * 2, loss_per_triangle=integer_triangle_loss) + for point in learner.ask(4)[0]: + learner.tell(point, learner.function(point)) + assert learner.loss() == 2.0 + points, _ = learner.ask(2) + assert len(points) == 2 + + def sample_point(seed_x: tuple[int, float]) -> float: return square(seed_x[1]) From cd7e1e0dd39533a00f92719f881171899a6fd5c3 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 5 Dec 2026 18:07:55 -0800 Subject: [PATCH 9/9] Handle integer sequence triangle losses Assisted-by: MindRoom DevAgent:openai/gpt-6.2-sol --- adaptive/learner/learner2D.py | 4 ++-- adaptive/tests/test_typing.py | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/adaptive/learner/learner2D.py b/adaptive/learner/learner2D.py index 982bfbe9..01cd8a77 100644 --- a/adaptive/learner/learner2D.py +++ b/adaptive/learner/learner2D.py @@ -3,7 +3,7 @@ import itertools import warnings from collections import OrderedDict -from collections.abc import Callable, Iterable, MutableSequence, Sequence, Sized +from collections.abc import Callable, Iterable, Sequence, Sized from copy import copy from math import sqrt from typing import TYPE_CHECKING, Any, Protocol, TypeAlias, cast @@ -812,7 +812,7 @@ def _fill_stack(self, stack_till: int = 1) -> tuple[list[_Point], list[float]]: if isinstance(losses, np.ndarray): if losses.dtype.kind in "iu" or not losses.flags.writeable: losses = losses.astype(float) - elif not isinstance(losses, MutableSequence): + elif not isinstance(losses, list): losses = list(losses) interp = cast("_LinearInterpolatorData", ip) diff --git a/adaptive/tests/test_typing.py b/adaptive/tests/test_typing.py index dfb6b76e..97ea436c 100644 --- a/adaptive/tests/test_typing.py +++ b/adaptive/tests/test_typing.py @@ -1,5 +1,6 @@ from __future__ import annotations +import array import asyncio import inspect import pickle @@ -180,8 +181,13 @@ def test_integrator_bounds(bounds: Sequence[float] | NDArray[Any]) -> None: @pytest.mark.parametrize( "loss_per_triangle", - [triangle_loss, lambda _: np.array([2, 1], dtype=np.int64), lambda _: (2.0, 1.0)], - ids=["list", "integer-array", "tuple"], + [ + triangle_loss, + lambda _: np.array([2, 1], dtype=np.int64), + lambda _: array.array("i", [2, 1]), + lambda _: (2.0, 1.0), + ], + ids=["list", "numpy-integer-array", "integer-array", "tuple"], ) def test_learner2d_accepts_custom_loss_results( loss_per_triangle: Callable[..., Any],