Skip to content
Open
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
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ repos:

# Ruff linter, replacement for flake8, isort, pydocstyle
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 'v0.15.12'
rev: 'v0.16.3'
hooks:
- id: ruff
args: [--fix, --show-fixes, --exit-non-zero-on-fix]
- id: ruff-format

# Python type checking
- repo: https://github.com/pre-commit/mirrors-mypy
rev: 'v2.0.0'
rev: 'v2.3.1'
hooks:
- id: mypy
args: [--allow-redefinition, --ignore-missing-imports]
6 changes: 3 additions & 3 deletions src/resample/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
__version__ = version("resample")

__all__ = [
"jackknife",
"__version__",
"bootstrap",
"permutation",
"empirical",
"__version__",
"jackknife",
"permutation",
]
6 changes: 2 additions & 4 deletions src/resample/_util.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
from typing import Optional, Tuple, Union

import numpy as np
from numpy.typing import ArrayLike

__all__ = ["normalize_rng", "wilson_score_interval"]


def normalize_rng(
random_state: Optional[Union[int, np.random.Generator]],
random_state: int | np.random.Generator | None,
) -> np.random.Generator:
"""Return normalized RNG object."""
if random_state is None:
Expand All @@ -19,7 +17,7 @@ def normalize_rng(

def wilson_score_interval(
n1: "ArrayLike", n: "ArrayLike", z: float
) -> Tuple[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
) -> tuple[np.ndarray, tuple[np.ndarray, np.ndarray]]:
"""Return binomial fraction and Wilson score interval."""
p = n1 / n
norm = 1 / (1 + z**2 / n)
Expand Down
34 changes: 14 additions & 20 deletions src/resample/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,17 @@
"""

__all__ = [
"resample",
"bootstrap",
"variance",
"covariance",
"confidence_interval",
"covariance",
"resample",
"variance",
]

from collections.abc import Callable, Collection, Generator
from typing import (
Any,
Callable,
Collection,
Dict,
Generator,
List,
Optional,
Tuple,
Union,
)

import numpy as np
Expand All @@ -47,7 +41,7 @@ def resample(
size: int = 100,
method: str = "balanced",
strata: Optional["ArrayLike"] = None,
random_state: Optional[Union[np.random.Generator, int]] = None,
random_state: np.random.Generator | int | None = None,
) -> Generator[np.ndarray, None, None]:
"""
Return generator of bootstrap samples.
Expand Down Expand Up @@ -147,7 +141,7 @@ def resample(
"""
sample_np = np.atleast_1d(sample)
n_sample = len(sample_np)
args_np: List[np.ndarray] = []
args_np: list[np.ndarray] = []

if args:
if not isinstance(args[0], Collection):
Expand All @@ -158,7 +152,7 @@ def resample(
"deprecated",
FutureWarning,
)
kwargs: Dict[str, Any] = {
kwargs: dict[str, Any] = {
"size": size,
"method": method,
"strata": strata,
Expand Down Expand Up @@ -381,7 +375,7 @@ def confidence_interval(
cl: float = 0.95,
ci_method: str = "bca",
**kwargs: Any,
) -> Tuple[float, float]:
) -> tuple[float, float]:
"""
Calculate bootstrap confidence intervals.

Expand Down Expand Up @@ -491,7 +485,7 @@ def _resample_ordinary_1(


def _resample_ordinary_n(
samples: List[np.ndarray], size: int, rng: np.random.Generator
samples: list[np.ndarray], size: int, rng: np.random.Generator
) -> Generator[np.ndarray, None, None]:
n = len(samples[0])
indices = np.arange(n)
Expand All @@ -513,7 +507,7 @@ def _resample_balanced_1(


def _resample_balanced_n(
samples: List[np.ndarray], size: int, rng: np.random.Generator
samples: list[np.ndarray], size: int, rng: np.random.Generator
) -> Generator[np.ndarray, None, None]:
n = len(samples[0])
indices = rng.permutation(n * size)
Expand All @@ -533,7 +527,7 @@ def _resample_extended_1(


def _resample_extended_n(
samples: List[np.ndarray], size: int, rng: np.random.Generator
samples: list[np.ndarray], size: int, rng: np.random.Generator
) -> Generator[np.ndarray, None, None]:
n = len(samples[0])
for i in range(size):
Expand All @@ -543,7 +537,7 @@ def _resample_extended_n(

def _fit_parametric_family(
dist: stats.rv_continuous, sample: np.ndarray
) -> Tuple[float, ...]:
) -> tuple[float, ...]:
if dist == stats.multivariate_normal:
# has no fit method...
return np.mean(sample, axis=0), np.cov(sample.T, ddof=1)
Expand Down Expand Up @@ -579,14 +573,14 @@ def _resample_parametric(

def _confidence_interval_percentile(
thetas: np.ndarray, alpha_half: float
) -> Tuple[float, float]:
) -> tuple[float, float]:
quant = quantile_function_gen(thetas)
return quant(alpha_half), quant(1 - alpha_half)


def _confidence_interval_bca(
theta: float, thetas: np.ndarray, j_thetas: np.ndarray, alpha_half: float
) -> Tuple[float, float]:
) -> tuple[float, float]:
norm = stats.norm

# bias correction; implementation notes:
Expand Down
9 changes: 5 additions & 4 deletions src/resample/empirical.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
like the empirical CDF. Implemented here are mostly tools used internally.
"""

__all__ = ["cdf_gen", "quantile_function_gen", "influence"]
__all__ = ["cdf_gen", "influence", "quantile_function_gen"]

from typing import Callable, Union
from collections.abc import Callable
from typing import Union

import numpy as np
from numpy.typing import ArrayLike
Expand Down Expand Up @@ -37,7 +38,7 @@ def cdf_gen(sample: "ArrayLike") -> Callable[[np.ndarray], np.ndarray]:

def quantile_function_gen(
sample: "ArrayLike",
) -> Callable[[Union[float, "ArrayLike"]], Union[float, np.ndarray]]:
) -> Callable[[Union[float, "ArrayLike"]], float | np.ndarray]:
"""
Return the empirical quantile function for the given sample.

Expand All @@ -57,7 +58,7 @@ class QuantileFn:
def __init__(self, sample: "ArrayLike"):
self._sorted = np.sort(sample, axis=0)

def __call__(self, p: Union[float, "ArrayLike"]) -> Union[float, np.ndarray]:
def __call__(self, p: Union[float, "ArrayLike"]) -> float | np.ndarray:
ndim = np.ndim(p) # must come before atleast_1d
p = np.atleast_1d(p)
result = np.empty(len(p))
Expand Down
13 changes: 7 additions & 6 deletions src/resample/jackknife.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@
"""

__all__ = [
"resample",
"jackknife",
"bias",
"bias_corrected",
"variance",
"cross_validation",
"jackknife",
"resample",
"variance",
]

from typing import Any, Callable, Collection, Generator, List
from collections.abc import Callable, Collection, Generator
from typing import Any

import numpy as np
from numpy.typing import ArrayLike
Expand Down Expand Up @@ -136,7 +137,7 @@ def _resample_1(sample: np.ndarray, copy: bool) -> Generator[np.ndarray, None, N
yield x.copy() if copy else x


def _resample_n(samples: List[np.ndarray], copy: bool) -> Generator[Any, None, None]:
def _resample_n(samples: list[np.ndarray], copy: bool) -> Generator[Any, None, None]:
x = [a[1:].copy() for a in samples]
yield (xi.copy() for xi in x)
for i in range(len(samples[0]) - 1):
Expand Down Expand Up @@ -363,5 +364,5 @@ def cross_validation(
deltas = []
for i, (x_in, y_in) in enumerate(resample(x, y, copy=False)):
yip = predict(x_in, y_in, x[i], *args)
deltas.append((y[i] - yip))
deltas.append(y[i] - yip)
return np.var(deltas) # type:ignore
17 changes: 9 additions & 8 deletions src/resample/permutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,20 @@

__all__ = [
"TestResult",
"usp",
"same_population",
"anova",
"kruskal",
"pearsonr",
"same_population",
"spearmanr",
"ttest",
"usp",
]

import sys
import warnings
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Callable, Optional, Tuple, Union
from typing import Any

import numpy as np
from numpy.typing import ArrayLike, NDArray
Expand Down Expand Up @@ -89,7 +90,7 @@ def __len__(self) -> int:
"""Return length of tuple."""
return 3

def __getitem__(self, idx: int) -> Union[float, NDArray]:
def __getitem__(self, idx: int) -> float | NDArray:
"""Return fields by index."""
if idx == 0:
return self.statistic
Expand All @@ -105,7 +106,7 @@ def usp(
*,
size: int = 9999,
method: str = "auto",
random_state: Optional[Union[np.random.Generator, int]] = None,
random_state: np.random.Generator | int | None = None,
) -> TestResult:
"""
Test independence of two discrete data sets with the U-statistic.
Expand Down Expand Up @@ -198,9 +199,9 @@ def same_population(
x: "ArrayLike",
y: "ArrayLike",
*args: "ArrayLike",
transform: Optional[Callable[[NDArray], NDArray]] = None,
transform: Callable[[NDArray], NDArray] | None = None,
size: int = 9999,
random_state: Optional[Union[np.random.Generator, int]] = None,
random_state: np.random.Generator | int | None = None,
) -> TestResult:
"""
Compute p-value for hypothesis that samples originate from same population.
Expand Down Expand Up @@ -511,7 +512,7 @@ def __call__(self, *args: NDArray) -> float:
)
return between_group_variability / within_group_variability

def _init(self, args: Tuple[NDArray, ...]) -> None:
def _init(self, args: tuple[NDArray, ...]) -> None:
n = sum(len(a) for a in args)
k = len(args)
self.km1 = k - 1
Expand Down