Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/typecheck.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Type checking

on:
pull_request:
push:
branches: [main]

jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.13"
- name: Install uv
uses: astral-sh/setup-uv@v6
- name: Install dependencies and type checkers
run: |
uv venv --python 3.13
uv pip install '.[test,other,notebook]' scipy-stubs==1.18.1.1 pandas-stubs==3.1.2.261202 ty==1.2.0 mypy==2.4.1
- name: Run ty
run: .venv/bin/ty check --error-on-warning --python .venv adaptive tests/typing_contract.py
- name: Run mypy
run: .venv/bin/mypy adaptive tests/typing_contract.py
20 changes: 0 additions & 20 deletions .github/workflows/typeguard.yml

This file was deleted.

4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ repos:
args: ["ruff", "--fix", "--ignore=E402,B018,F704"]
additional_dependencies: [jupytext, ruff]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v1.15.0"
rev: "v2.4.1"
hooks:
- id: mypy
exclude: ipynb_filter.py
files: ^adaptive/
4 changes: 2 additions & 2 deletions adaptive/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
)
from adaptive.runner import AsyncRunner, BlockingRunner, Runner

from adaptive import learner, runner, utils # isort:skip
from adaptive import learner, notebook_integration, runner, types as types, utils # isort:skip

__all__ = [
"learner",
Expand All @@ -46,4 +46,4 @@
]

# to avoid confusion with `notebook_extension`
del notebook_integration # type: ignore[name-defined] # noqa: F821
del notebook_integration
24 changes: 0 additions & 24 deletions adaptive/_types.py

This file was deleted.

32 changes: 32 additions & 0 deletions adaptive/learner/_sorted_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Static interfaces for the untyped sorted mapping dependencies."""

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from collections.abc import Callable, KeysView, Mapping, Sequence
from typing import TypeVar

_Key = TypeVar("_Key")
_Value = TypeVar("_Value")

# The sorted mapping libraries are not typed. Their classes extend dict,
# but keys() also supports indexing and slicing in sorted order.
class _SortedKeys(KeysView[_Key], Sequence[_Key]): ...

class SortedDict(dict[_Key, _Value]):
def keys(self) -> _SortedKeys[_Key]: ... # type: ignore[override] # ty: ignore[incompatible-method-override]
def bisect_left(self, key: _Key) -> int: ...
def index(self, key: _Key) -> int: ...
def peekitem(self, index: int = -1) -> tuple[_Key, _Value]: ...

class ItemSortedDict(SortedDict[_Key, _Value]):
def __init__(
self,
key: Callable[[_Key, _Value], object],
mapping: Mapping[_Key, _Value] = ...,
) -> None: ...
else:
from sortedcollections.recipes import ItemSortedDict
from sortedcontainers.sorteddict import SortedDict

__all__ = ["ItemSortedDict", "SortedDict"]
74 changes: 46 additions & 28 deletions adaptive/learner/average_learner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@

from collections.abc import Callable
from math import sqrt
from typing import TYPE_CHECKING, Any, TypeAlias, cast

import cloudpickle
import numpy as np
from numpy.typing import NDArray

from adaptive.learner.base_learner import BaseLearner
from adaptive.notebook_integration import ensure_holoviews
from adaptive.types import Float, Int, Real
from adaptive.utils import (
assign_defaults,
cache_latest,
partial_function_from_dataframe,
)

if TYPE_CHECKING:
from holoviews.element import Histogram
else:
Histogram = Any

try:
import pandas

Expand All @@ -24,6 +30,11 @@
with_pandas = False


_Seed: TypeAlias = int | np.integer[Any]
_Sample: TypeAlias = float | np.float64 | np.int_
_AverageData: TypeAlias = tuple[dict[_Seed, _Sample], int, _Sample, _Sample]


class AverageLearner(BaseLearner):
"""A naive implementation of adaptive computing of averages.

Expand All @@ -49,9 +60,14 @@ class AverageLearner(BaseLearner):
Number of evaluated points.
"""

data: dict[_Seed, _Sample]
pending_points: set[_Seed]

npoints: int

def __init__(
self,
function: Callable[[int], Real],
function: Callable[[int], Any],
atol: float | None = None,
rtol: float | None = None,
min_npoints: int = 2,
Expand All @@ -65,14 +81,14 @@ def __init__(

self.data = {}
self.pending_points = set()
self.function = function # type: ignore
self.function: Callable[..., Any] = function
self.atol = atol
self.rtol = rtol
self.npoints = 0
# Cannot estimate standard deviation with fewer than 2 points.
self.min_npoints = max(min_npoints, 2)
self.sum_f: Real = 0.0
self.sum_f_sq: Real = 0.0
self.sum_f: _Sample = 0.0
self.sum_f_sq: _Sample = 0.0

def new(self) -> AverageLearner:
"""Create a copy of `~adaptive.AverageLearner` without the data."""
Expand All @@ -82,11 +98,11 @@ def new(self) -> AverageLearner:
def n_requested(self) -> int:
return self.npoints + len(self.pending_points)

def to_numpy(self):
def to_numpy(self) -> NDArray[Any]:
"""Data as NumPy array of size (npoints, 2) with seeds and values."""
return np.array(sorted(self.data.items()))

def to_dataframe( # type: ignore[override]
def to_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override]
self,
with_default_function_args: bool = True,
function_prefix: str = "function.",
Expand Down Expand Up @@ -126,14 +142,14 @@ def to_dataframe( # type: ignore[override]
assign_defaults(self.function, df, function_prefix)
return df

def load_dataframe( # type: ignore[override]
def load_dataframe( # type: ignore[override] # ty: ignore[incompatible-method-override]
self,
df: pandas.DataFrame,
with_default_function_args: bool = True,
function_prefix: str = "function.",
seed_name: str = "seed",
y_name: str = "y",
):
) -> None:
"""Load data from a `pandas.DataFrame`.

If ``with_default_function_args`` is True, then ``learner.function``'s
Expand All @@ -160,7 +176,7 @@ def load_dataframe( # type: ignore[override]
self.function, df, function_prefix
)

def ask(self, n: int, tell_pending: bool = True) -> tuple[list[int], list[Float]]:
def ask(self, n: int, tell_pending: bool = True) -> tuple[list[int], list[float]]:
points = list(range(self.n_requested, self.n_requested + n))

if any(p in self.data or p in self.pending_points for p in points):
Expand All @@ -177,7 +193,7 @@ def ask(self, n: int, tell_pending: bool = True) -> tuple[list[int], list[Float]
self.tell_pending(p)
return points, loss_improvements

def tell(self, n: Int, value: Real) -> None:
def tell(self, n: _Seed, value: _Sample) -> None:
if n in self.data:
# The point has already been added before.
return
Expand All @@ -188,16 +204,17 @@ def tell(self, n: Int, value: Real) -> None:
self.sum_f_sq += value**2
self.npoints += 1

def tell_pending(self, n: int) -> None:
def tell_pending(self, n: _Seed) -> None:
self.pending_points.add(n)

@property
def mean(self) -> Float:
def mean(self) -> float:
"""The average of all values in `data`."""
return self.sum_f / self.npoints
# Division of these real scalars produces a float or a numpy.float64.
return cast(float, self.sum_f / self.npoints)

@property
def std(self) -> Float:
def std(self) -> float:
"""The corrected sample standard deviation of the values
in `data`."""
n = self.npoints
Expand All @@ -210,11 +227,9 @@ def std(self) -> Float:
return sqrt(numerator / (n - 1))

@cache_latest
def loss(self, real: bool = True, *, n=None) -> Float:
def loss(self, real: bool = True, *, n: int | None = None) -> float:
if n is None:
n = self.npoints if real else self.n_requested
else:
n = n
if min(self.npoints, n) < self.min_npoints:
return np.inf
standard_error = self.std / sqrt(n)
Expand All @@ -225,18 +240,18 @@ def loss(self, real: bool = True, *, n=None) -> Float:
rloss /= abs(mean)
return max(aloss, rloss)

def _loss_improvement(self, n: int) -> Float:
def _loss_improvement(self, n: int) -> float:
loss = self.loss()
if np.isfinite(loss):
return loss - self.loss(n=self.npoints + n)
else:
return np.inf

def remove_unfinished(self):
def remove_unfinished(self) -> None:
"""Remove uncomputed data from the learner."""
self.pending_points = set()

def plot(self):
def plot(self) -> Histogram:
"""Returns a histogram of the evaluated data.

Returns
Expand All @@ -251,13 +266,13 @@ def plot(self):
vals = hv.Points(vals)
return hv.operation.histogram(vals, num_bins=num_bins, dimension="y")

def _get_data(self) -> tuple[dict[int, Real], int, Real, Real]:
def _get_data(self) -> _AverageData:
return (self.data, self.npoints, self.sum_f, self.sum_f_sq)

def _set_data(self, data: tuple[dict[int, Real], int, Real, Real]) -> None:
def _set_data(self, data: _AverageData) -> None:
self.data, self.npoints, self.sum_f, self.sum_f_sq = data

def __getstate__(self):
def __getstate__(self) -> tuple[bytes, float, float, int, _AverageData]:
return (
cloudpickle.dumps(self.function),
self.atol,
Expand All @@ -266,8 +281,11 @@ def __getstate__(self):
self._get_data(),
)

def __setstate__(self, state):
function, atol, rtol, min_npoints, data = state
function = cloudpickle.loads(function)
self.__init__(function, atol, rtol, min_npoints)
def __setstate__(
self, state: tuple[bytes, float, float, int, _AverageData]
) -> None:
pickled_function, atol, rtol, min_npoints, data = state
type(self).__init__(
self, cloudpickle.loads(pickled_function), atol, rtol, min_npoints
)
self._set_data(data)
Loading
Loading