diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 966e6861..9b7ce9b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,7 +8,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.8", "3.9", "3.10", "3.11"] + python-version: ["3.11", "3.12", "3.13", "3.14"] os: ["ubuntu-latest", "macos-latest", "windows-latest"] steps: - uses: actions/checkout@v2 diff --git a/VERSION b/VERSION index 26aaba0e..13a0e150 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.2.0 +1.3.0.dev0 diff --git a/docs/python314-numeric-20260930.rst b/docs/python314-numeric-20260930.rst new file mode 100644 index 00000000..baf6d152 --- /dev/null +++ b/docs/python314-numeric-20260930.rst @@ -0,0 +1,51 @@ +Python 3.14 numerical checkpoint +================================ + +Parent integration owner, 2026-09-30. PR1 source base is +29f0a327d2069324f13d0c6fa0809a5c7566a6d4. No production code or dependency +installation changed. Existing Python 3.14.7 and installed scientific packages +were used directly with this isolated worktree's ``src`` on PYTHONPATH. + +Actual packages: JAX/JAXlib0.9.2, NumPy2.5.3, SciPy1.18.1, +scikit-image0.26.0, Pydantic2.13.5, pooch1.9.0. CPU platform, BLAS/OpenMP +threads1, disabled pytest plugin autoload and source bytecode/cache writing. +Fit process affinity is one CPU. No datasets, downloads, providers or GUI. + +Real checks +----------- + +* Existing public JAX inverse-DCT/SciPy comparisons and odd/even 1D/2D/3D + round trips: 3PASS,9.83s pytest,10.72s process,545160KiB peakRSS. +* New bounded 24-observation32x32 synthetic checks: 3PASS,7.83s pytest, + 9.15s process,450640KiB peakRSS. Real 2D/3D fit-transform preserves + floating measurement units and shapes, fitted field RMSE<0.15, zero + disabled darkfield, saved model/settings/profiles reload and correction + agree. Stationary biology produces materially worse recovered shading + than moving objects, exposing identifiability rather than promising it. + +Original logs/XML and process resource measurements are retained at +``/home/ts/wt/openhcs-issue-batch-20260929/basicpy-parent-numeric-20260930/``. +Each process exited0. Final published-test rerun: 6PASS,13.96s pytest, +15.97s process,690508KiB peakRSS, zero swaps, covering both suites in one +process. The tests use existing model declared attributes directly (BOUND-7). +No new model, field store, +registry, solver, fallback or compatibility layer is introduced (BOUND-2, +IMPL-13, TIME-1). Tests exercise the original BaSiC and JaxDCT owners. + +Reproduce from this worktree using the existing interpreter:: + + PYTHONPATH=$PWD/src PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 JAX_PLATFORMS=cpu \ + OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \ + XLA_FLAGS=--xla_cpu_multi_thread_eigen=false \ + python3.14 -B -m pytest -p no:cacheprovider \ + tests/test_public_jax_dct.py tests/test_python314_fit.py -q + +Boundaries +---------- + +This proves real import and bounded CPU numerical behavior on the existing +Python3.14 environment, including persisted profiles. It does not prove a +fresh dependency resolver, minimum-version matrix, CUDA, autotuning, fitted +additive darkfield, real acquisitions, or OpenHCS compiled/MCP execution. +No installed user entrypoint or blind harness changed. PR217 and paired +ArrayBridge integration remain separate acceptance boundaries. diff --git a/docs/python314-openhcs.md b/docs/python314-openhcs.md new file mode 100644 index 00000000..b8125c98 --- /dev/null +++ b/docs/python314-openhcs.md @@ -0,0 +1,95 @@ +# JAX prototype modernization for OpenHCS + +Current parent checkpoint: real Python 3.14 CPU fits, persisted model reload, +stationary-signal control and public DCT comparisons passed. See the canonical +[numerical receipt](python314-numeric-20260930.rst). Nothing has been installed; +OpenHCS compiled/MCP acceptance is still separate. + +The following records the historical 2026-09-29 source-only checkpoint and its +then-pending checks; it must not be read as today's package availability. +Original integration owner: Linnaeus (OpenHCS backend/dependencies, issue +[OpenHCS #213](https://github.com/OpenHCSDev/openhcs/issues/213)). + +## Provenance and API + +Reuses the clean `trissim/BaSiCPy` JAX prototype at `ae2c647`, including Tristan's +`fc9da06` dependency change and `ae2c647` public `functools.wraps` change. +The LADMAP/approximate optimization and correction formula are not replaced. +`BaSiC.fit_transform(images, timelapse=False)`, `FittingMode`, `flatfield`, +`darkfield`, model settings and saved profile names retain their existing owners. +Images are independent observations `(N,Y,X)` or `(N,Z,Y,X)`, never a mixture +of channels. No pseudo-BaSiC algorithm or permissive alternate import is added. + +Current [peng-lab 2.x](https://github.com/peng-lab/BaSiCPy) uses PyTorch and a +different model/API, including `is_timelapse` rather than `timelapse`. +Its [PR #174](https://github.com/peng-lab/BaSiCPy/pull/174) already addresses +modern SciPy for that implementation; [PR #170](https://github.com/peng-lab/BaSiCPy/pull/170) +targets Python 3.12/3.13. This fork preserves the existing JAX implementation +instead of duplicating those PyTorch changes or accidentally calling its API. + +## Candidate dependency matrix + +The running OpenHCS venv is Python 3.12.3 with JAX/JAXlib 0.9.2; BaSiCPy is not +installed. `/usr/bin/python3.14` is Python 3.14.7, linux-x86_64. Neither this +fork's dependencies nor its model have been imported on 3.14 yet. + +| Owner | Source/metadata basis | Draft constraint | +| --- | --- | --- | +| JAX | [0.9.2 metadata](https://pypi.org/pypi/jax/0.9.2/json); [JAXlib cp314 wheels](https://pypi.org/pypi/jaxlib/0.9.2/json) | `jax>=0.9.2,<0.10`; JAX owns matching JAXlib | +| NumPy | JAX 0.9.2 requires NumPy 2 | `numpy>=2.0` | +| SciPy | [1.16.2 cp314 wheels](https://pypi.org/pypi/scipy/1.16.2/json) | `scipy>=1.16.2`; no old `scipy<1.13` cap | +| scikit-image | [0.26.0 cp314 wheels](https://pypi.org/pypi/scikit-image/0.26.0/json); 0.25.2 has none | `scikit-image>=0.26.0,<0.27` | +| Pydantic | [2.12 adds Python 3.14 support](https://pydantic.dev/articles/pydantic-v2-12-release) | `pydantic>=2.12,<3` | + +Wheel availability and syntax are not import, numerical, GPU, or application +readiness evidence. These ranges are reviewable candidates pending a real +isolated Python 3.14 resolve/import/fit. Autotuning's old Hyperactive dependency +is owned by the existing `autotune` method and optional extra, not imported to +perform an ordinary fit. Autotuning is not part of the readiness claim. + +## Focused ownership audit + +Scope: changed JAX inverse-DCT owner, model/Pydantic boundary, dependency/test +configuration. This is source/AST/catalog review, not a full NRA proof/scan. + +- IMPL-13 / TIME-1: existing `JaxDCT` now delegates to JAX's + [public `idctn`](https://docs.jax.dev/en/latest/_autosummary/jax.scipy.fft.idctn.html). + The copied private-JAX helper and its tests are deleted in place; no fallback. +- TIME-6: removed nonexistent module-level DCT exports, not new aliases. +- BOUND-2: model settings and JAX pytree metadata use Pydantic's current + `model_dump`/`model_copy`/`model_dump_json`, with existing model types retained. +- New-case check: another DCT backend belongs to the existing `DCT` family and + derived `DCT_BACKENDS`. It needs no caller-side roster or copied inverse-DCT + implementation. A new model field remains declared on `BaSiC`/`BaseFit`; their + dumps project it without another schema list. The wrapper must deliberately + expose a useful new user parameter, not mirror the entire model. + +Inherited resize/fitting-mode dispatch and the unfinished historical CLI are +outside this focused patch. No claim of a globally clean codebase is made. + +## Evidence and pending acceptance + +Executed with no numerical imports or environment changes: + +``` +/usr/bin/python3.14 scripts/check_source_contracts.py +``` + +Four source tests pass (0.052 seconds): syntax, public inverse-DCT owner, +dependency contract and current Pydantic owner API. This does not execute DCT +or fit. `tests/test_public_jax_dct.py` contains the real SciPy comparison and +round-trip regression for odd/even 1D/2D/3D arrays; execution is pending. + +Next shared slot, after parent #151/#212 acceptance and explicit handoff: + +1. Verify isolated import paths, resolve actual cp314 dependencies and import. +2. Bound CPU threads, use synthetic independent same-channel shaded fields, + run real DCT regressions and fit-transform; inspect both fitted fields and + report elapsed time, peak/RSS/PSS/private/swap memory. +3. Compare recovered shading and moving synthetic objects; include a stationary + object negative control to expose biological leakage/identifiability limits. +4. Verify paired OpenHCS compiled execution and real MCP discovery/signature/ + execute/artifact inspection. No blind biology inputs or installed changes. + +All PRs remain draft; no installation, Python 3.14 fit, CUDA support or +OpenHCS entrypoint acceptance is claimed here. diff --git a/noxfile.py b/noxfile.py index 8169b735..29037611 100644 --- a/noxfile.py +++ b/noxfile.py @@ -1,27 +1,17 @@ """Nox automation file.""" -import platform import shutil from pathlib import Path from nox import Session, session -python_versions = ["3.11", "3.10", "3.9", "3.8"] +python_versions = ["3.11", "3.12", "3.13", "3.14"] @session(python=python_versions) def tests(session: Session) -> None: """Run the test suite.""" - if platform.system() == "Windows": - session.install( - "jax[cpu]==0.4.11", - "-f", - "https://whls.blob.core.windows.net/unstable/index.html", - "--use-deprecated", - "legacy-resolver", - ) - session.install("ml-dtypes==0.2.0") - session.install(".") + session.install(".[autotune]") session.install( "dask", "pytest", diff --git a/scripts/check_source_contracts.py b/scripts/check_source_contracts.py new file mode 100644 index 00000000..3526a637 --- /dev/null +++ b/scripts/check_source_contracts.py @@ -0,0 +1,60 @@ +"""Light source-only checks; deliberately do not import numerical backends.""" + +from __future__ import annotations + +import ast +import configparser +from pathlib import Path +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +class SourceContractTests(unittest.TestCase): + def test_source_parses_on_running_interpreter(self): + for path in (ROOT / "src").rglob("*.py"): + with self.subTest(path=path.relative_to(ROOT)): + ast.parse(path.read_text(), filename=str(path)) + + def test_inverse_dct_uses_public_owner(self): + path = ROOT / "src/basicpy/tools/dct_tools.py" + tree = ast.parse(path.read_text()) + owner = next( + node for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == "JaxDCT" + ) + inverse = next( + node for node in owner.body + if isinstance(node, ast.FunctionDef) and node.name == "idctnd" + ) + self.assertEqual(ast.unparse(inverse.body[0].value.func), "jax.scipy.fft.idctn") + self.assertFalse((ROOT / "src/basicpy/tools/_jax_idct.py").exists()) + for path in (ROOT / "src").rglob("*.py"): + for node in ast.walk(ast.parse(path.read_text())): + if isinstance(node, ast.ImportFrom): + self.assertFalse((node.module or "").startswith("jax._"), path) + self.assertNotIn("_jax_idct", node.module or "", path) + + def test_python314_dependency_contract(self): + config = configparser.ConfigParser() + config.read(ROOT / "setup.cfg") + dependencies = config["options"]["install_requires"].split() + self.assertEqual(config["options"]["python_requires"], ">=3.11") + self.assertIn("jax>=0.9.2,<0.10", dependencies) + self.assertIn("scipy>=1.16.2", dependencies) + self.assertIn("pydantic>=2.12.0,<3.0.0", dependencies) + self.assertFalse(any(dep.startswith("hyperactive") for dep in dependencies)) + self.assertIn("autotune", config["options.extras_require"]) + + def test_supported_pydantic_owner_api(self): + for relative in ("src/basicpy/basicpy.py", "src/basicpy/_jax_routines.py"): + tree = ast.parse((ROOT / relative).read_text()) + for node in ast.walk(tree): + if isinstance(node, ast.Attribute): + self.assertNotIn(node.attr, ("dict", "json", "__fields__"), relative) + if isinstance(node, ast.ClassDef): + self.assertNotEqual(node.name, "Config", relative) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/setup.cfg b/setup.cfg index 663fe20d..726d0892 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,7 +4,7 @@ version = file: VERSION description = A python package for background and shading correction of optical microscopy images long_description = file: README.md long_description_content_type = text/markdown -url = https://github.com/peng-lab/BaSiCPy +url = https://github.com/OpenHCSDev/BaSiCPy author = Nicholas Schaub, Tim Morello, Tingying Peng, Yohsuke T. Fukai author_email = nick.schaub@nih.gov, timothy.morello@downstate.edu, tingying.peng@helmholtz-muenchen.de, ysk@yfukai.net license = MIT @@ -15,22 +15,24 @@ classifiers = Operating System :: OS Independent Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only + Programming Language :: Python :: 3.11 + Programming Language :: Python :: 3.12 + Programming Language :: Python :: 3.13 + Programming Language :: Python :: 3.14 keywords = background shading flatfield darkfield biology optical microscopy image illumination project_urls = - Bug Tracker = https://github.com/peng-lab/BaSiCPy/issues + Bug Tracker = https://github.com/OpenHCSDev/BaSiCPy/issues [options] packages = find: install_requires = - hyperactive>=4.4.0 - jax>=0.4.38,<0.6.0 - jaxlib>=0.4.38,<0.6.0 - numpy + jax>=0.9.2,<0.10 + numpy>=2.0 pooch - pydantic>=2.7.0,<3.0.0 - scikit-image - scipy<1.13 -python_requires = >=3.8 + pydantic>=2.12.0,<3.0.0 + scikit-image>=0.26.0,<0.27 + scipy>=1.16.2 +python_requires = >=3.11 package_dir = = src @@ -42,6 +44,8 @@ console_scripts = basicpy = basicpy.__main__:main [options.extras_require] +autotune = + hyperactive>=4.4.0,<5 dask = dask dev = diff --git a/src/basicpy/_jax_routines.py b/src/basicpy/_jax_routines.py index b12243d7..2b806915 100644 --- a/src/basicpy/_jax_routines.py +++ b/src/basicpy/_jax_routines.py @@ -5,7 +5,7 @@ from jax import jit, lax from jax import numpy as jnp from jax.tree_util import register_pytree_node_class -from pydantic import BaseModel, Field, PrivateAttr +from pydantic import BaseModel, ConfigDict, Field, PrivateAttr from basicpy.tools.dct_tools import JaxDCT @@ -57,9 +57,7 @@ class BaseFit(BaseModel): description="Maximum number of iterations for single optimization.", ) - class Config: - frozen = True - extra = "ignore" + model_config = ConfigDict(frozen=True, extra="ignore") def _cond(self, vals): k = vals[0] @@ -200,7 +198,7 @@ def fit_baseline( def tree_flatten(self): # all of the fields are treated as "static" values for JAX children = [] - aux_data = self.dict() + aux_data = self.model_dump() return (children, aux_data) @classmethod diff --git a/src/basicpy/basicpy.py b/src/basicpy/basicpy.py index 5ddc3f6e..6adbe722 100644 --- a/src/basicpy/basicpy.py +++ b/src/basicpy/basicpy.py @@ -16,12 +16,10 @@ # 3rd party modules import numpy as np -from hyperactive import Hyperactive -from hyperactive.optimizers import HillClimbingOptimizer from jax import device_put from jax.image import ResizeMethod from jax.image import resize as jax_resize -from pydantic import BaseModel, Field, PrivateAttr, root_validator +from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, model_validator from skimage.filters import threshold_otsu from skimage.morphology import ball, binary_erosion from skimage.transform import resize as skimage_resize @@ -193,13 +191,10 @@ class BaSiC(BaseModel): _smoothness_darkfield: float = PrivateAttr(None) _sparse_cost_darkfield: float = PrivateAttr(None) - class Config: - """Pydantic class configuration.""" + model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid") - arbitrary_types_allowed = True - extra = "forbid" - - @root_validator(pre=True) + @model_validator(mode="before") + @classmethod def debug_log_values(cls, values: Dict[str, Any]): """Use a validator to echo input values.""" logger.debug("Initializing BaSiC with parameters:") @@ -389,7 +384,7 @@ def fit( init_mu = self.mu_coef / spectral_norm else: init_mu = self.mu_coef / spectral_norm / np.prod(Im2.shape) - fit_params = self.dict() + fit_params = self.model_dump() fit_params.update( dict( smoothness_flatfield=self._smoothness_flatfield, @@ -714,6 +709,9 @@ def autotune( """ + from hyperactive import Hyperactive + from hyperactive.optimizers import HillClimbingOptimizer + if search_space is None: search_space = { "smoothness_flatfield": list(np.logspace(-3, 1, 15)), @@ -738,7 +736,7 @@ def autotune( ) # calculate the histogram range - basic = self.copy(update=init_params) + basic = self.model_copy(update=init_params) basic.fit( images, fitting_weight=fitting_weight, @@ -757,7 +755,7 @@ def autotune( def fit_and_calc_entropy(params): try: - basic = self.copy(update=params) + basic = self.model_copy(update=params) basic.fit( images, fitting_weight=fitting_weight, @@ -837,7 +835,7 @@ def settings(self) -> Dict: Returns: current settings """ - return self.dict() + return self.model_dump() def save_model(self, model_dir: PathLike, overwrite: bool = False) -> None: """Save current model to folder. @@ -859,7 +857,7 @@ def save_model(self, model_dir: PathLike, overwrite: bool = False) -> None: # save settings with open(path / _SETTINGS_FNAME, "w") as fp: # see pydantic docs for output options - fp.write(self.json()) + fp.write(self.model_dump_json()) # NOTE emit warning if profiles are all zeros? fit probably not run # save profiles diff --git a/src/basicpy/tools/_jax_idct.py b/src/basicpy/tools/_jax_idct.py deleted file mode 100644 index d16a3fd0..00000000 --- a/src/basicpy/tools/_jax_idct.py +++ /dev/null @@ -1,65 +0,0 @@ -"""A custom JAX idct method.""" - -import jax.numpy as jnp -import scipy.fft as osp_fft -from jax import lax -import functools -from jax._src.util import canonicalize_axis - - -# `_W4` copied from jax._src.scipy.fft -def _W4(N, k): - return jnp.exp(-0.5j * jnp.pi * k / N) - - -def _slice_ref_in_dim(x, start, stop, stride, axis): - return tuple( - slice(start, stop, stride) if dim == axis else slice(None, None) - for dim in range(x.ndim) - ) - - -def _dct_interleave_inverse(x, axis): - inverse = True - if inverse: - N = x.shape[axis] - v0 = lax.slice_in_dim(x, None, (N + 1) // 2, 1, axis) - v1 = lax.rev(lax.slice_in_dim(x, (N + 1) // 2, None, 1, axis), (axis,)) - ref0 = _slice_ref_in_dim(x, None, None, 2, axis) - ref1 = _slice_ref_in_dim(x, 1, None, 2, axis) - out = jnp.zeros(x.shape, dtype=x.dtype) - out = out.at[ref0].set(v0) - out = out.at[ref1].set(v1) - return out - - -# REFACTOR I'm sure there is a much cleaner way of doing this -@functools.wraps(osp_fft.idct) -def idct(x, norm=None, axis=-1): - axis = canonicalize_axis(axis, x.ndim) - N = x.shape[axis] - k = lax.expand_dims(jnp.arange(N), [a for a in range(x.ndim) if a != axis]) - V = _W4(N, -k) * x - - x0 = lax.slice_in_dim(x, None, 1, 1, axis) / 2 - V = V.at[_slice_ref_in_dim(V, None, 1, 1, axis)].set(x0) - - if norm == "ortho": - factor = lax.concatenate( - [ - lax.full((1,), 2 * jnp.sqrt(N), V.dtype), - lax.full((N - 1,), jnp.sqrt(2 * N), V.dtype), - ], - 0, - ) - factor = lax.expand_dims(factor, [a for a in range(V.ndim) if a != axis]) - - V = V * factor - - v = jnp.fft.ifft(V, axis=axis) - - xrev = lax.slice_in_dim(x, 1, None, 1, axis) - xrev = lax.rev(xrev, (axis,)) - - out = _dct_interleave_inverse(v, axis) - return out.real diff --git a/src/basicpy/tools/dct_tools.py b/src/basicpy/tools/dct_tools.py index 061079a3..93550e54 100644 --- a/src/basicpy/tools/dct_tools.py +++ b/src/basicpy/tools/dct_tools.py @@ -1,23 +1,11 @@ """2D and 3D discrete cosine transform tools.""" -import importlib.util -import logging -import os +import logging from abc import ABC, abstractmethod, abstractproperty -from functools import partial import numpy as np import scipy.fft import jax -from jax import jit -import basicpy.tools._jax_idct - -__all__ = [ - "dct2d", - "idct2d", - "dct3d", - "idct3d", -] # initialize logger with the package name logger = logging.getLogger(__name__) @@ -67,13 +55,11 @@ def dct2d(arr: np.ndarray) -> np.ndarray: def dct3d(arr: np.ndarray) -> np.ndarray: return JaxDCT.dctnd(arr) - # custom idct since JAX only implements dct type 2 (not idct, dct type 3) - @staticmethod - @partial(jit, static_argnames=["ndims"]) - def idctnd(arr: np.ndarray, ndims: int) -> np.ndarray: - for i in range(ndims): - arr = basicpy.tools._jax_idct.idct(arr, norm="ortho", axis=i) - return arr + @staticmethod + def idctnd(arr: np.ndarray, ndims: int) -> np.ndarray: + return jax.scipy.fft.idctn( + arr, norm="ortho", type=2, axes=tuple(range(ndims)) + ) @staticmethod def idct2d(arr: np.ndarray) -> np.ndarray: diff --git a/tests/test_jax_idct.py b/tests/test_jax_idct.py deleted file mode 100644 index 178dc6c4..00000000 --- a/tests/test_jax_idct.py +++ /dev/null @@ -1,27 +0,0 @@ -import jax.numpy as jnp -import scipy.fft -from jax._src.scipy.fft import _dct_interleave - -from basicpy.tools import _jax_idct - - -def test_inverse_interleave(): - x = jnp.arange(24).reshape(4, 3, 2) - - for axis in range(x.ndim): - y = _dct_interleave(x, axis=axis) - y_inv = _jax_idct._dct_interleave_inverse(y, axis) - assert jnp.allclose(x, y_inv) - - -def test_custom_jax_idct(): - x = jnp.arange(24).reshape(4, 3, 2) - - for axis in range(x.ndim): - ours = _jax_idct.idct(x, norm="ortho", axis=axis) - theirs = scipy.fft.idct(x, norm="ortho", axis=axis) - assert jnp.allclose(ours, theirs) - - ours = _jax_idct.idct(x, axis=axis) - theirs = scipy.fft.idct(x, axis=axis) - assert jnp.allclose(ours, theirs) diff --git a/tests/test_public_jax_dct.py b/tests/test_public_jax_dct.py new file mode 100644 index 00000000..7ccf4aac --- /dev/null +++ b/tests/test_public_jax_dct.py @@ -0,0 +1,21 @@ +"""Public JAX DCT owner matches SciPy on odd/even multidimensional shapes.""" + +import numpy as np +import pytest +import scipy.fft + +from basicpy.tools.dct_tools import JaxDCT + + +@pytest.mark.parametrize("shape", [(7,), (4, 7), (3, 4, 7)]) +def test_public_jax_inverse_dct_matches_scipy_and_round_trips(shape): + values = np.linspace(-3, 10, np.prod(shape), dtype=np.float32).reshape(shape) + actual = JaxDCT.idctnd(values, len(shape)) + expected = scipy.fft.idctn(values, norm="ortho", type=2) + np.testing.assert_allclose(actual, expected, rtol=2e-5, atol=2e-5) + np.testing.assert_allclose( + JaxDCT.idctnd(JaxDCT.dctnd(values), len(shape)), + values, + rtol=2e-5, + atol=2e-5, + ) diff --git a/tests/test_python314_fit.py b/tests/test_python314_fit.py new file mode 100644 index 00000000..ba743b69 --- /dev/null +++ b/tests/test_python314_fit.py @@ -0,0 +1,66 @@ +"""Bounded, offline fits through the real BaSiC model and persisted profiles.""" + +import numpy as np +import pytest + +from basicpy import BaSiC + + +def shaded_observations(*, stationary=False, volume=False): + yy, xx = np.mgrid[-1:1:32j, -1:1:32j] + flatfield = 1.2 - 0.3 * (yy**2 + xx**2) + 0.1 * xx + flatfield /= flatfield.mean() + rng = np.random.default_rng(213) + frames = [] + for index in range(24): + background = 3000 + 50 * index + if stationary: + signal = background * np.exp(-((xx - 0.2)**2 + (yy + 0.1)**2) / 0.09) + else: + cx, cy = rng.uniform(-0.8, 0.8, size=2) + signal = 5000 * np.exp(-((xx - cx)**2 + (yy - cy)**2) / 0.008) + frames.append(np.rint((background + signal) * flatfield).astype(np.uint16)) + images = np.stack(frames) + if volume: + images = np.stack((images, images), axis=1) + flatfield = np.stack((flatfield, flatfield)) + return images, flatfield + + +def fit_model(images): + model = BaSiC(max_iterations=100, working_size=None, max_workers=1) + corrected = np.asarray(model.fit_transform(images, timelapse=False)) + return model, corrected + + +@pytest.mark.parametrize("volume", [False, True]) +def test_real_fit_and_saved_profiles_preserve_measurement_units(tmp_path, volume): + images, truth = shaded_observations(volume=volume) + model, corrected = fit_model(images) + assert corrected.shape == images.shape + assert model.flatfield.shape == model.darkfield.shape == images.shape[1:] + assert np.issubdtype(corrected.dtype, np.floating) + assert np.isfinite(corrected).all() + np.testing.assert_allclose(model.darkfield, 0, atol=1e-6) + np.testing.assert_allclose(corrected, images / model.flatfield, rtol=1e-5, atol=1e-3) + assert np.sqrt(np.mean((model.flatfield - truth)**2)) < 0.15 + assert np.any(corrected != np.floor(corrected)) + + destination = tmp_path / "model" + model.save_model(destination) + restored = BaSiC.load_model(destination) + assert restored.model_dump() == model.model_dump() + np.testing.assert_array_equal(restored.flatfield, model.flatfield) + np.testing.assert_array_equal(restored.darkfield, model.darkfield) + np.testing.assert_array_equal(restored.baseline, model.baseline) + np.testing.assert_allclose(restored.transform(images), corrected, rtol=1e-6, atol=1e-3) + + +def test_stationary_signal_is_not_mistaken_for_evidence_of_identifiability(): + moving, truth = shaded_observations() + stationary, _ = shaded_observations(stationary=True) + moving_model, _ = fit_model(moving) + stationary_model, _ = fit_model(stationary) + moving_error = np.sqrt(np.mean((moving_model.flatfield - truth)**2)) + stationary_error = np.sqrt(np.mean((stationary_model.flatfield - truth)**2)) + assert stationary_error > moving_error + 0.02