diff --git a/.copier-answers.yml b/.copier-answers.yml
new file mode 100644
index 00000000..26e77881
--- /dev/null
+++ b/.copier-answers.yml
@@ -0,0 +1,17 @@
+# Changes here will be overwritten by Copier; NEVER EDIT MANUALLY
+_commit: '4346961'
+_src_path: https://github.com/AllenNeuralDynamics/python-templates
+author_name: Neural Dynamics accelerator at the Allen Institute
+initial_version: 0.0.0
+level_of_support: Supported
+max_python_target_version: '3.14'
+min_python_target_version: '3.10'
+package_name: giant_python
+project_created_date: '2026-03-27'
+project_description: Glutamate Imaging Analysis Toolbox, Python implementation
+project_name: GIAnT-Python
+project_url: ''
+release_type: GitHub
+repo_visibility: public
+template_type: library-template
+
diff --git a/.flake8 b/.flake8
deleted file mode 100644
index 765c4187..00000000
--- a/.flake8
+++ /dev/null
@@ -1,11 +0,0 @@
-[flake8]
-exclude =
- .git,
- __pycache__,
- build,
- .venv,
- venv,
- .conda
-max-complexity = 10
-# Black's PEP 8-compliant slice formatting conflicts with pycodestyle E203.
-extend-ignore = E203
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..d5917cc6
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+* text=auto
+uv.lock linguist-generated
\ No newline at end of file
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
deleted file mode 100644
index d1033e09..00000000
--- a/.github/workflows/lint.yml
+++ /dev/null
@@ -1,24 +0,0 @@
-name: Lint
-
-on:
- pull_request:
- branches:
- - main
-
-jobs:
- ci:
- runs-on: ubuntu-latest
- strategy:
- matrix:
- python-version: [ '3.10', '3.11', '3.12' ]
- steps:
- - uses: actions/checkout@v7
- - name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v6
- with:
- python-version: ${{ matrix.python-version }}
- - name: Install dependencies
- run: |
- python -m pip install -e . --group dev --no-cache-dir
- - name: Run linter checks
- run: flake8 . && interrogate --verbose .
\ No newline at end of file
diff --git a/.github/workflows/tag_and_publish.yml b/.github/workflows/tag_and_publish.yml
index b729b2ed..8ddca89d 100644
--- a/.github/workflows/tag_and_publish.yml
+++ b/.github/workflows/tag_and_publish.yml
@@ -3,72 +3,28 @@ on:
push:
branches:
- main
-# Set the publish job's "if" condition to true to enable PyPI publishing.
-# Requires that svc-aindscicomp be added as an admin to repo.
+
jobs:
update_badges:
- runs-on: ubuntu-latest
- continue-on-error: true
- steps:
- - uses: actions/checkout@v7
- with:
- ref: ${{ env.DEFAULT_BRANCH }}
- fetch-depth: 0
- token: ${{ secrets.SERVICE_TOKEN }}
- - name: Set up Python 3.10
- uses: actions/setup-python@v6
- with:
- python-version: '3.10'
- - name: Install dependencies
- run: |
- python -m pip install -e . --group dev --no-cache-dir
- - name: Get Python version and Update README.md
- run: |
- python_version=$(grep "requires-python" pyproject.toml | grep -o ">=[^\"]*")
- python_badge=$(grep '^\!\[Python\]' README.md | sed -n 's/.*\(python-[^)]*\).*/\1/p')
- new_python_badge="python-$python_version-blue?logo=python"
- sed -i "s/$python_badge/$new_python_badge/g" README.md
- - name: Get interrogate values and Update README.md
- run: |
- interrogate_val=$(interrogate . | grep -o 'actual: [0-9]*\.[0-9]*' | awk '{print $2}')
- interrogate_badge=$(grep '^\!\[Interrogate\]' README.md | sed -n 's/.*\(interrogate-[^)]*\).*/\1/p')
- if (( $(echo "$interrogate_val >= 90.00" | bc -l) )); then
- new_interrogate_badge="interrogate-$interrogate_val%25-brightgreen"
- elif (( $(echo "$interrogate_val < 80.00" | bc -l) )); then
- new_interrogate_badge="interrogate-$interrogate_val%25-red"
- else
- new_interrogate_badge="interrogate-$interrogate_val%25-yellow"
- fi
- sed -i "s/$interrogate_badge/$new_interrogate_badge/g" README.md
- - name: Commit changes
- uses: EndBug/add-and-commit@v10
- with:
- default_author: github_actions
- message: "ci: update badges [skip actions]"
- add: '["README.md"]'
+ uses: AllenNeuralDynamics/.github/.github/workflows/python_library_template_update_badges_v0_0_1.yml@main
+ with:
+
+ app-id: ${{ vars.SEMANTIC_RELEASE_BOT_APP_ID }}
+
+ secrets:
+
+ app-private-key: ${{ secrets.SEMANTIC_RELEASE_BOT_PRIVATE_KEY }}
+
+
tag:
needs: update_badges
- uses: AllenNeuralDynamics/.github/.github/workflows/release-bump-version.yml@main
+ uses: AllenNeuralDynamics/.github/.github/workflows/python_library_template_tag_v0_0_1.yml@main
+ with:
+
+ app-id: ${{ vars.SEMANTIC_RELEASE_BOT_APP_ID }}
+
secrets:
- repo-token: ${{ secrets.SERVICE_TOKEN }}
- publish:
- needs: tag
- if: false
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v7
- - name: Pull latest changes
- run: git pull origin main
- - name: Set up Python 3.10
- uses: actions/setup-python@v6
- with:
- python-version: '3.10'
- - name: Install dependencies
- run: |
- pip install --upgrade setuptools wheel twine build
- python -m build
- twine check dist/*
- - name: Publish on PyPI
- uses: pypa/gh-action-pypi-publish@release/v1
- with:
- password: ${{ secrets.AIND_PYPI_TOKEN }}
+
+ app-private-key: ${{ secrets.SEMANTIC_RELEASE_BOT_PRIVATE_KEY }}
+
+
diff --git a/.github/workflows/tests_and_format_check.yml b/.github/workflows/tests_and_format_check.yml
new file mode 100644
index 00000000..77864d54
--- /dev/null
+++ b/.github/workflows/tests_and_format_check.yml
@@ -0,0 +1,31 @@
+name: Run test and format checks
+
+on:
+ pull_request:
+ branches:
+ - dev
+ - main
+
+jobs:
+ test_and_format_checks:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ python-version: ["3.10", "3.11", "3.12"]
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: astral-sh/setup-uv@v7
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install dependencies
+ run: uv sync
+ - name: Check docstring coverage
+ run: uv run interrogate --verbose
+ - name: Run format checks
+ run: uv run ruff check
+ - name: Check tests and test coverage
+ run: uv run pytest
+
+
diff --git a/.gitignore b/.gitignore
index 405b4017..649f1f1d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,8 +37,19 @@ MANIFEST
pip-log.txt
pip-delete-this-directory.txt
-# Tool caches
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
# Translations
*.mo
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1f16d228..b5828113 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,38 +1,39 @@
# Contributing
-### Development setup
+We welcome contributions! We have documented our development practices and guidelines at (Software Practices) [https://docs.allenneuraldynamics.org/en/latest/policies_practices/software_practices.html].
-From the repository root, install the package and development tools with pip 25.1 or later:
+In general, we use uv, pytest, ruff, and interrogate for out local development.
+### Installation
+
+To install the dependencies needed for local development:
```bash
-pip install -e . --group dev
+uv sync --group dev
```
-Alternatively, use `uv sync`. Interactive ROI work also requires tkinter in the Python installation.
+To install the dependencies to build the documentation locally:
+```bash
+uv sync --group docs
+```
-### Code quality
+### Linters and testing
-Use the following tools to check documentation and maintain code style.
-
-- Use **interrogate** to check that modules, methods, etc. have been documented thoroughly:
+- Please test your changes using the **pytest** library, which will run the tests and log a coverage report:
```bash
-interrogate .
+uv run pytest .
```
-- Use **flake8** to check that code is up to standards (no unused imports, etc.):
-```bash
-flake8 .
-```
+- Use **interrogate** to check that modules, methods, etc. have been documented thoroughly:
-- Use **black** to automatically format the code into PEP standards:
```bash
-black .
+uv run interrogate .
```
-- Use **isort** to automatically sort import statements:
+- Use **ruff** to check that code is up to standards and auto-format:
```bash
-isort .
+uv run ruff check --fix
+uv run ruff format
```
### Pull requests
@@ -44,13 +45,14 @@ For internal members, please create a branch. For external members, please fork
where scope (optional) describes the packages affected by the code changes and type (mandatory) is one of:
-- **build**: Changes that affect build tools or external dependencies (example scopes: pyproject.toml, setup.py)
+- **build**: Changes that affect build tools or external dependencies (example scopes: pyproject.toml)
- **ci**: Changes to our CI configuration files and scripts (examples: .github/workflows/ci.yml)
- **docs**: Documentation only changes
- **feat**: A new feature
- **fix**: A bugfix
- **perf**: A code change that improves performance
- **refactor**: A code change that neither fixes a bug nor adds a feature
+- **test**: Adding missing tests or correcting existing tests
### Semantic Release
@@ -63,55 +65,13 @@ The table below, from [semantic release](https://github.com/semantic-release/sem
| `perf(pencil): remove graphiteWidth option` `BREAKING CHANGE: The graphiteWidth option has been removed.` `The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release (Note that the `BREAKING CHANGE: ` token must be in the footer of the commit and need to be all caps as shown) |
### Documentation
-
-The maintained Sphinx pages include a curated public API reference; do not regenerate them with `sphinx-apidoc`.
-Build the documentation and treat warnings as errors:
-
+To generate the rst files source files for documentation, run
```bash
-sphinx-build -b html -n -W --keep-going docs/source/ docs/build/html
+uv run sphinx-apidoc -o docs/source/ src
```
-
-External API links use Python, NumPy, and h5py inventories downloaded by Sphinx; a clean build requires network access to those documentation sites.
-
-Keep the README focused on running BandSILo. Put option and staging details in [API and data conventions](docs/source/migration.rst), scientific details in [trace estimation](docs/source/traces.rst), schemas in [file formats](docs/source/file_formats.rst), and ownership decisions in [architecture](docs/source/architecture.rst).
-
-### Read the Docs Deployment
-Note: Private repositories require **Read the Docs for Business** account. The following instructions are for a public repo.
-
-The following are required to import and build documentations on *Read the Docs*:
-- A *Read the Docs* user account connected to Github. See [here](https://docs.readthedocs.com/platform/stable/guides/connecting-git-account.html) for more details.
-- *Read the Docs* needs elevated permissions to perform certain operations that ensure that the workflow is as smooth as possible, like installing webhooks. If you are not the owner of the repo, you may have to request elevated permissions from the owner/admin.
-- A **.readthedocs.yaml** file in the root directory of the repo. Here is a basic template:
-```yaml
-# Read the Docs configuration file
-# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
-
-# Required
-version: 2
-
-# Set the OS, Python version, and other tools you might need
-build:
- os: ubuntu-24.04
- tools:
- python: "3.13"
-
-# Path to a Sphinx configuration file.
-sphinx:
- configuration: docs/source/conf.py
-
-# Declare the Python requirements required to build your documentation
-python:
- install:
- - method: pip
- path: .
- extra_requirements:
- - dev
+Then to create the documentation HTML files, run
+```bash
+uv run sphinx-build -b html docs/source/ docs/build/html
```
+More info on sphinx installation can be found [here](https://www.sphinx-doc.org/en/master/usage/installation.html).
-Here are the steps for building docs in *Read the Docs*. See [here](https://docs.readthedocs.com/platform/stable/intro/add-project.html) for detailed instructions:
-- From *Read the Docs* dashboard, click on **Add project**.
-- For automatic configuration, select **Configure automatically** and type the name of the repo. A repo with public visibility should appear as you type.
-- Follow the subsequent steps.
-- For manual configuration, select **Configure manually** and follow the subsequent steps
-
-Once a project is created successfully, you will be able to configure/modify the project's settings; such as **Default version**, **Default branch** etc.
diff --git a/LICENSE b/LICENSE
index d8f2a228..aa94e4bd 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2022 Allen Institute for Neural Dynamics
+Copyright (c) 2026-03-27 Neural Dynamics accelerator at the Allen Institute
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/docs/source/_static/dark-logo.svg b/docs/source/_static/dark-logo.svg
index dcc68fb1..33d6da25 100644
--- a/docs/source/_static/dark-logo.svg
+++ b/docs/source/_static/dark-logo.svg
@@ -1,129 +1,25 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/source/_static/favicon.ico b/docs/source/_static/favicon.ico
index 4cec1504..bffe9428 100644
Binary files a/docs/source/_static/favicon.ico and b/docs/source/_static/favicon.ico differ
diff --git a/docs/source/_static/light-logo.svg b/docs/source/_static/light-logo.svg
index b20cb67d..d14bae03 100644
--- a/docs/source/_static/light-logo.svg
+++ b/docs/source/_static/light-logo.svg
@@ -1,128 +1,25 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 9fd81d30..433042cc 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -7,72 +7,32 @@
from datetime import date
# -- Path Setup --------------------------------------------------------------
+from importlib.metadata import version as get_version
from os.path import abspath, dirname
from pathlib import Path
-from giant_python import __version__ as package_version
-
-INSTITUTE_NAME = "Allen Institute for Neural Dynamics"
-
current_year = date.today().year
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = Path(dirname(dirname(dirname(abspath(__file__))))).name
-copyright = f"{current_year}, {INSTITUTE_NAME}"
-author = INSTITUTE_NAME
-release = package_version
+copyright = f"{current_year}, Neural Dynamics accelerator at the Allen Institute"
+author = "Neural Dynamics accelerator at the Allen Institute"
+release = get_version("GIAnT-Python")
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = [
"sphinx.ext.duration",
+ "sphinx.ext.doctest",
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
- "sphinx.ext.intersphinx",
]
templates_path = ["_templates"]
exclude_patterns = []
-intersphinx_mapping = {
- "python": ("https://docs.python.org/3/", None),
- "numpy": ("https://numpy.org/doc/stable/", None),
- "h5py": ("https://docs.h5py.org/en/stable/", None),
-}
-
-napoleon_use_param = True
-napoleon_use_rtype = True
-napoleon_preprocess_types = True
-napoleon_type_aliases = {
- "Path": "pathlib.Path",
- "ndarray": "numpy.ndarray",
- "TrialTable": "giant_python.models.trial_table.TrialTable",
- "Slap2Info": "giant_python.models.trial_table.Slap2Info",
- "BandSiloParams": "giant_python.models.params.BandSiloParams",
- "ExecutionOptions": "giant_python.models.params.ExecutionOptions",
- "AnnotationOptions": "giant_python.models.params.AnnotationOptions",
- "ExperimentSummary": (
- "giant_python.models.experiment_summary.ExperimentSummary"
- ),
-}
-
-
-def _resolve_public_type_alias(app, env, node, contnode):
- """Resolve h5py's runtime class name through its public documentation."""
- if (
- node.get("refdomain") == "py"
- and node.get("reftarget") == "h5py._hl.group.Group"
- ):
- node["reftarget"] = "h5py.Group"
-
-
-def setup(app):
- """Normalize private type names before intersphinx resolves references."""
- app.connect("missing-reference", _resolve_public_type_alias, priority=400)
-
-
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
@@ -89,3 +49,4 @@ def setup(app):
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = False
+
diff --git a/examples/extract_band.py b/examples/extract_band.py
index ce7c8053..1f42fff2 100644
--- a/examples/extract_band.py
+++ b/examples/extract_band.py
@@ -15,10 +15,11 @@
import argparse
import os
import shutil
+from collections.abc import Generator
from contextlib import contextmanager
from dataclasses import dataclass, replace
from pathlib import Path, PurePosixPath, PureWindowsPath
-from typing import TYPE_CHECKING, Generator
+from typing import TYPE_CHECKING
if TYPE_CHECKING:
from giant_python import (
@@ -53,7 +54,13 @@ class PreparedRun:
def build_parser() -> argparse.ArgumentParser:
- """Describe explicit input roots, safe staging, and split run options."""
+ """Describe explicit input roots, safe staging, and split run options.
+
+ Returns
+ -------
+ argparse.ArgumentParser
+ Parser defining the input roots, staging modes, and run options.
+ """
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--trial-table", type=Path, required=True)
parser.add_argument(
@@ -119,7 +126,18 @@ def build_parser() -> argparse.ArgumentParser:
def require_directory(path: Path) -> Path:
- """Resolve a source directory and fail before staging if it is missing."""
+ """Resolve a source directory and fail before staging if it is missing.
+
+ Returns
+ -------
+ Path
+ The resolved, existing directory path.
+
+ Raises
+ ------
+ NotADirectoryError
+ If the resolved path is not a directory.
+ """
resolved = path.resolve(strict=True)
if not resolved.is_dir():
raise NotADirectoryError(path)
@@ -127,7 +145,13 @@ def require_directory(path: Path) -> Path:
def validate_relative_names(values: object, field: str) -> None:
- """Reject names that would bypass the explicitly selected input roots."""
+ """Reject names that would bypass the explicitly selected input roots.
+
+ Raises
+ ------
+ ValueError
+ If a name is absolute, has a drive anchor, or contains '..'.
+ """
import numpy as np
for entry in np.asarray(values, dtype=object).flat:
@@ -136,12 +160,7 @@ def validate_relative_names(values: object, field: str) -> None:
name = str(entry)
posix = PurePosixPath(name)
windows = PureWindowsPath(name)
- if (
- posix.is_absolute()
- or windows.anchor
- or ".." in posix.parts
- or ".." in windows.parts
- ):
+ if posix.is_absolute() or windows.anchor or ".." in posix.parts or ".." in windows.parts:
raise ValueError(
f"{field} must contain relative filenames without '..': "
f"{name!r}. Rebase the metadata explicitly before staging; "
@@ -150,7 +169,15 @@ def validate_relative_names(values: object, field: str) -> None:
def stage_directory(source: Path, destination: Path, mode: str) -> None:
- """Copy or link a directory without replacing any existing destination."""
+ """Copy or link a directory without replacing any existing destination.
+
+ Raises
+ ------
+ FileExistsError
+ If the destination already exists or is a symlink.
+ ValueError
+ If `mode` is neither "copy" nor "symlink".
+ """
if destination.exists() or destination.is_symlink():
raise FileExistsError(destination)
if mode == "copy":
@@ -172,7 +199,18 @@ def validate_annotation_arguments(
def require_file(path: Path) -> Path:
- """Resolve a required metadata file without creating anything."""
+ """Resolve a required metadata file without creating anything.
+
+ Returns
+ -------
+ Path
+ The resolved, existing file path.
+
+ Raises
+ ------
+ FileNotFoundError
+ If the resolved path is not a file.
+ """
resolved = path.resolve(strict=True)
if not resolved.is_file():
raise FileNotFoundError(path)
@@ -180,7 +218,20 @@ def require_file(path: Path) -> Path:
def validate_destination(requested: Path, sources: tuple[Path, ...]) -> Path:
- """Refuse existing destinations and recursive staging into input trees."""
+ """Refuse existing destinations and recursive staging into input trees.
+
+ Returns
+ -------
+ Path
+ The resolved, not-yet-existing destination directory.
+
+ Raises
+ ------
+ FileExistsError
+ If the requested destination already exists or is a symlink.
+ ValueError
+ If the resolved destination lies inside any of the source directories.
+ """
if requested.exists() or requested.is_symlink():
raise FileExistsError(f"Choose a fresh --results-dir: {requested}")
results = requested.resolve()
@@ -191,7 +242,13 @@ def validate_destination(requested: Path, sources: tuple[Path, ...]) -> Path:
def validate_paths(args: argparse.Namespace) -> InputPaths:
- """Check all paths without modifying files or the environment."""
+ """Check all paths without modifying files or the environment.
+
+ Returns
+ -------
+ InputPaths
+ Resolved table, data, motion, results, annotation and joblib paths.
+ """
table = require_file(args.trial_table)
data = require_directory(args.data_dir)
motion = require_directory(args.motion_correction)
@@ -203,16 +260,24 @@ def validate_paths(args: argparse.Namespace) -> InputPaths:
require_file(annotations / "annotations.h5")
sources += (annotations,)
results = validate_destination(args.results_dir, sources)
- joblib_temp = (
- require_directory(args.joblib_temp)
- if args.joblib_temp is not None
- else None
- )
+ joblib_temp = require_directory(args.joblib_temp) if args.joblib_temp is not None else None
return InputPaths(table, data, motion, results, annotations, joblib_temp)
def prepare_run(args: argparse.Namespace) -> PreparedRun:
- """Validate metadata and options before staging or environment changes."""
+ """Validate metadata and options before staging or environment changes.
+
+ Returns
+ -------
+ PreparedRun
+ Validated paths, the loaded trial table, and the run settings.
+
+ Raises
+ ------
+ ValueError
+ If the trial table lacks SLAP2 info, motion correction metadata, or
+ `motion_correction/fn_adata`.
+ """
paths = validate_paths(args)
from giant_python import (
AnnotationOptions,
@@ -227,9 +292,7 @@ def prepare_run(args: argparse.Namespace) -> PreparedRun:
if "fn_adata" not in table.motion_correction:
raise ValueError("The table requires motion_correction/fn_adata")
validate_relative_names(table.filename, "filename")
- validate_relative_names(
- table.motion_correction["fn_adata"], "motion_correction/fn_adata"
- )
+ validate_relative_names(table.motion_correction["fn_adata"], "motion_correction/fn_adata")
params = BandSiloParams(
analyze_hz=args.analyze_hz,
decay_tau_s=args.decay_tau_s,
@@ -285,9 +348,7 @@ def stage_and_extract(run: PreparedRun, args: argparse.Namespace) -> None:
results_dir.mkdir(parents=True, exist_ok=False)
staged_table = results_dir / "input_trial_table.h5"
shutil.copy2(paths.table, staged_table)
- stage_directory(
- paths.motion, results_dir / "motion_correction", args.stage_motion
- )
+ stage_directory(paths.motion, results_dir / "motion_correction", args.stage_motion)
if args.stage_data != "none":
staged_data = results_dir / "input"
stage_directory(data_dir, staged_data, args.stage_data)
@@ -311,7 +372,13 @@ def stage_and_extract(run: PreparedRun, args: argparse.Namespace) -> None:
def main(argv: list[str] | None = None) -> int:
- """Validate first, then stage a fresh run and extract registered bands."""
+ """Validate first, then stage a fresh run and extract registered bands.
+
+ Returns
+ -------
+ int
+ Process exit code; always 0 on success.
+ """
parser = build_parser()
args = parser.parse_args(argv)
validate_annotation_arguments(args, parser)
diff --git a/pyproject.toml b/pyproject.toml
index cb5229c9..b3ba65ca 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,20 +1,20 @@
[build-system]
-requires = ["setuptools"]
-build-backend = "setuptools.build_meta"
+requires = ["hatchling"]
+build-backend = "hatchling.build"
[project]
name = "giant-python"
+version = "0.1.14"
description = "Python translation of the GIAnT-MATLAB analysis package."
-license = {text = "MIT"}
+license = "MIT"
requires-python = ">=3.10"
authors = [
- {name = "Allen Institute for Neural Dynamics"}
+ {name = "Neural Dynamics accelerator at the Allen Institute"}
]
classifiers = [
"Programming Language :: Python :: 3"
]
readme = "README.md"
-dynamic = ["version"]
# NOTE: The SLAP2 band-scan (BandSILo) source-extraction backend requires
# ``slap2_utils`` (raw SLAP2 data-file reader). It is not published on PyPI, so
@@ -39,57 +39,69 @@ giant = "giant_python.cli:main"
[dependency-groups]
dev = [
- 'black',
- 'flake8',
- 'interrogate',
- 'isort',
- 'Sphinx',
- 'furo'
+ "ruff>=0.15.20,<1.0.0",
+ "pytest-cov>=7.1.0,<8.0.0",
+ "interrogate>=1.7.0,<2.0.0"
]
+docs = [
+ "Sphinx>=9.1.0,<10.0.0",
+ "furo==2025.12.19"
+]
+
+[tool.uv.dependency-groups]
+docs = { requires-python = ">=3.12" }
+
+[tool.hatch.metadata]
+allow-direct-references = true
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/giant_python"]
-[tool.setuptools.packages.find]
-where = ["src"]
+[tool.pytest.ini_options]
+addopts = [
+ "--cov=src",
+ "--cov-report=term-missing"
+]
+
+[tool.coverage.report]
+exclude_lines = [
+ "if __name__ == .__main__.:",
+ "^from .* import .*",
+ "^import .*",
+ "pragma: no cover"
+]
+fail_under = 80
-[tool.setuptools.package-data]
-# Bundle the default point-spread-function template used by the BandSILo
-# (band-scan) source-extraction backend, and the pages of `giant view`,
-# `giant spine view` and `giant annotate-raster`.
-giant_python = [
- "assets/psfs/*.tif",
- "viewer/page.html",
- "spine/view/page.html",
- "annotator/page.html",
+[tool.ruff]
+preview = true
+src = ["src", "tests"]
+include = ["*.py", "*.pyi", "**/pyproject.toml"]
+exclude = [
+ ".git",
+ ".mypy_cache",
+ ".ruff_cache",
+ ".venv",
+ "venv",
+ "build",
+ "dist",
+ "docs"
]
+line-length = 100
-[tool.setuptools.dynamic]
-version = {attr = "giant_python.__version__"}
+[tool.ruff.lint]
+select = ["I", "E", "F", "W", "ANN", "W505", "D", "DOC"]
-[tool.black]
-line-length = 79
-target_version = ['py310']
-exclude = '''
+[tool.ruff.lint.pycodestyle]
+max-doc-length = 100
-(
- /(
- \.eggs # exclude a few common directories in the
- | \.git # root of the project
- | \.hg
- | \.mypy_cache
- | \.venv
- | _build
- | build
- | dist
- | .conda
- )/
- | .gitignore
-)
-'''
+[tool.ruff.lint.pydocstyle]
+convention = "numpy"
-[tool.isort]
-line_length = 79
-profile = "black"
-skip = [".conda"]
+[tool.ruff.format]
+docstring-code-format = true
[tool.interrogate]
-exclude = ["setup.py", "docs", "build", ".conda"]
-fail-under = 100
+ignore-init-methods = true
+ignore-init-module = true
+exclude = ["docs", "build", ".conda", ".venv", "env"]
+fail-under = 100
\ No newline at end of file
diff --git a/setup.py b/setup.py
deleted file mode 100644
index 7f1a1763..00000000
--- a/setup.py
+++ /dev/null
@@ -1,4 +0,0 @@
-from setuptools import setup
-
-if __name__ == "__main__":
- setup()
diff --git a/src/giant_python/__init__.py b/src/giant_python/__init__.py
index 7e473415..d043aded 100644
--- a/src/giant_python/__init__.py
+++ b/src/giant_python/__init__.py
@@ -1,15 +1,17 @@
-"""GIAnT-Python: registration, band extraction and a chainable ``Pipeline``.
+"""GIAnT-Python: registration, band extraction and a chainable Pipeline.
-``register_multiroi`` registers SLAP2 raster recordings
-(``MultiRoiRegistrationParams``). Use ``BandSiloParams`` for science,
-``ExecutionOptions`` for run policy and ``AnnotationOptions`` for ROI/GUI
-policy. ``extract_sources`` defaults to the
+register_multiroi registers SLAP2 raster recordings
+(MultiRoiRegistrationParams). Use BandSiloParams for science,
+ExecutionOptions for run policy and AnnotationOptions for ROI/GUI
+policy. extract_sources defaults to the
implemented SLAP2 band workflow; explicitly requested unsupported modes raise.
Public exports are lazy: importing GIAnT does not load acquisition or GUI
toolkits. Summary arrays are currently eager, not disk-backed.
"""
from importlib import import_module
+from importlib.metadata import PackageNotFoundError
+from importlib.metadata import version as _installed_version
from typing import TYPE_CHECKING
if TYPE_CHECKING:
@@ -33,7 +35,11 @@
register_multiroi,
)
-__version__ = "0.1.14"
+try:
+ # The version is set once, in pyproject.toml; saved results record this same value.
+ __version__ = _installed_version("giant-python")
+except PackageNotFoundError: # a source tree that was never installed
+ __version__ = "0+unknown"
_MODEL_EXPORTS = {
"AnnotationOptions",
@@ -56,8 +62,24 @@
}
-def __getattr__(name: str):
- """Load a public model or workflow export on first access."""
+def __getattr__(name: str) -> object:
+ """Load a public model or workflow export on first access.
+
+ Parameters
+ ----------
+ name : str
+ Name of the public export to load.
+
+ Returns
+ -------
+ object
+ The requested model or workflow export, cached in the module globals.
+
+ Raises
+ ------
+ AttributeError
+ If name is not a public model or workflow export.
+ """
if name in _MODEL_EXPORTS:
module = import_module(".models", __name__)
elif name in _PIPELINE_EXPORTS:
@@ -70,7 +92,13 @@ def __getattr__(name: str):
def __dir__() -> list[str]:
- """Include lazy public exports in interactive completion."""
+ """Include lazy public exports in interactive completion.
+
+ Returns
+ -------
+ list[str]
+ Sorted module attribute names, including the lazy public exports.
+ """
return sorted(set(globals()) | set(__all__))
diff --git a/src/giant_python/annotator/__init__.py b/src/giant_python/annotator/__init__.py
index 2b05f004..18c0cb1f 100644
--- a/src/giant_python/annotator/__init__.py
+++ b/src/giant_python/annotator/__init__.py
@@ -1,3 +1,5 @@
-"""``giant annotate-raster``: soma and plain ROIs of a registered raster
-session, drawn in the browser on images of the whole
-session (:mod:`.session`, :mod:`.state`, :mod:`.server`)."""
+"""``giant annotate-raster``: soma and plain ROIs of a registered raster session.
+
+The ROIs are drawn in the browser on images of the whole
+session (:mod:`.session`, :mod:`.state`, :mod:`.server`).
+"""
diff --git a/src/giant_python/annotator/files.py b/src/giant_python/annotator/files.py
index 66747d0e..c39479c9 100644
--- a/src/giant_python/annotator/files.py
+++ b/src/giant_python/annotator/files.py
@@ -1,24 +1,24 @@
-"""Reading and writing the annotator's ``annotations.h5``.
+"""Reading and writing the annotator's annotations.h5.
-The file is GIAnT-MATLAB's (``saveAnnotationsH5.m``, schema 2), which
-GIAnT-MATLAB's and GIAnT-Python's SILo read: per path ``Path`` with
-``dr``, ``fn`` (the stem of the registered trial the ROIs are drawn in:
-the annotator's anchor trial), ``n_rois`` and ``roi_###`` groups with
-``type``, ``label``, ``mask`` and ``position``. Soma and plain ROIs go
+The file is GIAnT-MATLAB's (saveAnnotationsH5.m, schema 2), which
+GIAnT-MATLAB's and GIAnT-Python's SILo read: per path Path with
+dr, fn (the stem of the registered trial the ROIs are drawn in:
+the annotator's anchor trial), n_rois and roi_### groups with
+type, label, mask and position. Soma and plain ROIs go
there, as polygons.
-What those readers do not know is kept in a group ``/annotator`` that they
-ignore (both look only at root groups named ``Path`` or ``DMD``):
+What those readers do not know is kept in a group /annotator that they
+ignore (both look only at root groups named Path or DMD):
-* ``/annotator/state_json``: the whole state (:mod:`.state`) with the
+* /annotator/state_json: the whole state (:mod:`.state`) with the
polygons in each path's anchor-trial coordinates and the anchor's stem,
so that a later session restores it exactly;
-* ``/annotator/Path/fn``: the anchor trial's stem, including for paths
- that have yet to be annotated (``Path/fn`` is empty).
+* /annotator/Path/fn: the anchor trial's stem, including for paths
+ that have yet to be annotated (Path/fn is empty).
Arrays are stored column-major and strings as UTF-16 code units, as
-MATLAB's ``h5write`` does. A file that was not written by the annotator
-is copied to ``annotations.h5.before-annotator`` before it is replaced.
+MATLAB's h5write does. A file that was not written by the annotator
+is copied to annotations.h5.before-annotator before it is replaced.
"""
from __future__ import annotations
@@ -30,10 +30,10 @@
import warnings
from contextlib import nullcontext
from pathlib import Path
-from typing import Optional
import h5py
import numpy as np
+import numpy.typing as npt
from ..extraction.raster.annotations import (
_text,
@@ -41,8 +41,7 @@
read_annotations,
)
from .session import AnnotatorSession, PathData
-from .state import KINDS, _points, clean_state, empty_state
-from .state import mask_outline, polygon_mask
+from .state import KINDS, _points, clean_state, empty_state, mask_outline, polygon_mask
SCHEMA_VERSION = 2 # GIAnT-MATLAB's annotationsSchemaVersion
GROUP = "annotator"
@@ -50,25 +49,71 @@
def _chars(text: str) -> np.ndarray:
- """A string as MATLAB's ``1 x n`` uint16 character codes."""
+ """Return a string as MATLAB's 1 x n uint16 character codes.
+
+ Parameters
+ ----------
+ text : str
+ The string.
+
+ Returns
+ -------
+ np.ndarray
+ The uint16 character codes, as a column.
+ """
codes = np.frombuffer(str(text).encode("utf-16-le"), dtype=" np.ndarray:
- """An array as MATLAB's ``h5write`` stores it (column-major)."""
+ """Return an array as MATLAB's h5write stores it (column-major).
+
+ Parameters
+ ----------
+ a : np.ndarray
+ The array.
+
+ Returns
+ -------
+ np.ndarray
+ The array, transposed and contiguous if it has two or more dimensions.
+ """
a = np.asarray(a)
return np.ascontiguousarray(a.T) if a.ndim >= 2 else a
-def _scalar(value, dtype) -> np.ndarray:
- """A MATLAB ``1 x 1`` value."""
+def _scalar(value: float, dtype: npt.DTypeLike) -> np.ndarray:
+ """Return a MATLAB 1 x 1 value.
+
+ Parameters
+ ----------
+ value : float
+ The value.
+ dtype : dtype-like
+ The array's data type.
+
+ Returns
+ -------
+ np.ndarray
+ The value as a 1 x 1 array.
+ """
return np.array([[value]], dtype=dtype)
def _mask(group: h5py.Group, name: str, mask: np.ndarray) -> None:
- """A mask as MATLAB's uint8 array, deflated (masks are mostly zero;
- MATLAB's and h5py's readers inflate it unasked)."""
+ """Write a mask as MATLAB's uint8 array, deflated.
+
+ Masks are mostly zero; MATLAB's and h5py's readers inflate it unasked.
+
+ Parameters
+ ----------
+ group : h5py.Group
+ The group to write to.
+ name : str
+ The dataset's name.
+ mask : np.ndarray
+ The mask.
+ """
group.create_dataset(
name,
data=_matlab(np.asarray(mask).astype(np.uint8)),
@@ -77,10 +122,24 @@ def _mask(group: h5py.Group, name: str, mask: np.ndarray) -> None:
)
-def anchor_stems(path, n_paths: int) -> list:
- """The trial each path's annotations are drawn in, from an existing
- file: the annotator's saved anchors, else ``Path/fn``; empty
- strings without a file."""
+def anchor_stems(path: str | Path | None, n_paths: int) -> list[str]:
+ """Return the trial each path's annotations are drawn in, from an existing file.
+
+ The trial is the annotator's saved anchor, else Path/fn; empty
+ strings without a file.
+
+ Parameters
+ ----------
+ path : str, Path or None
+ The file, if any.
+ n_paths : int
+ The number of paths.
+
+ Returns
+ -------
+ list of str
+ The stem of each path's anchor trial; empty where unknown.
+ """
out = [""] * n_paths
if path is None or not Path(path).exists():
return out
@@ -97,8 +156,19 @@ def anchor_stems(path, n_paths: int) -> list:
return out
-def _saved_state(f: h5py.File) -> Optional[dict]:
- """The annotator's state stored in an open file, if any."""
+def _saved_state(f: h5py.File) -> dict | None:
+ """Return the annotator's state stored in an open file, if any.
+
+ Parameters
+ ----------
+ f : h5py.File
+ The open file.
+
+ Returns
+ -------
+ dict or None
+ The state; None if the file has none or it cannot be read.
+ """
name = f"{GROUP}/state_json"
if name not in f:
return None
@@ -111,14 +181,43 @@ def _saved_state(f: h5py.File) -> Optional[dict]:
return obj if isinstance(obj, dict) else None
-def _path_group(f: h5py.File, d: int):
- """The public HDF5 group for a zero-based path, including legacy names."""
+def _path_group(f: h5py.File, d: int) -> h5py.Group | None:
+ """Return the public HDF5 group for a zero-based path, including legacy names.
+
+ Parameters
+ ----------
+ f : h5py.File
+ The open file.
+ d : int
+ The zero-based path.
+
+ Returns
+ -------
+ h5py.Group or None
+ The group Path (or legacy DMD); None if absent.
+ """
return f.get(f"Path{d + 1}", f.get(f"DMD{d + 1}"))
-def _anchor_points(points, data: PathData, stem: str) -> list:
- """Points of the trial called ``stem`` as canvas points (through the
- anchor if that trial is not in the session)."""
+def _anchor_points(points: npt.ArrayLike, data: PathData, stem: str) -> list:
+ """Return points of the trial called stem as canvas points.
+
+ A trial that is not in the session goes through the anchor.
+
+ Parameters
+ ----------
+ points : array-like
+ The [x, y] points in the frame of the trial called stem.
+ data : PathData
+ The path's data.
+ stem : str
+ The stem of the trial the points are drawn in.
+
+ Returns
+ -------
+ list
+ The points as canvas [x, y] points.
+ """
trial = annotation_trial(stem, data.stems) if stem else None
if trial is None or not data.present[trial]:
if stem:
@@ -131,11 +230,11 @@ def _anchor_points(points, data: PathData, stem: str) -> list:
return data.trial_to_canvas(points, trial).tolist()
-def read_state(path, session: AnnotatorSession) -> dict:
- """The state of an existing ``annotations.h5``, in canvas coordinates.
+def read_state(path: str | Path | None, session: AnnotatorSession) -> dict:
+ """Return the state of an existing annotations.h5, in canvas coordinates.
A file written by the annotator gives back what was saved. Another
- file (GIAnT-MATLAB's) gives its ROIs as polygons (``position`` if
+ file (GIAnT-MATLAB's) gives its ROIs as polygons (position if
stored, else the outline of the mask).
Parameters
@@ -153,8 +252,25 @@ def read_state(path, session: AnnotatorSession) -> dict:
return _read_state_and_labels(path, session)[0]
-def _read_state_and_labels(path, session):
- """Read the editable state and reserve labels of undisplayed ROIs."""
+def _read_state_and_labels(
+ path: str | Path | None, session: AnnotatorSession
+) -> tuple[dict, list[str]]:
+ """Read the editable state and reserve labels of undisplayed ROIs.
+
+ Parameters
+ ----------
+ path : str, Path or None
+ The file; None or a missing file gives an empty state.
+ session : AnnotatorSession
+ The session, whose paths' canvases place the polygons.
+
+ Returns
+ -------
+ state : dict
+ The editable state.
+ labels : list of str
+ The labels of the ROIs kept outside the editor.
+ """
if path is None or not Path(path).exists():
return empty_state(session.n_paths), []
with h5py.File(path, "r") as f:
@@ -162,13 +278,45 @@ def _read_state_and_labels(path, session):
return state, _reserved_labels(hidden)
-def _reserved_labels(hidden):
- """Labels already used by the ROIs kept outside the editor."""
+def _reserved_labels(hidden: dict) -> list[str]:
+ """Return the labels already used by the ROIs kept outside the editor.
+
+ Parameters
+ ----------
+ hidden : dict
+ The HDF5 ROI groups kept outside the editor, by path.
+
+ Returns
+ -------
+ list of str
+ Their labels.
+ """
return [_text(roi, "label") for rois in hidden.values() for roi in rois]
-def _read_existing(f, session, saved): # noqa: C901
- """Read editable polygons and references to their original HDF5 ROIs."""
+def _read_existing(
+ f: h5py.File | None, session: AnnotatorSession, saved: dict | None
+) -> tuple[dict, dict, dict]:
+ """Read editable polygons and references to their original HDF5 ROIs.
+
+ Parameters
+ ----------
+ f : h5py.File or None
+ The open file; None gives an empty state.
+ session : AnnotatorSession
+ The session, whose paths' canvases place the polygons.
+ saved : dict or None
+ The annotator's saved state in the file, if any.
+
+ Returns
+ -------
+ state : dict
+ The editable state.
+ sources : dict
+ The original HDF5 ROI group for each (path, mask_id).
+ hidden : dict
+ The HDF5 ROI groups kept outside the editor, by path.
+ """
n_paths = session.n_paths
state = empty_state(n_paths)
sources, hidden = {}, {}
@@ -192,16 +340,10 @@ def _read_existing(f, session, saved): # noqa: C901
entry = entries[d] if d < len(entries) else None
if entry is not None:
stem = str(entry.get("anchor_fn") or "")
- polygons = [
- r
- for r in entry.get("rois") or []
- if r.get("kind", "roi") in KINDS
- ]
+ polygons = [r for r in entry.get("rois") or [] if r.get("kind", "roi") in KINDS]
for i, roi in enumerate(polygons):
moved = dict(roi)
- moved["points"] = _anchor_points(
- roi.get("points") or [], data, stem
- )
+ moved["points"] = _anchor_points(roi.get("points") or [], data, stem)
if legacy and i < n:
moved["mask_id"] = i + 1
mask_id = moved.get("mask_id")
@@ -226,27 +368,43 @@ def _read_existing(f, session, saved): # noqa: C901
if original[i] is not None:
hidden[d].append(original[i])
continue
- rois.append(
- {
- "kind": "soma" if roi.is_soma else "roi",
- "label": roi.label,
- "points": _anchor_points(pts, data, entry.fn),
- "mask_id": i + 1,
- }
- )
+ rois.append({
+ "kind": "soma" if roi.is_soma else "roi",
+ "label": roi.label,
+ "points": _anchor_points(pts, data, entry.fn),
+ "mask_id": i + 1,
+ })
if original[i] is not None:
sources[d, i + 1] = original[i]
- state = clean_state(
- state, n_paths, reserved_labels=_reserved_labels(hidden)
- )
+ state = clean_state(state, n_paths, reserved_labels=_reserved_labels(hidden))
return state, sources, hidden
def _write_roi(
- group: h5py.Group, label: str, pts, shape, mask=None, zero_indexed=True
+ group: h5py.Group,
+ label: str,
+ pts: npt.ArrayLike,
+ shape: tuple[int, int],
+ mask: np.ndarray | None = None,
+ zero_indexed: bool = True,
) -> None:
- """One polygon in MATLAB's ROI layout: ``pts`` are ``[x, y]`` image
- coordinates of the anchor trial, ``shape`` its frame size."""
+ """Write one polygon in MATLAB's ROI layout.
+
+ Parameters
+ ----------
+ group : h5py.Group
+ The ROI's group.
+ label : str
+ The ROI's label.
+ pts : array-like
+ [x, y] image coordinates of the anchor trial.
+ shape : tuple of int
+ The anchor trial's frame size.
+ mask : np.ndarray or None
+ The ROI's mask; drawn from the polygon if None.
+ zero_indexed : bool
+ Whether the coordinates are zero-based.
+ """
pts = np.asarray(pts, np.float64).reshape(-1, 2)
group["type"] = _chars("polygon")
group["label"] = _chars(label)
@@ -255,8 +413,8 @@ def _write_roi(
group["position"] = _matlab(pos)
-def write_annotations(path, session: AnnotatorSession, state: dict) -> Path:
- """Write the state as ``annotations.h5`` (see the module docstring).
+def write_annotations(path: str | Path, session: AnnotatorSession, state: dict) -> Path:
+ """Write the state as annotations.h5 (see the module docstring).
Parameters
----------
@@ -289,23 +447,39 @@ def write_annotations(path, session: AnnotatorSession, state: dict) -> Path:
return path
-def _write_file(tmp, path, session, state, anchors): # noqa: C901
- """Build the replacement file, preserving masks in their original frame."""
+def _write_file(
+ tmp: Path, path: Path, session: AnnotatorSession, state: dict, anchors: list[str]
+) -> None:
+ """Build the replacement file, preserving masks in their original frame.
+
+ Parameters
+ ----------
+ tmp : Path
+ The file to write.
+ path : Path
+ The existing file (if any), whose masks are preserved.
+ session : AnnotatorSession
+ The session; every path's data is needed.
+ state : dict
+ The state in canvas coordinates.
+ anchors : list of str
+ The stem of each path's anchor trial.
+
+ Raises
+ ------
+ ValueError
+ If a path's annotation trial is unavailable, or a ROI crosses the
+ anchor frame or covers no pixels.
+ """
previous = h5py.File(path, "r") if path.exists() else nullcontext()
with previous as old, h5py.File(tmp, "w") as f:
old_saved = _saved_state(old) if old is not None else None
old_state, sources, hidden = _read_existing(old, session, old_saved)
- state = clean_state(
- state, session.n_paths, reserved_labels=_reserved_labels(hidden)
- )
+ state = clean_state(state, session.n_paths, reserved_labels=_reserved_labels(hidden))
saved = {"version": state["version"], "paths": []}
- legacy = (
- old_saved is not None
- and old[GROUP].attrs.get("file_version", 1) < 2
- )
+ legacy = old_saved is not None and old[GROUP].attrs.get("file_version", 1) < 2
zero = old is None or (
- "coords_zero_indexed" in old
- and bool(old["coords_zero_indexed"][()].item())
+ "coords_zero_indexed" in old and bool(old["coords_zero_indexed"][()].item())
)
f["row_major"] = _scalar(0, np.uint8)
f["coords_zero_indexed"] = _scalar(zero, np.uint8)
@@ -326,16 +500,10 @@ def _write_file(tmp, path, session, state, anchors): # noqa: C901
missing_anchor = fn and (trial is None or not data.present[trial])
if data is None or ((before or uneditable) and missing_anchor):
if data is not None and current != before:
- raise ValueError(
- f"path {d + 1}: annotation trial {fn!r} is unavailable"
- )
+ raise ValueError(f"path {d + 1}: annotation trial {fn!r} is unavailable")
if prior is not None:
old.copy(prior, f, name=name)
- if (
- legacy
- and not (before or uneditable)
- and "fn" in f[name]
- ):
+ if legacy and not (before or uneditable) and "fn" in f[name]:
del f[name]["fn"]
else:
f.create_group(name)["n_rois"] = _scalar(0, np.uint32)
@@ -348,9 +516,7 @@ def _write_file(tmp, path, session, state, anchors): # noqa: C901
x["fn"] = _chars(stem)
g = f.create_group(name)
g["dr"] = _chars(str(session.moco_dir))
- annotated = bool(
- current or uneditable or (fn and (before or not legacy))
- )
+ annotated = bool(current or uneditable or (fn and (before or not legacy)))
g["fn"] = _chars(stem if annotated else "")
old_points = {r.get("mask_id"): r["points"] for r in before}
rois = []
@@ -359,10 +525,7 @@ def _write_file(tmp, path, session, state, anchors): # noqa: C901
mask_id = roi.get("mask_id")
source = sources.get((d, mask_id))
key = f"roi_{i:03d}"
- if (
- source is not None
- and old_points.get(mask_id) == roi["points"]
- ):
+ if source is not None and old_points.get(mask_id) == roi["points"]:
old.copy(source, g, name=key)
if _text(g[key], "label") != roi["label"]:
if "label" in g[key]:
@@ -372,8 +535,7 @@ def _write_file(tmp, path, session, state, anchors): # noqa: C901
label = f"path {d + 1}: ROI {roi['label']!r}"
if (pts < 0).any() or (pts > shape[::-1]).any():
raise ValueError(
- f"{label} crosses the anchor frame. "
- "Move it inside the dashed outline."
+ f"{label} crosses the anchor frame. Move it inside the dashed outline."
)
mask = polygon_mask(pts, shape)
if not mask.any():
@@ -399,8 +561,15 @@ def _write_file(tmp, path, session, state, anchors): # noqa: C901
def _backup_foreign(path: Path) -> None:
- """Copy an existing file that the annotator did not write aside, once
- (``.before-annotator``; with a time stamp if that exists)."""
+ """Copy an existing file that the annotator did not write aside, once.
+
+ The copy is .before-annotator (with a time stamp if that exists).
+
+ Parameters
+ ----------
+ path : Path
+ The file about to be replaced.
+ """
if not path.exists():
return
try:
@@ -411,7 +580,5 @@ def _backup_foreign(path: Path) -> None:
pass # not readable as HDF5: keep a copy all the same
backup = path.with_name(path.name + ".before-annotator")
if backup.exists():
- backup = path.with_name(
- f"{path.name}.before-annotator-{time.strftime('%Y%m%d-%H%M%S')}"
- )
+ backup = path.with_name(f"{path.name}.before-annotator-{time.strftime('%Y%m%d-%H%M%S')}")
shutil.copy2(path, backup)
diff --git a/src/giant_python/annotator/server.py b/src/giant_python/annotator/server.py
index 10237327..731bc005 100644
--- a/src/giant_python/annotator/server.py
+++ b/src/giant_python/annotator/server.py
@@ -1,8 +1,8 @@
"""``giant annotate-raster``: draw the ROIs of a raster session in the browser.
-``giant annotate-raster TRIAL_TABLE`` reads a registered raster session's
+giant annotate-raster TRIAL_TABLE reads a registered raster session's
alignment files (:mod:`.session`), serves http://127.0.0.1:8791 (one
-page, :data:`PAGE`) and writes ``/annotations/annotations.h5``
+page, :data:`PAGE`) and writes /annotations/annotations.h5
(:mod:`.files`) whenever the page changes something:
* **the image**: the session's mean image (all good trials, or a range of
@@ -15,26 +15,27 @@
template, sharpness, motion, discarded frames and online z, which points
out the trials that look unusual.
-API (used by the page): GET ``/api/meta``; ``/api/pixels?path=`` (uint32
+API (used by the page): GET /api/meta; /api/pixels?path= (uint32
flat canvas indices of the path's imaged pixels); ``/api/image?path=&kind=
-session|range|trial&trial=&first=&last=`` (float32 ``channels x pixels``
-at those pixels, shape in ``X-Shape``; ``path`` and trials one-based);
-``/api/coverage?path=`` (uint8 per imaged pixel: the share of the session
-image's trials that imaged it, 255 = all); ``/api/traces?path=&trial=``
-(JSON); ``/api/browse?dir=&find=1`` (a
+session|range|trial&trial=&first=&last=`` (float32 channels x pixels
+at those pixels, shape in X-Shape; path and trials one-based);
+/api/coverage?path= (uint8 per imaged pixel: the share of the session
+image's trials that imaged it, 255 = all); /api/traces?path=&trial=
+(JSON); /api/browse?dir=&find=1 (a
folder's subfolders and trial tables, for the Open dialog); POST
-``/api/state`` (JSON state and its revision; answers the new revision,
-cleaned state and each path's soma brightness), ``/api/open``
-(``{"table": path}``; answers the new session's meta) and ``/api/close``.
-Each POST includes the session ID from ``/api/meta``.
+/api/state (JSON state and its revision; answers the new revision,
+cleaned state and each path's soma brightness), /api/open
+({"table": path}; answers the new session's meta) and /api/close.
+Each POST includes the session ID from /api/meta.
-``giant annotate-raster`` without a table starts with the Open dialog, and
+giant annotate-raster without a table starts with the Open dialog, and
the page's Open button switches sessions, so that several acquisitions can
be annotated one after another without restarting.
"""
from __future__ import annotations
+import argparse
import json
import os
import threading
@@ -42,54 +43,93 @@
import webbrowser
from http.server import ThreadingHTTPServer
from pathlib import Path
-from typing import Optional
from urllib.parse import parse_qs, urlparse
from uuid import uuid4
import numpy as np
+import numpy.typing as npt
-from ..spine.view.server import _bracket
+from ..spine.view.server import _bracket, _Server6, allowed_hosts
from ..spine.view.server import _Handler as _BaseHandler
-from ..spine.view.server import _Server6, allowed_hosts
from .files import _read_state_and_labels, anchor_stems, write_annotations
-from .session import MOTION_SD_FLAG, STAT_NAMES, AnnotatorSession
+from .session import MOTION_SD_FLAG, STAT_NAMES, AnnotatorSession, PathData
from .state import clean_state, polygon_mask
PAGE = Path(__file__).with_name("page.html")
DEFAULT_PORT = 8791
-def _round(a, nd: int = 4) -> list:
- """An array as a list rounded to ``nd`` decimals (NaN stays NaN; the
- handler sends it as null)."""
+def _round(a: npt.ArrayLike, nd: int = 4) -> list:
+ """Return an array as a list rounded to nd decimals.
+
+ NaN stays NaN; the handler sends it as null.
+
+ Parameters
+ ----------
+ a : array_like
+ The values.
+ nd : int
+ Decimals to round to.
+
+ Returns
+ -------
+ list
+ The rounded values as nested lists.
+ """
return np.round(np.asarray(a, np.float64), nd).tolist()
#: Folders the search for trial tables does not enter.
-SKIP_DIRS = frozenset(
- {
- "motion_correction",
- "source_extraction",
- "annotations",
- "cache",
- "raw_dat",
- "ref",
- "__pycache__",
- }
-)
+SKIP_DIRS = frozenset({
+ "motion_correction",
+ "source_extraction",
+ "annotations",
+ "cache",
+ "raw_dat",
+ "ref",
+ "__pycache__",
+})
FIND_DEPTH, FIND_LIMIT, FIND_SECONDS = 5, 300, 8.0
-def session_label(table) -> str:
- """A short name for a session: the last two folders above its table
- (``/``)."""
+def session_label(table: str | Path) -> str:
+ """Return a short name for a session.
+
+ It is the last two folders above its table
+ (/).
+
+ Parameters
+ ----------
+ table : str or Path
+ The session's trial table.
+
+ Returns
+ -------
+ str
+ The folder names joined by /.
+ """
parts = Path(table).resolve().parent.parts[-2:]
return "/".join(p for p in parts if p not in ("/", ""))
def _table_entry(path: Path, base: Path) -> dict:
- """A trial table for the page's list: where it is and whether its
- folder already holds annotations."""
+ """Return a trial table for the page's list.
+
+ The entry says where the table is and whether its
+ folder already holds annotations.
+
+ Parameters
+ ----------
+ path : Path
+ The trial table.
+ base : Path
+ The folder the table is shown relative to, if it is below it.
+
+ Returns
+ -------
+ dict
+ path, name (relative to base where possible) and annotated.
+ """
try:
shown = str(path.relative_to(base))
except ValueError:
@@ -101,13 +141,13 @@ def _table_entry(path: Path, base: Path) -> dict:
}
-def browse(directory, find: bool = False) -> dict: # noqa: C901
- """What the page's Open dialog lists for a folder.
+def browse(directory: str | Path | None, find: bool = False) -> dict:
+ """List what the page's Open dialog shows for a folder.
Parameters
----------
directory : str or Path
- The folder (``~`` is expanded; a file gives its folder).
+ The folder (~ is expanded; a file gives its folder).
find : bool
Also search the folders below it for trial tables (at most
:data:`FIND_DEPTH` levels, :data:`FIND_LIMIT` tables and
@@ -117,10 +157,10 @@ def browse(directory, find: bool = False) -> dict: # noqa: C901
Returns
-------
dict
- ``dir``, ``parent`` (None at the root), ``dirs`` (subfolder names),
- ``tables`` (``trial_table*.h5`` in the folder) and, with ``find``,
- ``found`` and ``truncated``; each table as ``path``, ``name`` and
- ``annotated``.
+ dir, parent (None at the root), dirs (subfolder names),
+ tables (trial_table*.h5 in the folder) and, with find,
+ found and truncated; each table as path, name and
+ annotated.
Raises
------
@@ -157,9 +197,7 @@ def browse(directory, find: bool = False) -> dict: # noqa: C901
subdirs[:] = sorted(
x
for x in subdirs
- if depth < FIND_DEPTH
- and x not in SKIP_DIRS
- and not x.startswith(".")
+ if depth < FIND_DEPTH and x not in SKIP_DIRS and not x.startswith(".")
)
for name in sorted(names):
if name.startswith("trial_table") and name.endswith(".h5"):
@@ -180,17 +218,26 @@ class AnnotatorStore:
The registered session.
annotations : str or Path, optional
The file to read and write (default
- ``/annotations/annotations.h5``).
+ /annotations/annotations.h5).
label : str
Session label for the page.
"""
- def __init__(self, session: AnnotatorSession, annotations=None, label=""):
- """Build every path's data and read an existing file."""
+ def __init__(
+ self,
+ session: AnnotatorSession,
+ annotations: str | Path | None = None,
+ label: str = "",
+ ) -> None:
+ """Build every path's data and read an existing file.
+
+ Raises
+ ------
+ ValueError
+ If no imaging path has a readable alignment file.
+ """
self.session = session
- self.file = Path(
- annotations or session.savedr / "annotations" / "annotations.h5"
- )
+ self.file = Path(annotations or session.savedr / "annotations" / "annotations.h5")
self.label = label or session_label(session.table_path)
anchors = anchor_stems(self.file, session.n_paths)
self.paths = []
@@ -199,9 +246,7 @@ def __init__(self, session: AnnotatorSession, annotations=None, label=""):
self.paths.append(session.path(d, anchors[d]))
p = self.paths[-1]
if p is None:
- print(
- f" path {d + 1}: no readable alignment file", flush=True
- )
+ print(f" path {d + 1}: no readable alignment file", flush=True)
continue
print(
f" path {d + 1}: {int(p.present.sum())} trials, "
@@ -211,16 +256,24 @@ def __init__(self, session: AnnotatorSession, annotations=None, label=""):
if not any(p is not None for p in self.paths):
raise ValueError("no imaging path has a readable alignment file")
self.had_file = self.file.exists()
- self.state, self.reserved_labels = _read_state_and_labels(
- self.file, session
- )
+ self.state, self.reserved_labels = _read_state_and_labels(self.file, session)
self.state_revision = 0
self.saved = ""
self._lock = threading.Lock()
def meta(self) -> dict:
- """What the page needs once: the session, its paths' statistics
- and the current state."""
+ """Return what the page needs once.
+
+ That is the session, its paths' statistics
+ and the current state.
+
+ Returns
+ -------
+ dict
+ The page's metadata: label, table, file, had_file, saved,
+ n_trials, start_min, motion_sd_flag, paths (one entry per
+ path), reserved_labels, state and state_revision.
+ """
s = self.session
paths = []
for d, p in enumerate(self.paths):
@@ -231,30 +284,28 @@ def meta(self) -> dict:
(p.frame_offset - p.frame_offset[p.anchor])[p.present],
axis=0,
)
- paths.append(
- {
- "path": d + 1,
- "rows": p.shape[0],
- "cols": p.shape[1],
- "channels": p.n_channels,
- "anchor": p.anchor + 1,
- "anchor_fn": p.stems[p.anchor],
- "edit_bounds": [
- *(-p.frame_offset[p.anchor][::-1]).tolist(),
- *p.frame_shape[p.anchor][::-1].tolist(),
- ],
- "present": p.present.astype(int).tolist(),
- "failed": p.failed.astype(int).tolist(),
- "good": p.good.astype(int).tolist(),
- "stems": p.stems,
- "stats": {k: _round(p.stats[k]) for k in STAT_NAMES},
- "match_thresh": round(float(p.match_thresh), 4),
- "scale": _round(p.scale, 5),
- "chunks": [[a + 1, b + 1] for a, b in s.chunks(d)],
- "max_shift": int(np.abs(origins).max()),
- "soma": self.soma(d),
- }
- )
+ paths.append({
+ "path": d + 1,
+ "rows": p.shape[0],
+ "cols": p.shape[1],
+ "channels": p.n_channels,
+ "anchor": p.anchor + 1,
+ "anchor_fn": p.stems[p.anchor],
+ "edit_bounds": [
+ *(-p.frame_offset[p.anchor][::-1]).tolist(),
+ *p.frame_shape[p.anchor][::-1].tolist(),
+ ],
+ "present": p.present.astype(int).tolist(),
+ "failed": p.failed.astype(int).tolist(),
+ "good": p.good.astype(int).tolist(),
+ "stems": p.stems,
+ "stats": {k: _round(p.stats[k]) for k in STAT_NAMES},
+ "match_thresh": round(float(p.match_thresh), 4),
+ "scale": _round(p.scale, 5),
+ "chunks": [[a + 1, b + 1] for a, b in s.chunks(d)],
+ "max_shift": int(np.abs(origins).max()),
+ "soma": self.soma(d),
+ })
return {
"label": self.label,
"table": str(s.table_path),
@@ -271,7 +322,7 @@ def meta(self) -> dict:
}
def image(self, d: int, kind: str, q: dict) -> np.ndarray:
- """An image of zero-based path ``d`` at its imaged pixels.
+ """Return an image of zero-based path d at its imaged pixels.
Parameters
----------
@@ -279,7 +330,7 @@ def image(self, d: int, kind: str, q: dict) -> np.ndarray:
Zero-based path.
kind : {'session', 'range', 'trial'}
The mean over the path's good trials; the mean over the
- present trials ``first``..``last``; or trial ``trial``'s mean
+ present trials first..last; or trial trial's mean
image.
q : dict
The request's other parameters (one-based trials).
@@ -288,6 +339,12 @@ def image(self, d: int, kind: str, q: dict) -> np.ndarray:
-------
ndarray of float32, (channels, pixels)
Values at the path's imaged pixels (:meth:`pixels`).
+
+ Raises
+ ------
+ ValueError
+ If the path is not available, the trial does not exist or kind is
+ unknown.
"""
p = self._available_path(d)
n = p.n_trials
@@ -307,31 +364,97 @@ def image(self, d: int, kind: str, q: dict) -> np.ndarray:
raise ValueError(f"unknown image kind {kind!r}")
def coverage(self, d: int) -> np.ndarray:
- """How many of the session image's trials imaged each pixel of
- zero-based path ``d``: uint8 per imaged pixel, 255 = every good
+ """Return how many of the session image's trials imaged each pixel.
+
+ The pixels are those of
+ zero-based path d: uint8 per imaged pixel, 255 = every good
trial. SILo seeds sources only where every valid trial was
- imaged."""
+ imaged.
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+
+ Returns
+ -------
+ np.ndarray
+ uint8 per imaged pixel, the share of the trials that imaged it (255 = every
+ good trial).
+
+ Raises
+ ------
+ ValueError
+ If the path has no readable alignment file.
+ """ # noqa: DOC502
p = self._available_path(d)
sel = p.good if p.good.any() else p.present
frac = np.isfinite(p.vals[sel]).all(2).mean(0)
return np.floor(frac * 255).astype(np.uint8)
def pixels(self, d: int) -> np.ndarray:
- """Flat canvas indices (row-major) of zero-based path ``d``'s
- imaged pixels, the pixels :meth:`image` gives values for."""
+ """Return flat canvas indices (row-major) of zero-based path d's imaged pixels.
+
+ These are the pixels :meth:`image` gives values for.
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+
+ Returns
+ -------
+ np.ndarray
+ uint32 canvas indices.
+
+ Raises
+ ------
+ ValueError
+ If the path has no readable alignment file.
+ """ # noqa: DOC502
return self._available_path(d).idx.astype(np.uint32)
- def _available_path(self, d):
- """Return the requested path or explain why it cannot be viewed."""
+ def _available_path(self, d: int) -> PathData:
+ """Return the requested path or explain why it cannot be viewed.
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+
+ Returns
+ -------
+ PathData
+ The path's data.
+
+ Raises
+ ------
+ ValueError
+ If the path has no readable alignment file.
+ """
p = self.paths[d]
if p is None:
raise ValueError(f"path {d + 1}: no readable alignment file")
return p
def soma(self, d: int) -> dict:
- """Each trial's brightness inside the path's soma ROIs, relative
- to its median over good trials: ``{"ch1": [...], "ch2": [...]}``
- (empty without a soma)."""
+ """Return each trial's brightness inside the path's soma ROIs.
+
+ The brightness is relative
+ to its median over good trials: {"ch1": [...], "ch2": [...]}
+ (empty without a soma).
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+
+ Returns
+ -------
+ dict
+ {"ch1": [...], "ch2": [...]} per channel and trial, or empty without
+ a soma (or for a path without a readable alignment file).
+ """
p = self.paths[d]
if p is None:
return {}
@@ -348,7 +471,7 @@ def soma(self, d: int) -> dict:
v = v / np.where(ref > 0, ref, np.nan)
return {f"ch{c + 1}": _round(v[:, c]) for c in range(v.shape[1])}
- def set_state(self, obj) -> dict:
+ def set_state(self, obj: dict) -> dict:
"""Take the page's state, write the file and answer what changed.
Parameters
@@ -362,9 +485,7 @@ def set_state(self, obj) -> dict:
The cleaned state, its revision, save time and soma brightness.
"""
s = self.session
- state = clean_state(
- obj, s.n_paths, reserved_labels=self.reserved_labels
- )
+ state = clean_state(obj, s.n_paths, reserved_labels=self.reserved_labels)
for d, p in enumerate(self.paths):
if p is None:
state["paths"][d] = {"rois": []}
@@ -382,14 +503,30 @@ def set_state(self, obj) -> dict:
}
def traces(self, d: int, t: int) -> dict:
- """Trial ``t``'s motion and online offsets on path ``d`` (both
- zero-based), rounded."""
+ """Return trial t's motion and online offsets on path d, rounded.
+
+ Both d and t are zero-based.
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+ t : int
+ Zero-based trial.
+
+ Returns
+ -------
+ dict
+ The session's traces of the trial, arrays rounded to 3 decimals as lists.
+
+ Raises
+ ------
+ ValueError
+ If the path has no readable alignment file.
+ """ # noqa: DOC502
self._available_path(d)
out = self.session.trial_traces(d, t)
- return {
- k: (_round(v, 3) if isinstance(v, np.ndarray) else v)
- for k, v in out.items()
- }
+ return {k: (_round(v, 3) if isinstance(v, np.ndarray) else v) for k, v in out.items()}
class Hub:
@@ -407,25 +544,44 @@ class Hub:
"""
def __init__(
- self, store=None, root=None, max_shift=15, workers=8, cache=True
- ):
+ self,
+ store: AnnotatorStore | None = None,
+ root: str | Path | None = None,
+ max_shift: int = 15,
+ workers: int = 8,
+ cache: bool = True,
+ ) -> None:
"""Keep the session and the settings for the next ones."""
- self.store: Optional[AnnotatorStore] = store
+ self.store: AnnotatorStore | None = store
self.root = Path(root).expanduser() if root else None
self.max_shift, self.workers, self.cache = max_shift, workers, cache
self._lock = threading.RLock()
self.session_id = uuid4().hex
def start_dir(self) -> str:
- """The folder the Open dialog shows first."""
+ """Return the folder the Open dialog shows first.
+
+ Returns
+ -------
+ str
+ The open session's output folder's parent, else the root or the working
+ directory.
+ """
store = self.store
if store is not None:
return str(store.session.table_path.parent.parent)
return str((self.root or Path.cwd()).resolve())
def meta(self) -> dict:
- """The open session's :meth:`AnnotatorStore.meta`, or
- ``{"empty": True}``; with the dialog's start folder."""
+ """Return the open session's :meth:`AnnotatorStore.meta`, or {"empty": True}.
+
+ The dialog's start folder is added.
+
+ Returns
+ -------
+ dict
+ The metadata, with browse (the dialog's start folder) and session_id.
+ """
with self._lock:
store = self.store
out = {"empty": True} if store is None else store.meta()
@@ -434,7 +590,12 @@ def meta(self) -> dict:
return out
def need(self) -> AnnotatorStore:
- """The open session.
+ """Return the open session.
+
+ Returns
+ -------
+ AnnotatorStore
+ The open session.
Raises
------
@@ -446,14 +607,21 @@ def need(self) -> AnnotatorStore:
raise ValueError("no session is open")
return store
- def open(self, table) -> dict:
- """Open another session (the one before is dropped; everything it
- changed is already in its file) and answer its meta.
+ def open(self, table: str | Path | None) -> dict:
+ """Open another session and answer its meta.
+
+ The one before is dropped; everything it
+ changed is already in its file.
Parameters
----------
table : str or Path
- ``trial_table.h5`` or its folder.
+ trial_table.h5 or its folder.
+
+ Returns
+ -------
+ dict
+ The new session's :meth:`meta`.
Raises
------
@@ -486,7 +654,13 @@ def open(self, table) -> dict:
return self.meta()
def close(self) -> dict:
- """Drop the open session (its file is up to date)."""
+ """Drop the open session (its file is up to date).
+
+ Returns
+ -------
+ dict
+ The empty hub's :meth:`meta`.
+ """
with self._lock:
self.store = None
self.session_id = uuid4().hex
@@ -494,19 +668,28 @@ def close(self) -> dict:
class _Handler(_BaseHandler):
- """Answers the annotator page (see the module docstring). Requests are
- checked as ``giant spine view``'s: a trusted ``Host`` only, and writes
- only as JSON from this server's own page."""
+ """Answer the annotator page (see the module docstring).
+
+ Requests are
+ checked as giant spine view's: a trusted Host only, and writes
+ only as JSON from this server's own page.
+ """
hub: Hub
- def do_GET(self):
+ def do_GET(self) -> None:
"""Route a GET request."""
u = urlparse(self.path)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
- def go():
- """Answer it."""
+ def go() -> None:
+ """Answer it.
+
+ Raises
+ ------
+ LookupError
+ If the path is not one of the page's.
+ """
if self._untrusted_host():
self._json({"error": "untrusted Host"}, 403)
return
@@ -522,14 +705,10 @@ def go():
)
)
elif u.path == "/api/image":
- img = self.hub.need().image(
- int(q["path"]) - 1, q.get("kind", "session"), q
- )
+ img = self.hub.need().image(int(q["path"]) - 1, q.get("kind", "session"), q)
body = np.ascontiguousarray(img, np.float32).tobytes()
shape = ",".join(str(n) for n in img.shape)
- self._send(
- 200, body, "application/octet-stream", {"X-Shape": shape}
- )
+ self._send(200, body, "application/octet-stream", {"X-Shape": shape})
elif u.path == "/api/coverage":
cov = self.hub.need().coverage(int(q["path"]) - 1)
self._send(200, cov.tobytes(), "application/octet-stream")
@@ -537,22 +716,24 @@ def go():
idx = self.hub.need().pixels(int(q["path"]) - 1)
self._send(200, idx.tobytes(), "application/octet-stream")
elif u.path == "/api/traces":
- self._json(
- self.hub.need().traces(
- int(q["path"]) - 1, int(q["trial"]) - 1
- )
- )
+ self._json(self.hub.need().traces(int(q["path"]) - 1, int(q["trial"]) - 1))
else:
raise LookupError(u.path)
self._guard(go)
- def do_POST(self):
+ def do_POST(self) -> None:
"""Save the page's state, or open or close a session."""
u = urlparse(self.path)
- def go():
- """Answer it."""
+ def go() -> None:
+ """Answer it.
+
+ Raises
+ ------
+ LookupError
+ If the path is not one of the page's POST paths.
+ """
if self._untrusted_host():
self._json({"error": "untrusted Host"}, 403)
return
@@ -571,9 +752,7 @@ def go():
code = 200
if body.get("session_id") != self.hub.session_id:
code = 409
- result = {
- "error": "The session changed. Reload this page."
- }
+ result = {"error": "The session changed. Reload this page."}
elif u.path == "/api/open":
result = self.hub.open(body.get("table"))
elif u.path == "/api/close":
@@ -583,8 +762,7 @@ def go():
if body.get("state_revision") != store.state_revision:
code = 409
result = {
- "error": "Another tab changed this session. "
- "Reload this page.",
+ "error": "Another tab changed this session. Reload this page.",
"state_revision": store.state_revision,
}
else:
@@ -594,9 +772,15 @@ def go():
self._guard(go)
-def make_server(hub, host="127.0.0.1", port=DEFAULT_PORT):
- """An HTTP server (not started), trusting the loopback names and
- ``host`` (every name when bound to all interfaces).
+def make_server(
+ hub: Hub | AnnotatorStore | None,
+ host: str = "127.0.0.1",
+ port: int = DEFAULT_PORT,
+) -> ThreadingHTTPServer:
+ """Build an HTTP server (not started).
+
+ It trusts the loopback names and
+ host (every name when bound to all interfaces).
Parameters
----------
@@ -604,6 +788,11 @@ def make_server(hub, host="127.0.0.1", port=DEFAULT_PORT):
The sessions to serve: a hub, one session, or none yet.
host : str
port : int
+
+ Returns
+ -------
+ ThreadingHTTPServer
+ The server, bound to host and port.
"""
if not isinstance(hub, Hub):
hub = Hub(hub)
@@ -614,7 +803,7 @@ def make_server(hub, host="127.0.0.1", port=DEFAULT_PORT):
return srv
-def add_arguments(p) -> None:
+def add_arguments(p: argparse.ArgumentParser) -> None:
"""``giant annotate-raster``'s options."""
p.add_argument(
"trial_table",
@@ -656,20 +845,34 @@ def add_arguments(p) -> None:
p.add_argument(
"--no-cache",
action="store_true",
- help="do not keep the aligned mean images in "
- "/annotations/cache",
+ help="do not keep the aligned mean images in /annotations/cache",
)
p.add_argument("--label", default="", help="session label on the page")
p.add_argument("--host", default="127.0.0.1")
p.add_argument("--port", type=int, default=DEFAULT_PORT)
- p.add_argument(
- "--no-browser", action="store_true", help="do not open a browser tab"
- )
+ p.add_argument("--no-browser", action="store_true", help="do not open a browser tab")
+
+
+def make_hub(args: argparse.Namespace) -> Hub:
+ """Build the hub for parsed giant annotate-raster arguments.
+ The named session is open, or the hub is empty.
+
+ Parameters
+ ----------
+ args : argparse.Namespace
+ The parsed arguments (see :func:`add_arguments`).
-def make_hub(args) -> Hub:
- """The hub for parsed ``giant annotate-raster`` arguments: with the
- named session open, or empty."""
+ Returns
+ -------
+ Hub
+ The hub with the named session open, or empty without a trial table.
+
+ Raises
+ ------
+ ValueError
+ If --annotations or --moco-dir is given without a trial table.
+ """
store = None
if not args.trial_table and (args.annotations or args.moco_dir):
raise ValueError("--annotations and --moco-dir require a trial table")
@@ -687,13 +890,22 @@ def make_hub(args) -> Hub:
flush=True,
)
store = AnnotatorStore(session, args.annotations, args.label)
- return Hub(
- store, args.root, args.max_shift, args.workers, not args.no_cache
- )
+ return Hub(store, args.root, args.max_shift, args.workers, not args.no_cache)
+
+
+def serve(args: argparse.Namespace) -> int:
+ """Run giant annotate-raster until interrupted.
+ Parameters
+ ----------
+ args : argparse.Namespace
+ The parsed arguments (see :func:`add_arguments`).
-def serve(args) -> int:
- """Run ``giant annotate-raster`` until interrupted."""
+ Returns
+ -------
+ int
+ The exit code, 0.
+ """
hub = make_hub(args)
server = make_server(hub, args.host, args.port)
url = f"http://{_bracket(args.host)}:{server.server_address[1]}/"
diff --git a/src/giant_python/annotator/session.py b/src/giant_python/annotator/session.py
index e0a6a95e..74ecf75a 100644
--- a/src/giant_python/annotator/session.py
+++ b/src/giant_python/annotator/session.py
@@ -1,13 +1,14 @@
-"""A registered raster session as the annotator sees it: every trial's mean
-image on one canvas, and per-trial statistics.
+"""A registered raster session as the annotator sees it.
+
+Every trial's mean image on one canvas, and per-trial statistics.
Only the trial table and the alignment files (``*_ALIGNMENTDATA.h5``) are
-read: each trial's per-channel mean image, its motion, ``recNegErr``, the
+read: each trial's per-channel mean image, its motion, recNegErr, the
online offsets and the frame origin. No movie and no raw data are opened,
so a session of hundreds of trials loads in seconds to a minute.
**The canvas.** Each trial's mean image is placed by its frame origin
-(``slap2/cropRow``, ``slap2/cropCol``; they differ between trials when
+(slap2/cropRow, slap2/cropCol; they differ between trials when
ROIs were deleted between acquisitions), then moved by a whole-pixel shift
onto a session template (median of up to 20 evenly spaced trials, refined
once), as SILo's rigid across-trial alignment does with its own images.
@@ -15,15 +16,15 @@
margin. This alignment is for viewing, statistics and the session image;
SILo aligns the trials again itself.
-**The anchor trial.** ``annotations.h5`` stores ROIs in the frame of one
-registered trial (``Path/fn``), and SILo moves them into its consensus
+**The anchor trial.** annotations.h5 stores ROIs in the frame of one
+registered trial (Path/fn), and SILo moves them into its consensus
frame through that trial's map. The shifts are therefore taken relative to
an anchor trial (the trial an existing file names, else the trial that
matches the template best), so that a canvas pixel and the anchor's pixel
differ by a constant offset (:attr:`PathData.frame_offset`).
**Storage.** Images are kept at the imaged pixels only:
-``vals[trial, pixel, channel]`` with ``idx`` the pixels' flat canvas
+vals[trial, pixel, channel] with idx the pixels' flat canvas
indices, about a tenth of the dense size for sparse raster ROIs.
"""
@@ -32,13 +33,14 @@
import json
import os
import warnings
+from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path, PurePath
-from typing import Optional, Sequence
import h5py
import numpy as np
+import numpy.typing as npt
from scipy import fft as sfft
from scipy import ndimage
@@ -81,7 +83,7 @@ class _Raw:
failed: bool
-def read_alignment(path) -> _Raw:
+def read_alignment(path: str | Path) -> _Raw:
"""Read the annotator's inputs from one ``*_ALIGNMENTDATA.h5``.
Parameters
@@ -92,7 +94,7 @@ def read_alignment(path) -> _Raw:
Returns
-------
_Raw
- The mean image as ``(rows, cols, channels)`` and the traces.
+ The mean image as (rows, cols, channels) and the traces.
"""
with h5py.File(path, "r") as f:
mean = np.asarray(f["meanIM"][()], np.float32)
@@ -101,20 +103,26 @@ def read_alignment(path) -> _Raw:
mean = mean[:, :, None]
mean = mean.transpose(1, 0, 2)
- def vec(name):
- """A dataset as a float vector (empty if absent)."""
+ def vec(name: str) -> np.ndarray:
+ """Read a dataset as a float vector (empty if absent).
+
+ Parameters
+ ----------
+ name : str
+ Dataset name in the file.
+
+ Returns
+ -------
+ np.ndarray
+ The dataset as a flat float64 vector; empty if absent.
+ """
if name not in f:
return np.zeros(0)
return np.asarray(f[name][()], np.float64).ravel()
- online = [
- vec(f"slap2/onlineMotion{k}")
- for k in ("Xshift", "Yshift", "Zshift")
- ]
+ online = [vec(f"slap2/onlineMotion{k}") for k in ("Xshift", "Yshift", "Zshift")]
n = max(len(o) for o in online)
- online = np.stack(
- [o if len(o) == n else np.full(n, np.nan) for o in online]
- )
+ online = np.stack([o if len(o) == n else np.full(n, np.nan) for o in online])
crop = (vec("slap2/cropRow"), vec("slap2/cropCol"))
hz = vec("alignHz")
failed = vec("registrationFailed")
@@ -131,7 +139,22 @@ def vec(name):
def shift_image(img: np.ndarray, dr: int, dc: int) -> np.ndarray:
- """``out[r, c] = img[r + dr, c + dc]``, NaN where that is outside."""
+ """Shift an image so that out[r, c] = img[r + dr, c + dc], NaN where that is outside.
+
+ Parameters
+ ----------
+ img : np.ndarray
+ The image, (rows, cols, ...).
+ dr : int
+ Row shift, px.
+ dc : int
+ Column shift, px.
+
+ Returns
+ -------
+ np.ndarray
+ The shifted image, NaN where the source is outside img.
+ """
out = np.full_like(img, np.nan)
h, w = img.shape[:2]
r0, r1 = max(0, -dr), min(h, h - dr)
@@ -142,7 +165,18 @@ def shift_image(img: np.ndarray, dr: int, dc: int) -> np.ndarray:
def _centred(img: np.ndarray) -> np.ndarray:
- """``img`` minus its mean over finite pixels, zero elsewhere."""
+ """Subtract the mean over finite pixels from an image, zero elsewhere.
+
+ Parameters
+ ----------
+ img : np.ndarray
+ The image.
+
+ Returns
+ -------
+ np.ndarray
+ img minus its mean over finite pixels, zero elsewhere (float32).
+ """
ok = np.isfinite(img)
if not ok.any():
return np.zeros(img.shape, np.float32)
@@ -160,7 +194,7 @@ class _Matcher:
Largest shift searched per axis, px.
"""
- def __init__(self, template: np.ndarray, max_shift: int):
+ def __init__(self, template: np.ndarray, max_shift: int) -> None:
"""Transform the template once."""
h, w = template.shape
self.max_shift = int(max_shift)
@@ -172,11 +206,20 @@ def __init__(self, template: np.ndarray, max_shift: int):
self.ft = np.conj(sfft.rfft2(_centred(template), self.size))
def shift(self, img: np.ndarray) -> tuple:
- """``(dr, dc)`` maximizing ``sum template[r, c] img[r+dr, c+dc]``."""
+ """Find the shift maximizing sum template[r, c] img[r+dr, c+dc].
+
+ Parameters
+ ----------
+ img : np.ndarray
+ The image to align to the template.
+
+ Returns
+ -------
+ tuple
+ (dr, dc), the row and column shift maximizing the correlation, px.
+ """
m = self.max_shift
- xc = sfft.irfft2(
- sfft.rfft2(_centred(img), self.size) * self.ft, self.size
- )
+ xc = sfft.irfft2(sfft.rfft2(_centred(img), self.size) * self.ft, self.size)
rows = np.r_[0 : m + 1, self.size[0] - m : self.size[0]]
cols = np.r_[0 : m + 1, self.size[1] - m : self.size[1]]
win = xc[np.ix_(rows, cols)]
@@ -189,7 +232,23 @@ def shift(self, img: np.ndarray) -> tuple:
def _pearson(a: np.ndarray, b: np.ndarray, min_px: int = 100) -> float:
- """Correlation of two vectors over the entries finite in both."""
+ """Compute the correlation of two vectors over the entries finite in both.
+
+ Parameters
+ ----------
+ a : np.ndarray
+ First vector.
+ b : np.ndarray
+ Second vector.
+ min_px : int
+ Fewest entries finite in both for a correlation to be computed.
+
+ Returns
+ -------
+ float
+ The Pearson correlation; NaN if fewer than min_px entries are finite in both
+ or a vector is constant.
+ """
ok = np.isfinite(a) & np.isfinite(b)
if ok.sum() < min_px:
return float("nan")
@@ -204,6 +263,16 @@ def sharpness(img: np.ndarray) -> float:
The image minus its Gaussian blur (sigma 3 px, normalized for
unimaged pixels), as a standard deviation over the mean. A trial that
is out of focus or blurred by motion scores lower than the others.
+
+ Parameters
+ ----------
+ img : np.ndarray
+ The image, NaN where not imaged.
+
+ Returns
+ -------
+ float
+ The sharpness; NaN if fewer than 100 pixels are imaged or the mean is not positive.
"""
ok = np.isfinite(img)
if ok.sum() < 100:
@@ -216,8 +285,21 @@ def sharpness(img: np.ndarray) -> float:
return float(np.nanstd(high) / mean) if mean > 0 else float("nan")
-def _nan(shape, dtype=np.float64) -> np.ndarray:
- """An array of NaN."""
+def _nan(shape: int | tuple[int, ...], dtype: npt.DTypeLike = np.float64) -> np.ndarray:
+ """Return an array of NaN.
+
+ Parameters
+ ----------
+ shape : int or tuple of int
+ Shape of the array.
+ dtype : dtype
+ Data type of the array.
+
+ Returns
+ -------
+ np.ndarray
+ An array of NaN.
+ """
return np.full(shape, np.nan, dtype)
@@ -230,28 +312,28 @@ class PathData:
path : int
One-based path number.
shape : tuple of int
- Canvas ``(rows, cols)``.
+ Canvas (rows, cols).
idx : ndarray of int64, (pixels,)
Flat canvas indices of the pixels imaged in at least one trial.
vals : ndarray of float32, (trials, pixels, channels)
- The trials' aligned mean images at ``idx``; NaN where a trial did
+ The trials' aligned mean images at idx; NaN where a trial did
not image a pixel, and for trials without an alignment file.
present, failed : ndarray of bool, (trials,)
Whether the trial has an alignment file; whether registration
- flagged it (the trial table's ``registration_failed``, else the
- file's ``registrationFailed``).
+ flagged it (the trial table's registration_failed, else the
+ file's registrationFailed).
frame_offset : ndarray of int, (trials, 2)
- ``trial pixel (row, col) = canvas pixel + frame_offset[trial]``.
+ trial pixel (row, col) = canvas pixel + frame_offset[trial].
frame_shape : ndarray of int, (trials, 2)
Each trial's registered frame size.
anchor : int
Zero-based anchor trial (see the module docstring).
stems : list of str
- The trials' registered-movie stems (``annotations.h5``'s ``fn``).
+ The trials' registered-movie stems (annotations.h5's fn).
stats : dict of ndarray, (trials,)
:data:`STAT_NAMES`.
match_thresh : float
- ``min(0.9, median - 2 SD)`` of ``match`` over unflagged trials:
+ min(0.9, median - 2 SD) of match over unflagged trials:
the rule of SILo's valid-trial test, applied to these images.
scale : ndarray, (channels,)
99.5th percentile of the session image per channel, for display.
@@ -292,8 +374,18 @@ def good(self) -> np.ndarray:
return ok & ~(match < self.match_thresh)
def to_canvas(self, values: np.ndarray) -> np.ndarray:
- """Per-pixel values ``(pixels, ...)`` as canvas images
- ``(..., rows, cols)``, NaN at the other pixels."""
+ """Put per-pixel values (pixels, ...) on canvas images (..., rows, cols).
+
+ Parameters
+ ----------
+ values : np.ndarray
+ Per-pixel values, (pixels, ...).
+
+ Returns
+ -------
+ np.ndarray
+ Canvas images (..., rows, cols), NaN at the other pixels.
+ """
tail = values.shape[1:]
out = _nan((self.shape[0] * self.shape[1],) + tail, np.float32)
out[self.idx] = values
@@ -301,11 +393,22 @@ def to_canvas(self, values: np.ndarray) -> np.ndarray:
return np.moveaxis(out, (0, 1), (-2, -1)) if tail else out
def trial_image(self, trial: int) -> np.ndarray:
- """One trial's mean image, ``(channels, rows, cols)``."""
+ """Return one trial's mean image.
+
+ Parameters
+ ----------
+ trial : int
+ Zero-based trial.
+
+ Returns
+ -------
+ np.ndarray
+ The trial's mean image, (channels, rows, cols).
+ """
return self.to_canvas(self.vals[trial])
- def mean_image(self, trials: Optional[np.ndarray] = None) -> np.ndarray:
- """The mean over trials, weighted by their frames.
+ def mean_image(self, trials: np.ndarray | None = None) -> np.ndarray:
+ """Compute the mean over trials, weighted by their frames.
Parameters
----------
@@ -320,10 +423,20 @@ def mean_image(self, trials: Optional[np.ndarray] = None) -> np.ndarray:
"""
return self.to_canvas(self.mean_values(trials))
- def mean_values(self, trials: Optional[np.ndarray] = None) -> np.ndarray:
- """:meth:`mean_image` at the imaged pixels, ``(pixels, channels)``.
+ def mean_values(self, trials: np.ndarray | None = None) -> np.ndarray:
+ """Return :meth:`mean_image` at the imaged pixels, (pixels, channels).
An explicit selection with no present trials yields only NaNs.
+
+ Parameters
+ ----------
+ trials : np.ndarray or None
+ The trials to average, as in :meth:`mean_image`.
+
+ Returns
+ -------
+ np.ndarray
+ The weighted mean at the imaged pixels, (pixels, channels) float32.
"""
sel = self.good if trials is None else np.asarray(trials, bool)
sel = sel & self.present
@@ -341,18 +454,46 @@ def mean_values(self, trials: Optional[np.ndarray] = None) -> np.ndarray:
return (num.sum(0) / den).astype(np.float32)
def canvas_to_trial(self, xy: np.ndarray, trial: int) -> np.ndarray:
- """Canvas points ``[x, y]`` (column, row; pixel ``(r, c)`` covers
- ``[c, c+1) x [r, r+1)``) in a trial's frame, same convention."""
+ """Convert canvas points [x, y] to a trial's frame, same convention.
+
+ Canvas points are [x, y] (column, row; pixel (r, c) covers
+ [c, c+1) x [r, r+1)).
+
+ Parameters
+ ----------
+ xy : np.ndarray
+ Canvas points, (n, 2) or (2,).
+ trial : int
+ Zero-based trial.
+
+ Returns
+ -------
+ np.ndarray
+ The points in the trial's frame, (n, 2).
+ """
off = self.frame_offset[trial]
return np.asarray(xy, np.float64).reshape(-1, 2) + [off[1], off[0]]
def trial_to_canvas(self, xy: np.ndarray, trial: int) -> np.ndarray:
- """The inverse of :meth:`canvas_to_trial`."""
+ """Return the inverse of :meth:`canvas_to_trial`.
+
+ Parameters
+ ----------
+ xy : np.ndarray
+ Points in the trial's frame, (n, 2) or (2,).
+ trial : int
+ Zero-based trial.
+
+ Returns
+ -------
+ np.ndarray
+ The points on the canvas, (n, 2).
+ """
off = self.frame_offset[trial]
return np.asarray(xy, np.float64).reshape(-1, 2) - [off[1], off[0]]
def mask_values(self, mask: np.ndarray) -> np.ndarray:
- """Each trial's mean over a canvas mask, ``(trials, channels)``.
+ """Each trial's mean over a canvas mask, (trials, channels).
Parameters
----------
@@ -373,12 +514,36 @@ def mask_values(self, mask: np.ndarray) -> np.ndarray:
def _stem(name: str) -> str:
- """A registered movie's file stem."""
+ """Return a registered movie's file stem.
+
+ Parameters
+ ----------
+ name : str
+ The movie's file name or path.
+
+ Returns
+ -------
+ str
+ The file stem; empty if name is empty.
+ """
return PurePath(str(name).replace("\\", "/")).stem if name else ""
-def _signature(files: Sequence[Optional[Path]], extra) -> str:
- """Identity of a path's inputs: names, sizes, times and settings."""
+def _signature(files: Sequence[Path | None], extra: object) -> str:
+ """Return the identity of a path's inputs: names, sizes, times and settings.
+
+ Parameters
+ ----------
+ files : sequence of (Path or None)
+ The trials' alignment files.
+ extra : object
+ Further settings, JSON-serializable.
+
+ Returns
+ -------
+ str
+ A JSON string identifying the inputs.
+ """
rec = []
for p in files:
if p is None or not p.exists():
@@ -390,7 +555,20 @@ def _signature(files: Sequence[Optional[Path]], extra) -> str:
def _samples(ok: np.ndarray, n: int = 20) -> np.ndarray:
- """Up to ``n`` evenly spaced trials among those ``ok``."""
+ """Pick up to n evenly spaced trials among those ok.
+
+ Parameters
+ ----------
+ ok : np.ndarray
+ Boolean mask of the eligible trials.
+ n : int
+ Most trials to pick.
+
+ Returns
+ -------
+ np.ndarray
+ Indices of the picked trials.
+ """
t = np.flatnonzero(ok)
if t.size == 0:
return t
@@ -398,15 +576,15 @@ def _samples(ok: np.ndarray, n: int = 20) -> np.ndarray:
return t[np.unique(pick)]
-def build_path( # noqa: C901
+def build_path(
path: int,
- files: Sequence[Optional[Path]],
+ files: Sequence[Path | None],
stems: Sequence[str],
- table_failed: Optional[np.ndarray] = None,
+ table_failed: np.ndarray | None = None,
anchor_stem: str = "",
max_shift: int = 15,
workers: int = 8,
-) -> Optional[PathData]:
+) -> PathData | None:
"""Read one path's alignment files and put its trials on a canvas.
Parameters
@@ -418,11 +596,11 @@ def build_path( # noqa: C901
stems : sequence of str
The trials' registered-movie stems.
table_failed : ndarray of bool, optional
- The trial table's ``registration_failed`` for this path; the
+ The trial table's registration_failed for this path; the
files' own flags if None.
anchor_stem : str
Stem of the trial to anchor the canvas to (an existing
- annotation's ``fn``); the best-matching trial if empty or unknown.
+ annotation's fn); the best-matching trial if empty or unknown.
max_shift : int
Largest across-trial shift searched, px.
workers : int
@@ -435,8 +613,19 @@ def build_path( # noqa: C901
"""
n = len(files)
- def load(p):
- """One file, or None."""
+ def load(p: str | Path | None) -> _Raw | None:
+ """Read one file, or return None.
+
+ Parameters
+ ----------
+ p : str or Path or None
+ The alignment file.
+
+ Returns
+ -------
+ _Raw or None
+ The file's contents; None if p is None, missing or not readable.
+ """
if p is None or not Path(p).exists():
return None
try:
@@ -454,18 +643,27 @@ def load(p):
if table_failed is not None and len(table_failed) == n:
failed = np.asarray(table_failed, bool) & present | failed
n_ch = max(r.mean.shape[2] for r in raw if r is not None)
- crop = np.array(
- [r.crop if r is not None else (0, 0) for r in raw], int
- )
+ crop = np.array([r.crop if r is not None else (0, 0) for r in raw], int)
place = crop - crop[present].min(0)
place[~present] = 0
- fshape = np.array(
- [r.mean.shape[:2] if r is not None else (0, 0) for r in raw], int
- )
+ fshape = np.array([r.mean.shape[:2] if r is not None else (0, 0) for r in raw], int)
h0, w0 = (place + fshape)[present].max(0)
- def summed(t, shift=(0, 0)):
- """Trial ``t``'s channel sum on the uncropped canvas."""
+ def summed(t: int, shift: tuple[int, int] = (0, 0)) -> np.ndarray:
+ """Return trial t's channel sum on the uncropped canvas.
+
+ Parameters
+ ----------
+ t : int
+ Zero-based trial.
+ shift : tuple of int
+ Whole-pixel (dr, dc) shift applied to the image.
+
+ Returns
+ -------
+ np.ndarray
+ The channel sum on the uncropped canvas, (rows, cols).
+ """
img = _nan((h0, w0), np.float32)
r, c = place[t]
s = raw[t].mean.sum(2) # NaN where any channel is, as SILo
@@ -484,8 +682,20 @@ def summed(t, shift=(0, 0)):
count += np.isfinite(summed(t))
common = count >= CORE_FRACTION * ok.sum()
- def masked(img):
- """``img`` on the common pixels."""
+ def masked(img: np.ndarray) -> np.ndarray:
+ """Restrict an image to the common pixels.
+
+ Parameters
+ ----------
+ img : np.ndarray
+ The image.
+
+ Returns
+ -------
+ np.ndarray
+ img on the common pixels (NaN elsewhere); img if there are no
+ common pixels to restrict to.
+ """
return img if common is None else np.where(common, img, np.nan)
samples = _samples(ok)
@@ -502,9 +712,22 @@ def masked(img):
shifts[present] = np.array(list(got), int).reshape(-1, 2)
del stack
- def template_vec(sh):
- """Template and trials' sums at the common pixels, for shifts
- ``sh`` (dense, for the samples and one trial at a time)."""
+ def template_vec(sh: np.ndarray) -> np.ndarray:
+ """Compute the template and trials' sums at the common pixels.
+
+ For shifts sh (dense, for the samples and one trial at a time).
+
+ Parameters
+ ----------
+ sh : np.ndarray
+ Whole-pixel shifts, (trials, 2).
+
+ Returns
+ -------
+ np.ndarray
+ The median over the samples of the shifted channel sums at the common
+ pixels.
+ """
stack = np.stack([masked(summed(t, sh[t])) for t in samples])
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
@@ -513,9 +736,7 @@ def template_vec(sh):
tmpl = template_vec(shifts)
corr = _nan(n)
got = pool.map(
- lambda t: _pearson(
- tmpl.ravel(), masked(summed(t, shifts[t])).ravel()
- ),
+ lambda t: _pearson(tmpl.ravel(), masked(summed(t, shifts[t])).ravel()),
np.flatnonzero(present),
)
corr[present] = list(got)
@@ -556,9 +777,7 @@ def template_vec(sh):
for t in np.flatnonzero(present):
m = raw[t].mean
rr, cc = pr + offset[t, 0], pc + offset[t, 1]
- inside = (
- (rr >= 0) & (rr < m.shape[0]) & (cc >= 0) & (cc < m.shape[1])
- )
+ inside = (rr >= 0) & (rr < m.shape[0]) & (cc >= 0) & (cc < m.shape[1])
vals[t, inside, : m.shape[2]] = m[rr[inside], cc[inside]]
data = PathData(
@@ -575,18 +794,20 @@ def template_vec(sh):
stats={},
match_thresh=0.9,
scale=np.ones(n_ch),
- align_hz=float(
- np.median([r.align_hz for r in raw if r is not None])
- ),
+ align_hz=float(np.median([r.align_hz for r in raw if r is not None])),
)
_statistics(data, raw, ok, moved, pool)
return data
-def _statistics( # noqa: C901
- data: PathData, raw, ok, moved: bool, pool
+def _statistics(
+ data: PathData,
+ raw: list[_Raw | None],
+ ok: np.ndarray,
+ moved: bool,
+ pool: ThreadPoolExecutor,
) -> None:
- """Fill ``data.stats``, ``match_thresh``, ``core`` and ``scale``."""
+ """Fill data.stats, match_thresh, core and scale."""
n, present = data.n_trials, data.present
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
@@ -597,12 +818,9 @@ def _statistics( # noqa: C901
core = imaged.any(0)
tmpl = np.nanmedian(sums[_samples(ok)], 0)
use = core if moved else np.ones(core.shape, bool)
- match = np.array(
- [
- _pearson(tmpl[use], sums[t, use]) if present[t] else np.nan
- for t in range(n)
- ]
- )
+ match = np.array([
+ _pearson(tmpl[use], sums[t, use]) if present[t] else np.nan for t in range(n)
+ ])
known = match[ok & np.isfinite(match)]
thresh = 0.9
if known.size:
@@ -612,8 +830,19 @@ def _statistics( # noqa: C901
ref = np.nanmedian(bright[ok], axis=0)
bright = bright / np.where(ref > 0, ref, np.nan)
- def sharp(t):
- """Sharpness of trial ``t``'s channel sum."""
+ def sharp(t: int) -> float:
+ """Return the sharpness of trial t's channel sum.
+
+ Parameters
+ ----------
+ t : int
+ Zero-based trial.
+
+ Returns
+ -------
+ float
+ The sharpness of the trial's channel sum on the canvas.
+ """
return sharpness(data.to_canvas(sums[t]))
sh = _nan(n)
@@ -624,22 +853,16 @@ def sharp(t):
st["bright_ch1"] = bright[:, 0]
st["bright_ch2"] = bright[:, 1] if bright.shape[1] > 1 else _nan(n)
st["match"], st["sharp"] = match, sh
- st["coverage"] = np.where(
- present, (imaged & core).sum(1) / max(1, core.sum()), np.nan
- )
+ st["coverage"] = np.where(present, (imaged & core).sum(1) / max(1, core.sum()), np.nan)
for t in np.flatnonzero(present):
r = raw[t]
if r.motion_r.size:
- st["motion_sd"][t] = max(
- np.nanstd(r.motion_r), np.nanstd(r.motion_c)
- )
+ st["motion_sd"][t] = max(np.nanstd(r.motion_r), np.nanstd(r.motion_c))
st["n_frames"][t] = r.motion_r.size
if r.rec_neg_err.size >= 10:
try:
st["discard"][t] = float(
- discard_frames(
- r.rec_neg_err, r.align_hz, MOTION_THRESH, 0.0
- ).mean()
+ discard_frames(r.rec_neg_err, r.align_hz, MOTION_THRESH, 0.0).mean()
)
except (ValueError, IndexError, FloatingPointError):
pass
@@ -661,8 +884,8 @@ def sharp(t):
data.scale = np.array(scale)
-def save_cache(data: PathData, path, signature: str) -> None:
- """Write ``data`` to ``path`` (``.npz``), replacing it at once."""
+def save_cache(data: PathData, path: str | Path, signature: str) -> None:
+ """Write data to path (.npz), replacing it at once."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + f".tmp{os.getpid()}")
@@ -671,16 +894,14 @@ def save_cache(data: PathData, path, signature: str) -> None:
fh,
signature=np.array(signature),
meta=np.array(
- json.dumps(
- {
- "path": data.path,
- "shape": list(data.shape),
- "anchor": data.anchor,
- "stems": data.stems,
- "match_thresh": data.match_thresh,
- "align_hz": data.align_hz,
- }
- )
+ json.dumps({
+ "path": data.path,
+ "shape": list(data.shape),
+ "anchor": data.anchor,
+ "stems": data.stems,
+ "match_thresh": data.match_thresh,
+ "align_hz": data.align_hz,
+ })
),
idx=data.idx,
vals=data.vals,
@@ -695,9 +916,22 @@ def save_cache(data: PathData, path, signature: str) -> None:
os.replace(tmp, path)
-def load_cache(path, signature: str) -> Optional[PathData]:
- """The cached :class:`PathData` at ``path`` if its inputs are the same
- (``signature``), else None."""
+def load_cache(path: str | Path, signature: str) -> PathData | None:
+ """Return the cached :class:`PathData` at path if its inputs are the same.
+
+ Parameters
+ ----------
+ path : str or Path
+ The cache file (.npz).
+ signature : str
+ The inputs' signature; the cache is used only if it matches.
+
+ Returns
+ -------
+ PathData or None
+ The cached data; None if the file is missing, not usable or its signature
+ differs (signature).
+ """
path = Path(path)
if not path.exists():
return None
@@ -759,32 +993,32 @@ class AnnotatorSession:
start_min: np.ndarray
max_shift: int = 15
workers: int = 8
- cache_dir: Optional[Path] = None
+ cache_dir: Path | None = None
_paths: dict = field(default_factory=dict, repr=False)
@classmethod
def open(
cls,
- table,
- moco_dir=None,
+ table: str | Path,
+ moco_dir: str | Path | None = None,
max_shift: int = 15,
workers: int = 8,
cache: bool = True,
- ) -> "AnnotatorSession":
+ ) -> AnnotatorSession:
"""Read a registered session's trial table.
Parameters
----------
table : str or Path
- ``trial_table.h5`` or its folder.
+ trial_table.h5 or its folder.
moco_dir : str or Path, optional
- Registration folder (default ``/motion_correction``).
+ Registration folder (default /motion_correction).
max_shift : int
Largest across-trial shift searched, px.
workers : int
Threads reading files.
cache : bool
- Keep each path's data in ``/annotations/cache``.
+ Keep each path's data in /annotations/cache.
Returns
-------
@@ -806,16 +1040,12 @@ def open(
shape = filename.shape
reg = _read(f, "motion_correction/fn_reg_ds", row_major)
ada = _read(f, "motion_correction/fn_adata", row_major)
- failed = _read(
- f, "motion_correction/registration_failed", row_major
- )
+ failed = _read(f, "motion_correction/registration_failed", row_major)
savedr = _read(f, "savedr", row_major)
start = _read(f, "slap2_info/trial_start_time_inferred", row_major)
if reg is None or ada is None:
raise ValueError(f"{table} has no registration (giant register)")
- savedr = Path(
- str(savedr.ravel()[0]) if savedr is not None else table.parent
- )
+ savedr = Path(str(savedr.ravel()[0]) if savedr is not None else table.parent)
failed = (
np.zeros(shape, bool)
if failed is None or np.size(failed) != shape[0] * shape[1]
@@ -850,18 +1080,55 @@ def n_trials(self) -> int:
return int(self.filename.shape[1])
def stem(self, d: int, t: int) -> str:
- """Registered-movie stem of zero-based path ``d``, trial ``t``."""
+ """Return the registered-movie stem of zero-based path d, trial t.
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+ t : int
+ Zero-based trial.
+
+ Returns
+ -------
+ str
+ The movie's file stem; empty if none is named.
+ """
return _stem(str(self.fn_reg_ds[d, t] or ""))
- def alignment(self, d: int, t: int) -> Optional[Path]:
- """Alignment file of zero-based path ``d``, trial ``t``, if named."""
+ def alignment(self, d: int, t: int) -> Path | None:
+ """Return the alignment file of zero-based path d, trial t, if named.
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+ t : int
+ Zero-based trial.
+
+ Returns
+ -------
+ Path or None
+ The alignment file in the registration folder; None if none is named.
+ """
name = str(self.fn_adata[d, t] or "")
return (self.moco_dir / name) if name else None
def chunks(self, d: int) -> list:
- """Runs of consecutive trials read from the same raw file
- (acquisitions of a chunked session): ``(first, last)`` zero-based,
- inclusive."""
+ """Return runs of consecutive trials read from the same raw file.
+
+ These are the acquisitions of a chunked session.
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+
+ Returns
+ -------
+ list
+ (first, last) zero-based trial pairs, inclusive.
+ """
names = [str(x or "") for x in self.filename[d]]
out, start = [], 0
for t in range(1, len(names) + 1):
@@ -870,9 +1137,8 @@ def chunks(self, d: int) -> list:
start = t
return out
- def path(self, d: int, anchor_stem: str = "") -> Optional[PathData]:
- """Zero-based path ``d``'s data, built (or read from the cache) on
- first use.
+ def path(self, d: int, anchor_stem: str = "") -> PathData | None:
+ """Return zero-based path d's data, built (or read from the cache) on first use.
Parameters
----------
@@ -919,9 +1185,22 @@ def path(self, d: int, anchor_stem: str = "") -> Optional[PathData]:
return data
def trial_traces(self, d: int, t: int) -> dict:
- """One trial's motion and online-offset traces, read from its
- alignment file: ``motion_r``, ``motion_c``, ``rec_neg_err``,
- ``online_x``, ``online_y``, ``online_z`` (lists)."""
+ """Read one trial's motion and online-offset traces from its alignment file.
+
+ Parameters
+ ----------
+ d : int
+ Zero-based path.
+ t : int
+ Zero-based trial.
+
+ Returns
+ -------
+ dict
+ motion_r, motion_c, rec_neg_err, online_x, online_y,
+ online_z (lists) and align_hz; empty if the trial has no alignment
+ file.
+ """
p = self.alignment(d, t)
if p is None or not p.exists():
return {}
diff --git a/src/giant_python/annotator/state.py b/src/giant_python/annotator/state.py
index 27a95176..ed1e44c6 100644
--- a/src/giant_python/annotator/state.py
+++ b/src/giant_python/annotator/state.py
@@ -2,26 +2,30 @@
The state is a JSON-serializable dict::
- {"version": 1,
- "paths": [{"rois": [{"kind": "soma", "label": "soma1",
- "points": [[x, y], ...]}, ...]}, ...]}
+ {
+ "version": 1,
+ "paths": [
+ {"rois": [{"kind": "soma", "label": "soma1", "points": [[x, y], ...]}, ...]},
+ ...,
+ ],
+ }
-``paths`` has one entry per imaging path, in order. A ROI is a polygon
-with ``points`` ``[x, y]`` (column, row) in image coordinates in which
-pixel ``(r, c)`` covers ``[c, c + 1) x [r, r + 1)``; in memory and on the
+paths has one entry per imaging path, in order. A ROI is a polygon
+with points [x, y] (column, row) in image coordinates in which
+pixel (r, c) covers [c, c + 1) x [r, r + 1); in memory and on the
page they are canvas coordinates
(:class:`~giant_python.annotator.session.PathData`), in the file the
-anchor trial's (:mod:`.files`). ``kind`` is
+anchor trial's (:mod:`.files`). kind is
-* ``'soma'``: SILo seeds no sources inside and extracts a trace (the label
- contains ``soma`` in any case, which is how SILo recognizes a soma);
-* ``'roi'``: SILo extracts a trace.
+* 'soma': SILo seeds no sources inside and extracts a trace (the label
+ contains soma in any case, which is how SILo recognizes a soma);
+* 'roi': SILo extracts a trace.
-An optional ``mask_id`` associates a restored polygon with its original
+An optional mask_id associates a restored polygon with its original
ROI on the same path, even if the editor renames or reorders it.
-Earlier versions also kept exclusion zones (ROIs of kind ``'exclude'``)
-and marks of bad trials (``trials``). They did not improve source finding
+Earlier versions also kept exclusion zones (ROIs of kind 'exclude')
+and marks of bad trials (trials). They did not improve source finding
and were removed; :func:`clean_state` drops them from an old state.
"""
@@ -29,9 +33,10 @@
import math
import re
-from typing import Optional
+from collections.abc import Iterable
import numpy as np
+import numpy.typing as npt
STATE_VERSION = 1
KINDS = ("soma", "roi")
@@ -43,21 +48,46 @@
def empty_state(n_paths: int) -> dict:
- """A state without annotations for ``n_paths`` paths."""
+ """Return a state without annotations for n_paths paths.
+
+ Parameters
+ ----------
+ n_paths : int
+ The number of imaging paths.
+
+ Returns
+ -------
+ dict
+ The empty state, with one ROI-less entry per path.
+ """
return {
"version": STATE_VERSION,
"paths": [{"rois": []} for _ in range(n_paths)],
}
-def _label(kind: str, label, taken: set) -> str:
- """A ROI's label, unlike every label in ``taken`` (lower case).
+def _label(kind: str, label: object, taken: set) -> str:
+ """Return a ROI's label, unlike every label in taken (lower case).
The given label is kept if it is free. A soma's label that does not say
- so gets ``soma`` in front (SILo knows a soma by its label). Without a
- label, or when a default label such as ``soma1`` is taken, the next
- free default of the kind is used (``soma1``, ``roi2``);
+ so gets soma in front (SILo knows a soma by its label). Without a
+ label, or when a default label such as soma1 is taken, the next
+ free default of the kind is used (soma1, roi2);
another taken label gets a number after it.
+
+ Parameters
+ ----------
+ kind : str
+ The ROI's kind, 'soma' or 'roi'.
+ label : object
+ The requested label (None or empty for none); converted with str.
+ taken : set
+ The labels already in use (lower case).
+
+ Returns
+ -------
+ str
+ The unique label.
"""
text = str(label or "").strip()[:MAX_TEXT]
if kind == "soma" and text and "SOMA" not in text.upper():
@@ -75,9 +105,20 @@ def _label(kind: str, label, taken: set) -> str:
return f"{_PREFIX[kind]}{k}"
-def _points(raw) -> Optional[list]:
- """Polygon points as a list of ``[x, y]`` floats, or None if they do
- not make a polygon."""
+def _points(raw: object) -> list | None:
+ """Return polygon points as a list of [x, y] floats.
+
+ Parameters
+ ----------
+ raw : object
+ The points as received, array-like of [x, y] pairs.
+
+ Returns
+ -------
+ list or None
+ The points rounded to three decimals, or None if they do
+ not make a polygon.
+ """
try:
pts = np.asarray(raw, np.float64).reshape(-1, 2)
except (TypeError, ValueError):
@@ -89,8 +130,10 @@ def _points(raw) -> Optional[list]:
return [[round(float(x), 3), round(float(y), 3)] for x, y in pts]
-def clean_state(obj, n_paths: int, *, reserved_labels=()) -> dict:
- """A state made valid: unknown fields dropped (among them the
+def clean_state(obj: object, n_paths: int, *, reserved_labels: Iterable[str] = ()) -> dict:
+ """Return a state made valid.
+
+ Unknown fields are dropped (among them the
exclusion zones and trial marks of earlier versions), labels fitted to
their kind and made unique over the whole session (so that a soma of
one path is never taken for a soma of the other).
@@ -112,7 +155,7 @@ def clean_state(obj, n_paths: int, *, reserved_labels=()) -> dict:
Raises
------
ValueError
- If ``obj`` is not a dict or a ROI has an unknown kind.
+ If obj is not a dict or a ROI has an unknown kind.
"""
if not isinstance(obj, dict):
raise ValueError("the annotation state must be an object")
@@ -137,26 +180,22 @@ def clean_state(obj, n_paths: int, *, reserved_labels=()) -> dict:
taken.add(label.lower())
entry = {"kind": kind, "label": label, "points": pts}
mask_id = roi.get("mask_id")
- if (
- type(mask_id) is int
- and mask_id > 0
- and mask_id not in mask_ids
- ):
+ if type(mask_id) is int and mask_id > 0 and mask_id not in mask_ids:
entry["mask_id"] = mask_id
mask_ids.add(mask_id)
out["paths"][d]["rois"].append(entry)
return out
-def polygon_mask(points, shape: tuple) -> np.ndarray:
- """The pixels whose centres lie inside a polygon.
+def polygon_mask(points: npt.ArrayLike, shape: tuple) -> np.ndarray:
+ """Return the pixels whose centres lie inside a polygon.
Parameters
----------
points : array-like, (vertices, 2)
- ``[x, y]`` in image coordinates (pixel ``(r, c)`` covers
- ``[c, c + 1) x [r, r + 1)``, so its centre is at
- ``(c + 0.5, r + 0.5)``).
+ [x, y] in image coordinates (pixel (r, c) covers
+ [c, c + 1) x [r, r + 1), so its centre is at
+ (c + 0.5, r + 0.5)).
shape : (rows, cols)
The image's size; the polygon is clipped to it.
@@ -174,9 +213,19 @@ def polygon_mask(points, shape: tuple) -> np.ndarray:
return mask
-def mask_outline(mask: np.ndarray) -> Optional[list]:
- """A polygon around the largest connected part of a mask, as ``[x, y]``
- image coordinates; None for an empty mask."""
+def mask_outline(mask: np.ndarray) -> list | None:
+ """Return a polygon around the largest connected part of a mask.
+
+ Parameters
+ ----------
+ mask : np.ndarray
+ The mask, (rows, cols); converted to bool.
+
+ Returns
+ -------
+ list or None
+ The polygon as [x, y] image coordinates; None for an empty mask.
+ """
from skimage.measure import find_contours
m = np.asarray(mask, bool)
@@ -191,6 +240,6 @@ def mask_outline(mask: np.ndarray) -> Optional[list]:
pts = np.column_stack([best[:, 1] - 1 + 0.5, best[:, 0] - 1 + 0.5])
if len(pts) > 1 and np.allclose(pts[0], pts[-1]):
pts = pts[:-1]
- step = max(1, int(math.ceil(len(pts) / 200)))
+ step = max(1, math.ceil(len(pts) / 200))
pts = pts[::step]
return None if len(pts) < 3 else pts.tolist()
diff --git a/src/giant_python/cli.py b/src/giant_python/cli.py
index 450fd30a..91f9f20b 100644
--- a/src/giant_python/cli.py
+++ b/src/giant_python/cli.py
@@ -1,14 +1,14 @@
"""CLI for SLAP2 registration, annotation and band extraction.
-``giant trial-table`` builds a SLAP2 session's trial table;
-``giant register`` registers raster recordings (MultiRoiRegistration) and
-computes each trial's summary statistics; ``giant reg-stats`` computes them
+giant trial-table builds a SLAP2 session's trial table;
+giant register registers raster recordings (MultiRoiRegistration) and
+computes each trial's summary statistics; giant reg-stats computes them
for trials registered earlier (GIAnT-MATLAB's included);
-``giant silo`` extracts sources from them (raster SILo; its stages also run
-on their own as ``giant silo-localize``, ``silo-plan``, ``silo-prepare``,
-``silo-dispatch``, ``silo-solve`` and ``silo-collect``, see
-:mod:`giant_python.cli_silo`); ``giant annotate`` loads or draws ROIs;
-``giant extract`` runs BandSILo.
+giant silo extracts sources from them (raster SILo; its stages also run
+on their own as giant silo-localize, silo-plan, silo-prepare,
+silo-dispatch, silo-solve and silo-collect, see
+:mod:`giant_python.cli_silo`); giant annotate loads or draws ROIs;
+giant extract runs BandSILo.
All delegate to the public workflow services with separate scientific,
execution and annotation options. GUI imports occur only when needed.
"""
@@ -17,7 +17,9 @@
import argparse
import sys
-from typing import Optional, Sequence
+from collections.abc import Sequence
+
+import numpy.typing as npt
from .cli_silo import SILO_COMMANDS, add_silo_commands, run_silo_command
from .cli_spine import SPINE_COMMANDS, add_spine_commands, run_spine_command
@@ -172,8 +174,7 @@ def _add_register_options(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--polish",
action="store_true",
- help="With --schedule grow: rematch every frame to the final "
- "template.",
+ help="With --schedule grow: rematch every frame to the final template.",
)
parser.add_argument(
"--device",
@@ -207,19 +208,17 @@ def _add_register_options(parser: argparse.ArgumentParser) -> None:
)
-def _add_reg_stats_command(subparsers) -> None:
+def _add_reg_stats_command(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
"""``giant reg-stats``: statistics of registered trials."""
stats = subparsers.add_parser(
"reg-stats",
- help="Summary statistics of registered trials (registration "
- "computes them for new ones).",
+ help="Summary statistics of registered trials (registration computes them for new ones).",
)
stats.add_argument("trial_table", help="Path to trial_table.h5.")
stats.add_argument(
"--out",
default=None,
- help="Folder for the statistics files (default: next to each "
- "registered movie).",
+ help="Folder for the statistics files (default: next to each registered movie).",
)
stats.add_argument(
"--datadr",
@@ -229,8 +228,7 @@ def _add_reg_stats_command(subparsers) -> None:
stats.add_argument(
"--moco",
default=None,
- help="Motion-correction folder (default: /"
- "motion_correction).",
+ help="Motion-correction folder (default: /motion_correction).",
)
stats.add_argument(
"--device",
@@ -255,33 +253,27 @@ def _add_reg_stats_command(subparsers) -> None:
default=None,
help=f"One-based {name}, comma-separated (default: all).",
)
- stats.add_argument(
- "--verbose", action="store_true", help="Print progress messages."
- )
+ stats.add_argument("--verbose", action="store_true", help="Print progress messages.")
def build_parser() -> argparse.ArgumentParser:
- """Build the ``giant`` argument parser.
+ """Build the giant argument parser.
Returns
-------
argparse.ArgumentParser
- Parser with ``trial-table``, ``register``, ``reg-stats``,
- ``annotate``, ``extract``, the SILo subcommands (``silo``,
- ``silo-localize``, ``silo-plan``, ``silo-prepare``,
- ``silo-dispatch``, ``silo-solve``, ``silo-collect``) and
- ``view``. Each
- subcommand stores its ``command`` name in the parsed namespace.
+ Parser with trial-table, register, reg-stats,
+ annotate, extract, the SILo subcommands (silo,
+ silo-localize, silo-plan, silo-prepare,
+ silo-dispatch, silo-solve, silo-collect) and
+ view. Each
+ subcommand stores its command name in the parsed namespace.
"""
parser = argparse.ArgumentParser(prog="giant")
subparsers = parser.add_subparsers(dest="command")
- table = subparsers.add_parser(
- "trial-table", help="Build a SLAP2 session's trial_table.h5."
- )
- table.add_argument(
- "dat_dir", help="Folder with the session's .dat and .meta files."
- )
+ table = subparsers.add_parser("trial-table", help="Build a SLAP2 session's trial_table.h5.")
+ table.add_argument("dat_dir", help="Folder with the session's .dat and .meta files.")
table.add_argument(
"--save-dir",
default=None,
@@ -294,16 +286,12 @@ def build_parser() -> argparse.ArgumentParser:
help="Keep only the first seconds of the session.",
)
- register = subparsers.add_parser(
- "register", help="Register SLAP2 raster recordings."
- )
+ register = subparsers.add_parser("register", help="Register SLAP2 raster recordings.")
register.add_argument("trial_table", help="Path to trial_table.h5.")
_add_register_options(register)
_add_reg_stats_command(subparsers)
- annotate = subparsers.add_parser(
- "annotate", help="Draw / save user ROIs (standalone step)."
- )
+ annotate = subparsers.add_parser("annotate", help="Draw / save user ROIs (standalone step).")
annotate.add_argument("trial_table", help="Path to trial_table.h5.")
_add_silo_options(annotate)
@@ -321,7 +309,7 @@ def build_parser() -> argparse.ArgumentParser:
return parser
-def _add_export_f0_command(subparsers) -> None:
+def _add_export_f0_command(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
"""``giant export-f0``: F0 network training data from a SILo run."""
from .export.f0_training import add_arguments
@@ -335,13 +323,21 @@ def _add_export_f0_command(subparsers) -> None:
def _cmd_export_f0(args: argparse.Namespace) -> int:
- """Handle ``giant export-f0``."""
+ """Handle giant export-f0.
+
+ Returns
+ -------
+ int
+ Exit code of the export.
+ """
from .export.f0_training import run_command
return run_command(args)
-def _add_export_f0_injected_command(subparsers) -> None:
+def _add_export_f0_injected_command(
+ subparsers: argparse._SubParsersAction[argparse.ArgumentParser],
+) -> None:
"""``giant export-f0-injected``: the GFP kind of the F0 training data."""
from .export.f0_injected import add_arguments
@@ -355,13 +351,21 @@ def _add_export_f0_injected_command(subparsers) -> None:
def _cmd_export_f0_injected(args: argparse.Namespace) -> int:
- """Handle ``giant export-f0-injected``."""
+ """Handle giant export-f0-injected.
+
+ Returns
+ -------
+ int
+ Exit code of the export.
+ """
from .export.f0_injected import run_command
return run_command(args)
-def _add_export_f0_layout_command(subparsers) -> None:
+def _add_export_f0_layout_command(
+ subparsers: argparse._SubParsersAction[argparse.ArgumentParser],
+) -> None:
"""``giant export-f0-layout``: raster layouts for the F0 simulator."""
from .export.f0_layout import add_arguments
@@ -375,13 +379,19 @@ def _add_export_f0_layout_command(subparsers) -> None:
def _cmd_export_f0_layout(args: argparse.Namespace) -> int:
- """Handle ``giant export-f0-layout``."""
+ """Handle giant export-f0-layout.
+
+ Returns
+ -------
+ int
+ Exit code of the export.
+ """
from .export.f0_layout import run_command
return run_command(args)
-def _add_view_command(subparsers) -> None:
+def _add_view_command(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
"""``giant view``: a browser viewer of SILo runs."""
from .viewer.server import add_arguments
@@ -395,13 +405,21 @@ def _add_view_command(subparsers) -> None:
def _cmd_view(args: argparse.Namespace) -> int:
- """Handle ``giant view``."""
+ """Handle giant view.
+
+ Returns
+ -------
+ int
+ Exit code of the viewer server.
+ """
from .viewer.server import serve
return serve(args)
-def _add_annotate_raster_command(subparsers) -> None:
+def _add_annotate_raster_command(
+ subparsers: argparse._SubParsersAction[argparse.ArgumentParser],
+) -> None:
"""``giant annotate-raster``: soma and plain ROIs of a raster session."""
from .annotator.server import add_arguments
@@ -415,7 +433,13 @@ def _add_annotate_raster_command(subparsers) -> None:
def _cmd_annotate_raster(args: argparse.Namespace) -> int:
- """Handle ``giant annotate-raster``."""
+ """Handle giant annotate-raster.
+
+ Returns
+ -------
+ int
+ Exit code of the annotator server.
+ """
from .annotator.server import serve
return serve(args)
@@ -424,7 +448,14 @@ def _cmd_annotate_raster(args: argparse.Namespace) -> int:
def _options_from_args(
args: argparse.Namespace,
) -> tuple[BandSiloParams, ExecutionOptions, AnnotationOptions]:
- """Build independent science, execution and annotation configuration."""
+ """Build independent science, execution and annotation configuration.
+
+ Returns
+ -------
+ tuple[BandSiloParams, ExecutionOptions, AnnotationOptions]
+ The scientific parameters, the execution options and the
+ annotation options, from the parsed arguments.
+ """
return (
BandSiloParams(
z_tol=args.z_tol,
@@ -451,7 +482,13 @@ def _options_from_args(
def _cmd_annotate(
args: argparse.Namespace,
) -> int:
- """Handle ``giant annotate`` (standalone ROI annotation)."""
+ """Handle giant annotate (standalone ROI annotation).
+
+ Returns
+ -------
+ int
+ Exit code (0).
+ """
from .pipeline.annotate import annotate_rois
params, execution, annotations = _options_from_args(args)
@@ -467,17 +504,27 @@ def _cmd_annotate(
def _cmd_trial_table(args: argparse.Namespace) -> int:
- """Handle ``giant trial-table`` (buildTrialTableSLAP2)."""
+ """Handle giant trial-table (buildTrialTableSLAP2).
+
+ Returns
+ -------
+ int
+ Exit code (0).
+ """
from .pipeline.trial_table import build_trial_table_slap2
- build_trial_table_slap2(
- args.dat_dir, args.save_dir, max_duration_s=args.max_duration_s
- )
+ build_trial_table_slap2(args.dat_dir, args.save_dir, max_duration_s=args.max_duration_s)
return 0
def _cmd_register(args: argparse.Namespace) -> int:
- """Handle ``giant register`` (MultiRoiRegistration)."""
+ """Handle giant register (MultiRoiRegistration).
+
+ Returns
+ -------
+ int
+ Exit code: 1 if any trial's registration raised, else 0.
+ """
import logging
from .io.trial_table import read_trial_table
@@ -510,7 +557,13 @@ def _cmd_register(args: argparse.Namespace) -> int:
def _cmd_reg_stats(args: argparse.Namespace) -> int:
- """Handle ``giant reg-stats``; nonzero if a trial failed."""
+ """Handle giant reg-stats; nonzero if a trial failed.
+
+ Returns
+ -------
+ int
+ Exit code: 1 if any trial failed, else 0.
+ """
import logging
from .pipeline.reg_stats import reg_stats
@@ -529,19 +582,16 @@ def _cmd_reg_stats(args: argparse.Namespace) -> int:
trials=args.trials,
)
failed = [r for r in results if r["error"] is not None]
- print(
- f"giant reg-stats: {len(results) - len(failed)} of {len(results)} "
- "trials written."
- )
+ print(f"giant reg-stats: {len(results) - len(failed)} of {len(results)} trials written.")
for r in failed:
print(f" failed: {r['out']}: {r['error']}")
return 1 if failed else 0
-def _report_registration(fields: dict, present) -> int:
- """Summarize ``register_multiroi``'s outcome; nonzero if a trial raised.
+def _report_registration(fields: dict, present: npt.ArrayLike) -> int:
+ """Summarize register_multiroi's outcome; nonzero if a trial raised.
- Trials flagged ``registrationFailed`` (too much motion, or too few
+ Trials flagged registrationFailed (too much motion, or too few
frames with samples) have outputs and are listed; SILo skips them.
Trials whose registration raised have no outputs (empty filenames).
Cells of a ragged table without a recording are listed apart.
@@ -549,7 +599,7 @@ def _report_registration(fields: dict, present) -> int:
Parameters
----------
fields : dict
- What ``register_multiroi`` returned.
+ What register_multiroi returned.
present : ndarray of bool
Which cells of the table name a recording.
@@ -566,24 +616,24 @@ def _report_registration(fields: dict, present) -> int:
raised = unnamed & present
flagged = failed & ~unnamed
- def trials(mask):
- """``trial t (path d)`` for each selected trial."""
- return ", ".join(
- f"trial {t + 1} (path {d + 1})" for d, t in zip(*np.nonzero(mask))
- )
+ def trials(mask: npt.ArrayLike) -> str:
+ """Return trial t (path d) for each selected trial.
- print(
- f"giant register: {(~unnamed).sum()} of {present.sum()} "
- "trials registered."
- )
+ Returns
+ -------
+ str
+ The selected trials, comma-separated, one-based.
+ """
+ return ", ".join(f"trial {t + 1} (path {d + 1})" for d, t in zip(*np.nonzero(mask)))
+
+ print(f"giant register: {(~unnamed).sum()} of {present.sum()} trials registered.")
if not present.all():
print(f"No recording (skipped): {trials(~present)}")
if flagged.any():
print(f"registrationFailed (excluded by SILo): {trials(flagged)}")
if raised.any():
print(
- f"Registration raised, no outputs (see the log): "
- f"{trials(raised)}",
+ f"Registration raised, no outputs (see the log): {trials(raised)}",
file=sys.stderr,
)
return 1
@@ -591,7 +641,13 @@ def trials(mask):
def _cmd_extract(args: argparse.Namespace) -> int:
- """Handle ``giant extract`` (source extraction)."""
+ """Handle giant extract (source extraction).
+
+ Returns
+ -------
+ int
+ Exit code (0).
+ """
from .pipeline.extract import extract_sources
params, execution, annotations = _options_from_args(args)
@@ -606,28 +662,28 @@ def _cmd_extract(args: argparse.Namespace) -> int:
return 0
-def main(argv: Optional[Sequence[str]] = None) -> int:
- """Entry point for the ``giant`` console script.
+def main(argv: Sequence[str] | None = None) -> int:
+ """Entry point for the giant console script.
- Dispatches ``trial-table``, ``register``, ``annotate``, ``extract``
+ Dispatches trial-table, register, annotate, extract
and the SILo commands to their workflow services.
Parameters
----------
argv : sequence of str, optional
- Command-line arguments (defaults to ``sys.argv[1:]``).
+ Command-line arguments (defaults to sys.argv[1:]).
Returns
-------
int
- Process exit code (``2`` when no subcommand is given).
+ Process exit code (2 when no subcommand is given).
Raises
------
SystemExit
Invalid options and unsupported workflows print an argparse error
and exit with code two, without claiming the operation succeeded.
- """
+ """ # noqa: DOC502
parser = build_parser()
args = parser.parse_args(argv)
handlers = {
diff --git a/src/giant_python/cli_silo.py b/src/giant_python/cli_silo.py
index da106fec..d1799db5 100644
--- a/src/giant_python/cli_silo.py
+++ b/src/giant_python/cli_silo.py
@@ -1,36 +1,36 @@
"""``giant silo`` and its staged commands (raster SILo for SLAP2).
-``giant silo TABLE`` runs SILo on one machine, streaming as GIAnT-MATLAB's
-``SILo.m`` (or, with ``--prepare-workers`` / ``--trial-workers``, with the
+giant silo TABLE runs SILo on one machine, streaming as GIAnT-MATLAB's
+SILo.m (or, with --prepare-workers / --trial-workers, with the
prepare and solve stages in several processes of the machine). The stages
also run on their own, for any subset of their units, so that they can be
scattered over machines:
-* ``giant silo-localize TABLE``: per-trial localization files;
-* ``giant silo-plan TABLE``: one extraction plan per path;
-* ``giant silo-prepare TABLE``: one container per trial-path
- (``--prepare-workers N``: N trials at once);
-* ``giant silo-dispatch TABLE --machines N``: solver job files;
-* ``giant silo-solve JOB``: one job's results files (needs only the job file
- and the containers it names; ``--trial-workers M``: M trials at once);
-* ``giant silo-collect TABLE``: the kinetics test, ``experiment_summary.h5``,
- ``per_trial_summary.h5`` and the trial table's fields, and the spot
+* giant silo-localize TABLE: per-trial localization files;
+* giant silo-plan TABLE: one extraction plan per path;
+* giant silo-prepare TABLE: one container per trial-path
+ (--prepare-workers N: N trials at once);
+* giant silo-dispatch TABLE --machines N: solver job files;
+* giant silo-solve JOB: one job's results files (needs only the job file
+ and the containers it names; --trial-workers M: M trials at once);
+* giant silo-collect TABLE: the kinetics test, experiment_summary.h5,
+ per_trial_summary.h5 and the trial table's fields, and the spot
annotation (:mod:`~giant_python.pipeline.silo_spots`);
-* ``giant silo-spots TABLE``: the spot annotation of an existing
- ``experiment_summary.h5`` again (for example one made before it existed).
+* giant silo-spots TABLE: the spot annotation of an existing
+ experiment_summary.h5 again (for example one made before it existed).
Scientific settings are :class:`~giant_python.models.params.SiloParams`
-fields: a few have their own options, any can be set with ``--set
-name=value`` or a JSON file (``--params``).
-
-The baseline: ``--baseline network`` localizes and extracts with the F0
-network's baselines (``*_BASELINE-80Hz.h5``) from ``--baseline-dir``, or
-predicts the missing ones with ``--f0-ckpt PATH`` (``slap2-f0
-predict-registered``; GPU). It is the default when ``--baseline-dir`` or
-``--f0-ckpt`` is given, the moving median (MATLAB's) otherwise. Staged runs
+fields: a few have their own options, any can be set with --set
+name=value or a JSON file (--params).
+
+The baseline: --baseline network localizes and extracts with the F0
+network's baselines (``*_BASELINE-80Hz.h5``) from --baseline-dir, or
+predicts the missing ones with --f0-ckpt PATH (slap2-f0
+predict-registered; GPU). It is the default when --baseline-dir or
+--f0-ckpt is given, the moving median (MATLAB's) otherwise. Staged runs
give every stage the same settings: the stages without those options
-(``silo-plan``, ``silo-dispatch``, ``silo-collect``) need ``--baseline
-network`` too, and refuse to run on files made with another baseline.
+(silo-plan, silo-dispatch, silo-collect) need --baseline
+network too, and refuse to run on files made with another baseline.
"""
from __future__ import annotations
@@ -39,10 +39,13 @@
import json
from dataclasses import fields
from pathlib import Path
-from typing import Optional
+from typing import TYPE_CHECKING
from .models.params import SiloExecution, SiloParams
+if TYPE_CHECKING:
+ from .pipeline.silo_session import SiloSession
+
SILO_COMMANDS = (
"silo",
"silo-localize",
@@ -55,8 +58,24 @@
)
-def parse_numbers(text: Optional[str]) -> Optional[list]:
- """One-based numbers ``"1,3-5"`` as a list; None for None."""
+def parse_numbers(text: str | None) -> list | None:
+ """Parse one-based numbers "1,3-5" into a list; None for None.
+
+ Parameters
+ ----------
+ text : str or None
+ Comma-separated numbers and ranges.
+
+ Returns
+ -------
+ list or None
+ The numbers as a list of int, or None if text is None.
+
+ Raises
+ ------
+ ValueError
+ If a range is empty or a number is below 1.
+ """
if text is None:
return None
out = []
@@ -176,8 +195,7 @@ def _add_science(parser: argparse.ArgumentParser) -> None:
dest="align_patch_px",
type=int,
default=None,
- help="Imaged pixels per patch of the patchwise field (MATLAB "
- "alignPatchPx; default 1500).",
+ help="Imaged pixels per patch of the patchwise field (MATLAB alignPatchPx; default 1500).",
)
g.add_argument(
"--localization-baseline",
@@ -195,10 +213,8 @@ def _add_science(parser: argparse.ArgumentParser) -> None:
def _add_session(parser: argparse.ArgumentParser) -> None:
- """The trial table and folder overrides."""
- parser.add_argument(
- "trial_table", help="trial_table.h5 (or the folder holding it)."
- )
+ """Add the trial table and folder overrides."""
+ parser.add_argument("trial_table", help="trial_table.h5 (or the folder holding it).")
g = parser.add_argument_group("folders")
g.add_argument(
"--moco-dir",
@@ -227,15 +243,16 @@ def _add_session(parser: argparse.ArgumentParser) -> None:
)
-def _add_baseline_files(parser: argparse.ArgumentParser, predict: bool):
- """The network's baselines: their folder and, if ``predict``, the
- prediction of missing ones."""
+def _add_baseline_files(parser: argparse.ArgumentParser, predict: bool) -> None:
+ """Add the network's baselines: their folder and the prediction of missing ones.
+
+ The prediction options are added only if predict.
+ """
g = parser.add_argument_group("the F0 network's baselines")
g.add_argument(
"--baseline-dir",
default=None,
- help="Folder of the network's *_BASELINE-80Hz.h5 files (default "
- "/baselines).",
+ help="Folder of the network's *_BASELINE-80Hz.h5 files (default /baselines).",
)
if not predict:
return
@@ -248,8 +265,7 @@ def _add_baseline_files(parser: argparse.ArgumentParser, predict: bool):
g.add_argument(
"--f0-device",
default="cuda",
- help="Device of the prediction: cuda (default), cpu (many times "
- "slower), auto.",
+ help="Device of the prediction: cuda (default), cpu (many times slower), auto.",
)
g.add_argument(
"--f0-command",
@@ -274,9 +290,12 @@ def _add_execution(
prepare: bool = False,
trials: bool = False,
) -> None:
- """How to run (SiloExecution); ``fits``: the solver's device,
- precision and batches (a job file brings its own); ``prepare`` and
- ``trials``: the processes that prepare and that solve whole trials."""
+ """Add how to run (SiloExecution).
+
+ fits: the solver's device,
+ precision and batches (a job file brings its own); prepare and
+ trials: the processes that prepare and that solve whole trials.
+ """
d = SiloExecution
g = parser.add_argument_group("execution (results do not depend on it)")
staged = prepare and trials # giant silo: either option stages the run
@@ -306,8 +325,7 @@ def _add_execution(
"process of --solver-threads threads (default 0: one trial at "
"a time, its subproblems spread over --solver-workers "
"processes). Much faster on a many-core machine; each process "
- "holds one trial's container."
- + (" See --prepare-workers." if staged else ""),
+ "holds one trial's container." + (" See --prepare-workers." if staged else ""),
)
g.add_argument(
"--workers",
@@ -380,12 +398,11 @@ def _add_execution(
g.add_argument("--verbose", action="store_true", help="Print progress.")
-def add_silo_commands(subparsers) -> None:
- """Add ``silo`` and the staged commands to ``giant``'s subparsers."""
+def add_silo_commands(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
+ """Add silo and the staged commands to giant's subparsers."""
run = subparsers.add_parser(
"silo",
- help="SILo source extraction of SLAP2 raster recordings on one "
- "machine (MATLAB's SILo.m).",
+ help="SILo source extraction of SLAP2 raster recordings on one machine (MATLAB's SILo.m).",
)
_add_session(run)
_add_science(run)
@@ -416,18 +433,14 @@ def add_silo_commands(subparsers) -> None:
help="Leave the trial table's source_extraction fields as they are.",
)
- loc = subparsers.add_parser(
- "silo-localize", help="SILo stage: per-trial localization files."
- )
+ loc = subparsers.add_parser("silo-localize", help="SILo stage: per-trial localization files.")
_add_session(loc)
_add_science(loc)
_add_execution(loc, solver=False)
_add_units(loc)
_add_baseline_files(loc, predict=True)
- pl = subparsers.add_parser(
- "silo-plan", help="SILo stage: one extraction plan per path."
- )
+ pl = subparsers.add_parser("silo-plan", help="SILo stage: one extraction plan per path.")
_add_session(pl)
_add_science(pl)
_add_execution(pl, solver=False)
@@ -438,18 +451,14 @@ def add_silo_commands(subparsers) -> None:
help="Seeds file used instead of the plan's seeding (parity runs).",
)
- prep = subparsers.add_parser(
- "silo-prepare", help="SILo stage: one container per trial-path."
- )
+ prep = subparsers.add_parser("silo-prepare", help="SILo stage: one container per trial-path.")
_add_session(prep)
_add_science(prep)
_add_execution(prep, solver=False, prepare=True)
_add_units(prep)
_add_baseline_files(prep, predict=False)
- disp = subparsers.add_parser(
- "silo-dispatch", help="SILo stage: solver job files."
- )
+ disp = subparsers.add_parser("silo-dispatch", help="SILo stage: solver job files.")
_add_session(disp)
_add_science(disp)
_add_execution(disp, solver=True)
@@ -480,8 +489,7 @@ def add_silo_commands(subparsers) -> None:
col = subparsers.add_parser(
"silo-collect",
- help="SILo stage: kinetics test, experiment and per-trial "
- "summaries, trial table fields.",
+ help="SILo stage: kinetics test, experiment and per-trial summaries, trial table fields.",
)
_add_session(col)
_add_science(col)
@@ -509,10 +517,8 @@ def add_silo_commands(subparsers) -> None:
def _add_units(parser: argparse.ArgumentParser) -> None:
- """Selection of trial-paths."""
- parser.add_argument(
- "--paths", default=None, help="Paths, e.g. 1,2 (default: all)."
- )
+ """Add the selection of trial-paths."""
+ parser.add_argument("--paths", default=None, help="Paths, e.g. 1,2 (default: all).")
parser.add_argument(
"--trials",
default=None,
@@ -520,8 +526,19 @@ def _add_units(parser: argparse.ArgumentParser) -> None:
)
-def _value(text: str):
- """A ``--set`` value: JSON if it parses, else the text."""
+def _value(text: str) -> object:
+ """Parse a --set value: JSON if it parses, else the text.
+
+ Parameters
+ ----------
+ text : str
+ The value as given.
+
+ Returns
+ -------
+ object
+ The parsed JSON value if text parses as JSON, else text.
+ """
try:
return json.loads(text)
except ValueError:
@@ -529,7 +546,20 @@ def _value(text: str):
def _f0_image_options(args: argparse.Namespace, values: dict) -> None:
- """``--f0-im-trim-s`` and ``--no-f0-images`` into ``values``."""
+ """Put --f0-im-trim-s and --no-f0-images into values.
+
+ Parameters
+ ----------
+ args : argparse.Namespace
+ Parsed command line.
+ values : dict
+ SiloParams fields, updated in place.
+
+ Raises
+ ------
+ ValueError
+ If both --f0-im-trim-s and --no-f0-images are given.
+ """
trim = getattr(args, "f0_im_trim_s", None)
if getattr(args, "no_f0_images", False):
if trim is not None:
@@ -540,12 +570,26 @@ def _f0_image_options(args: argparse.Namespace, values: dict) -> None:
def params_from_args(args: argparse.Namespace) -> SiloParams:
- """SiloParams from ``--params``, ``--set`` and the explicit options."""
+ """Build SiloParams from --params, --set and the explicit options.
+
+ Parameters
+ ----------
+ args : argparse.Namespace
+ Parsed command line.
+
+ Returns
+ -------
+ SiloParams
+ The scientific settings of the run.
+
+ Raises
+ ------
+ ValueError
+ If a --set item lacks =, or a field name is not a SiloParams field.
+ """
values: dict = {}
if getattr(args, "params", None):
- values.update(
- json.loads(Path(args.params).read_text(encoding="utf-8"))
- )
+ values.update(json.loads(Path(args.params).read_text(encoding="utf-8")))
for item in getattr(args, "set", []) or []:
if "=" not in item:
raise ValueError(f"--set needs NAME=VALUE, not {item!r}")
@@ -581,7 +625,18 @@ def params_from_args(args: argparse.Namespace) -> SiloParams:
def execution_from_args(args: argparse.Namespace) -> SiloExecution:
- """SiloExecution from the execution options."""
+ """Build SiloExecution from the execution options.
+
+ Parameters
+ ----------
+ args : argparse.Namespace
+ Parsed command line.
+
+ Returns
+ -------
+ SiloExecution
+ How to run the command.
+ """
values = {"workers": args.workers, "overwrite": args.overwrite}
values["verbose"] = args.verbose
values["loader_device"] = args.loader_device
@@ -605,16 +660,24 @@ def execution_from_args(args: argparse.Namespace) -> SiloExecution:
return SiloExecution(**values)
-def _session(args: argparse.Namespace):
- """The session of the command's trial table and folders (dispatch and
- collect need neither registered movies nor raw data)."""
+def _session(args: argparse.Namespace) -> SiloSession:
+ """Open the session of the command's trial table and folders.
+
+ Dispatch and collect need neither registered movies nor raw data.
+
+ Parameters
+ ----------
+ args : argparse.Namespace
+ Parsed command line.
+
+ Returns
+ -------
+ SiloSession
+ The opened session.
+ """
from .pipeline.silo_session import SiloSession
- inputs = (
- "collect"
- if args.command in ("silo-dispatch", "silo-collect", "silo-spots")
- else "all"
- )
+ inputs = "collect" if args.command in ("silo-dispatch", "silo-collect", "silo-spots") else "all"
return SiloSession.open(
args.trial_table,
args.moco_dir,
@@ -626,8 +689,21 @@ def _session(args: argparse.Namespace):
)
-def _selected_units(session, args) -> Optional[list]:
- """Zero-based ``(path, trial)`` pairs of ``--paths`` and ``--trials``."""
+def _selected_units(session: SiloSession, args: argparse.Namespace) -> list | None:
+ """Return zero-based (path, trial) pairs of --paths and --trials.
+
+ Parameters
+ ----------
+ session : SiloSession
+ The session (its path and trial counts apply to an omitted option).
+ args : argparse.Namespace
+ Parsed command line.
+
+ Returns
+ -------
+ list or None
+ The (path, trial) pairs, or None if neither option is given.
+ """
paths = parse_numbers(args.paths)
trials = parse_numbers(args.trials)
if paths is None and trials is None:
@@ -637,20 +713,29 @@ def _selected_units(session, args) -> Optional[list]:
return [(d - 1, t - 1) for d in paths for t in trials]
-def _print(record) -> None:
+def _print(record: object) -> None:
"""Print a stage's report as JSON."""
print(json.dumps(record, indent=1, default=str))
-def run_silo_command(args: argparse.Namespace) -> int: # noqa: C901
- """Run one of the SILo commands; returns the exit code."""
+def run_silo_command(args: argparse.Namespace) -> int:
+ """Run one of the SILo commands.
+
+ Parameters
+ ----------
+ args : argparse.Namespace
+ Parsed command line.
+
+ Returns
+ -------
+ int
+ The exit code (0).
+ """
from .pipeline import silo, silo_collect, silo_solve
ex = execution_from_args(args)
if args.command == "silo-solve":
- _print(
- silo_solve.solve_job(args.job, args.containers, args.results, ex)
- )
+ _print(silo_solve.solve_job(args.job, args.containers, args.results, ex))
return 0
params = params_from_args(args)
if args.command == "silo":
diff --git a/src/giant_python/cli_spine.py b/src/giant_python/cli_spine.py
index b386c604..5e4ad7af 100644
--- a/src/giant_python/cli_spine.py
+++ b/src/giant_python/cli_spine.py
@@ -1,13 +1,13 @@
"""``giant spine``: spine-size readout from a SILo run.
-``giant spine readout RUN_DIR --table TABLE [--baseline-dir DIR --moco-dir
-DIR]`` reads out every source's (and user ROI's) size in every trial and
-writes a ``spine_summary_.h5`` file (:mod:`giant_python.spine`),
+giant spine readout RUN_DIR --table TABLE [--baseline-dir DIR --moco-dir
+DIR] reads out every source's (and user ROI's) size in every trial and
+writes a spine_summary_.h5 file (:mod:`giant_python.spine`),
with the trend tests of the normalized sizes;
-``giant spine images`` only builds the network's per-trial F0 images (the
-slow part), which ``readout`` then reuses from its cache. ``giant spine
-view`` shows summaries in the browser (and writes marks), ``giant spine
-export-html`` writes one self-contained page of a summary.
+giant spine images only builds the network's per-trial F0 images (the
+slow part), which readout then reuses from its cache. giant spine
+view shows summaries in the browser (and writes marks), giant spine
+export-html writes one self-contained page of a summary.
"""
from __future__ import annotations
@@ -21,12 +21,8 @@
def _add_common(p: argparse.ArgumentParser) -> None:
"""Options shared by the spine commands."""
- p.add_argument(
- "run_dir", help="Folder with experiment_summary.h5 (a SILo run)."
- )
- p.add_argument(
- "--table", required=True, help="The session's trial_table.h5."
- )
+ p.add_argument("run_dir", help="Folder with experiment_summary.h5 (a SILo run).")
+ p.add_argument("--table", required=True, help="The session's trial_table.h5.")
p.add_argument(
"--baseline-dir",
default=None,
@@ -59,8 +55,7 @@ def _add_common(p: argparse.ArgumentParser) -> None:
"--align-hz",
type=float,
default=None,
- help="Frame rate of the registered movies (default: the run's "
- "alignHz, else 80).",
+ help="Frame rate of the registered movies (default: the run's alignHz, else 80).",
)
p.add_argument(
"--motion-thresh",
@@ -101,10 +96,15 @@ def _add_common(p: argparse.ArgumentParser) -> None:
p.add_argument("--quiet", action="store_true", help="No progress lines.")
-def _workers(asked):
- """The workers a spine command asks the readout for: the number
- given, else the default (up to 8, one per CPU;
- :func:`~giant_python.spine.parallel.n_workers`)."""
+def _workers(asked: int | None) -> int:
+ """Return the workers a spine command asks the readout for.
+
+ Returns
+ -------
+ int
+ The number given, else the default (up to 8, one per CPU;
+ :func:`~giant_python.spine.parallel.n_workers`).
+ """
if asked is not None:
return asked
from .spine.parallel import n_workers
@@ -112,11 +112,9 @@ def _workers(asked):
return n_workers(None)
-def add_spine_commands(subparsers) -> None:
- """Add ``giant spine`` and its subcommands."""
- spine = subparsers.add_parser(
- "spine", help="Spine-size readout from a SILo run."
- )
+def add_spine_commands(subparsers: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
+ """Add giant spine and its subcommands."""
+ spine = subparsers.add_parser("spine", help="Spine-size readout from a SILo run.")
sub = spine.add_subparsers(dest="spine_command")
readout = sub.add_parser(
"readout",
@@ -211,7 +209,19 @@ def add_spine_commands(subparsers) -> None:
def run_spine_command(args: argparse.Namespace) -> int:
- """Run a ``giant spine`` subcommand; print a JSON report."""
+ """Run a giant spine subcommand; print a JSON report.
+
+ Returns
+ -------
+ int
+ Process exit code (0 on success).
+
+ Raises
+ ------
+ ValueError
+ If no valid spine subcommand is given, or images is run without
+ --baseline-dir.
+ """
from .spine.pipeline import make_spine_summary
if args.spine_command == "view":
@@ -223,16 +233,10 @@ def run_spine_command(args: argparse.Namespace) -> int:
return export_html_from_args(args)
if args.spine_command not in ("readout", "images"):
- raise ValueError(
- "give a spine subcommand: readout, images, view or export-html"
- )
+ raise ValueError("give a spine subcommand: readout, images, view or export-html")
if args.spine_command == "images" and args.baseline_dir is None:
raise ValueError("giant spine images needs --baseline-dir")
- paths = (
- [int(x) for x in args.paths.split(",") if x.strip()]
- if args.paths
- else None
- )
+ paths = [int(x) for x in args.paths.split(",") if x.strip()] if args.paths else None
def say(msg: str) -> None:
"""Print a progress line to stderr."""
diff --git a/src/giant_python/export/__init__.py b/src/giant_python/export/__init__.py
index 3d7c32fc..a03ea84a 100644
--- a/src/giant_python/export/__init__.py
+++ b/src/giant_python/export/__init__.py
@@ -1,5 +1,5 @@
"""Exports of SILo runs for other tools.
:mod:`~giant_python.export.f0_training` writes training data for the SLAP2
-F0 network (slap2-F0-network) from a ``giant silo`` run.
+F0 network (slap2-F0-network) from a giant silo run.
"""
diff --git a/src/giant_python/export/f0_events.py b/src/giant_python/export/f0_events.py
index b59a35c0..0ba2215b 100644
--- a/src/giant_python/export/f0_events.py
+++ b/src/giant_python/export/f0_events.py
@@ -1,26 +1,26 @@
"""Event statistics of a SILo run, for simulations matched to a recording.
-Written by ``giant export-f0 --event-stats`` as ``event_statistics.json``
+Written by giant export-f0 --event-stats as event_statistics.json
next to the trial files. Per path:
* per source: position (canvas), footprint width, SNR, kinetics score, its
noise, the number of events and the rate per minute of kept 200 Hz frames,
- the event sizes (the peak of ``dF_denoised`` in each event) in SILo's raw
- units and as dF/F (over ``F0`` at the peak), as quantiles, and the rates at
- other thresholds (``ratesPerMin``: 3, 4, 5, 6 and 8 SDs);
+ the event sizes (the peak of dF_denoised in each event) in SILo's raw
+ units and as dF/F (over F0 at the peak), as quantiles, and the rates at
+ other thresholds (ratesPerMin: 3, 4, 5, 6 and 8 SDs);
* synchrony: for each event, whether another source has an onset within
- ``sync_frames`` 200 Hz frames, against the share expected if sources were
+ sync_frames 200 Hz frames, against the share expected if sources were
independent (each source's own rate);
-* SILo's kinetics constants (``tau_s``, ``tau2_s``) and frame rate.
+* SILo's kinetics constants (tau_s, tau2_s) and frame rate.
-An event is a run of kept 200 Hz frames where ``dF_denoised`` exceeds ``k``
-times the source's noise (the robust SD of ``dF_ls - dF_denoised``), with
-``k`` 6 by default. SILo's ``events`` trace also holds the many small events
-it fits to noise, and ``dF_denoised`` crosses lower thresholds often without
+An event is a run of kept 200 Hz frames where dF_denoised exceeds k
+times the source's noise (the robust SD of dF_ls - dF_denoised), with
+k 6 by default. SILo's events trace also holds the many small events
+it fits to noise, and dF_denoised crosses lower thresholds often without
activity: on the GFP control 847983 (every kept source false) the median
false rate is 62 per minute at 3 SDs (the activity mask's threshold, where
masking noise costs little), 15 at 4, 3 at 5, 0.6 at 6 and 0 at 8. Events
-smaller than ``k`` SDs are not counted: the rates and sizes describe the
+smaller than k SDs are not counted: the rates and sizes describe the
events above the detection limit. Sizes are in SILo's raw units: photons need
the session's gain (the registration statistics' photon model), which this
record does not assume.
@@ -28,18 +28,32 @@
from __future__ import annotations
+from typing import TYPE_CHECKING
+
import numpy as np
from .f0_mask import source_noise
+if TYPE_CHECKING:
+ from ..viewer.run import SiloRun
+
QUANTILES = (0.1, 0.25, 0.5, 0.75, 0.9)
EVENT_K = 6.0
RATE_KS = (3.0, 4.0, 5.0, 6.0, 8.0)
-def events(den: np.ndarray, threshold: float, keep: np.ndarray):
- """``(starts, ends)`` (end exclusive) of the runs of kept frames where
- ``den`` exceeds ``threshold``."""
+def events(den: np.ndarray, threshold: float, keep: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Find the runs of kept frames where den exceeds threshold.
+
+ Return them as (starts, ends) (end exclusive).
+
+ Returns
+ -------
+ starts : np.ndarray
+ Frame index at which each run starts.
+ ends : np.ndarray
+ Frame index at which each run ends (exclusive).
+ """
on = np.isfinite(den) & (den > threshold) & keep
if not on.any():
return np.zeros(0, np.int64), np.zeros(0, np.int64)
@@ -47,9 +61,20 @@ def events(den: np.ndarray, threshold: float, keep: np.ndarray):
return np.flatnonzero(d == 1), np.flatnonzero(d == -1)
-def event_sizes(den: np.ndarray, f0: np.ndarray, starts, ends):
- """Peak of ``dF_denoised`` in each event (raw) and over ``F0`` at the
- peak (dF/F)."""
+def event_sizes(
+ den: np.ndarray, f0: np.ndarray, starts: np.ndarray, ends: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """Peak of dF_denoised in each event, raw and as dF/F.
+
+ The dF/F size is the peak over F0 at the peak.
+
+ Returns
+ -------
+ raw : np.ndarray
+ Peak of den in each event.
+ dff : np.ndarray
+ Peak over F0 at the peak, for the events whose F0 there is finite and positive.
+ """
raw, dff = [], []
for a, b in zip(starts, ends):
k = a + int(np.nanargmax(den[a:b]))
@@ -59,15 +84,28 @@ def event_sizes(den: np.ndarray, f0: np.ndarray, starts, ends):
return np.asarray(raw), np.asarray(dff)
-def _median(x: np.ndarray):
- """Median of the finite values (None without any)."""
+def _median(x: np.ndarray) -> float | None:
+ """Median of the finite values (None without any).
+
+ Returns
+ -------
+ float | None
+ Median of the finite values of x, or None when there are none.
+ """
x = np.asarray(x, np.float64)
x = x[np.isfinite(x)]
return float(np.median(x)) if x.size else None
def _quantiles(x: np.ndarray) -> dict:
- """Quantiles and mean of a sample (empty: None)."""
+ """Quantiles and mean of a sample (empty: None).
+
+ Returns
+ -------
+ dict
+ Finite-value quantiles keyed q10, q25, q50, q75 and q90, plus
+ mean; None when the sample has no finite values.
+ """
x = x[np.isfinite(x)]
if x.size == 0:
return None
@@ -76,14 +114,23 @@ def _quantiles(x: np.ndarray) -> dict:
return out
-def synchrony(trials: list, window: int):
- """Share of events with another source's onset within ``window``
- frames of the same trial, observed and expected for independent
+def synchrony(trials: list, window: int) -> dict[str, float | int | None]:
+ """Share of events with another source's onset within window frames.
+
+ Onsets count within the same trial, observed and expected for independent
sources, both over the partners observed at the event: a source with
no trace there can neither coincide nor count towards chance.
- ``trials``: per trial, ``(starts, observed)`` with each source's onset
+ trials: per trial, (starts, observed) with each source's onset
frames (local to the trial) and its observed frames (bool, kept frames
- with a finite trace)."""
+ with a finite trace).
+
+ Returns
+ -------
+ dict[str, float | int | None]
+ observed (share of events with a coinciding partner onset), expected (the share
+ expected by chance for independent sources) and events (the number of events
+ counted); observed and expected are None when no event could be counted.
+ """
hits, tot, expect = 0, 0, 0.0
w = 2 * int(window) + 1
for starts, observed in trials:
@@ -98,12 +145,7 @@ def synchrony(trials: list, window: int):
i = st + dd
cover[s, i[(i >= 0) & (i < T)]] = True
e = obs.sum(1)
- pr = np.array(
- [
- min(1.0, st.size * w / ee) if ee > 0 else 0.0
- for st, ee in zip(starts, e)
- ]
- )
+ pr = np.array([min(1.0, st.size * w / ee) if ee > 0 else 0.0 for st, ee in zip(starts, e)])
logq = np.log1p(-np.minimum(pr, 1 - 1e-12)) # log(1 - p) per source
for s, st in enumerate(starts):
if st.size == 0:
@@ -123,14 +165,22 @@ def synchrony(trials: list, window: int):
}
-def path_statistics(
- run, d: int, sync_frames: int = 2, k: float = EVENT_K
-) -> dict:
- """Event statistics of path ``d`` (one-based) of a SILo run
- (:class:`~giant_python.viewer.run.SiloRun`); events cross ``k`` noise
- SDs. Events, peaks and synchrony stay within each trial (the traces are
+def path_statistics(run: SiloRun, d: int, sync_frames: int = 2, k: float = EVENT_K) -> dict:
+ """Event statistics of path d (one-based) of a SILo run.
+
+ The run is a :class:`~giant_python.viewer.run.SiloRun`; events cross k
+ noise SDs. Events, peaks and synchrony stay within each trial (the traces are
concatenated trials), and each source's exposure is its kept frames with
- a finite trace."""
+ a finite trace.
+
+ Returns
+ -------
+ dict
+ Path-level fields (path, analyzeHz, tau_s, tau2_s, thresholdSD,
+ keptMinutes, synchronyFrames, synchrony) and sources, one entry per
+ source with its position, noise, observed minutes, event count and rates, and size
+ quantiles. unavailable gives the reason when the run has no dF_denoised traces.
+ """
p = run.path(d)
hz = float(run.param("analyzeHz", 200.0) or 200.0)
out = {
@@ -153,14 +203,8 @@ def path_statistics(
den = tr["dF_denoised"]
f0 = tr["F0"] if "F0" in tr else np.full(den.shape, np.nan, np.float32)
keep = ~np.asarray(p.discard, bool)
- sigma = (
- source_noise(tr["dF_ls"], den, p.discard)
- if "dF_ls" in tr
- else np.full(n, np.nan)
- )
- spans = [
- p.trial_span(t) for t in range(p.n_frames.size) if p.n_frames[t] > 0
- ]
+ sigma = source_noise(tr["dF_ls"], den, p.discard) if "dF_ls" in tr else np.full(n, np.nan)
+ spans = [p.trial_span(t) for t in range(p.n_frames.size) if p.n_frames[t] > 0]
ks = [float(k)] + [kk for kk in RATE_KS if kk != float(k)]
counts = np.zeros((n, len(ks)), np.int64)
exposure = np.zeros(n)
@@ -188,54 +232,50 @@ def path_statistics(
kept_any = keep[: den.shape[0]]
for s in range(n):
minutes = exposure[s] / hz / 60.0
- if (
- not np.isfinite(sigma[s])
- and (np.nan_to_num(den[kept_any, s]) > 0).any()
- ):
+ if not np.isfinite(sigma[s]) and (np.nan_to_num(den[kept_any, s]) > 0).any():
# active without a noise estimate (no finite dF_ls): unavailable,
# not zero events
- out["sources"].append(
- {
- "rc": [float(v) for v in p.sources.rc[s]],
- "width": float(p.sources.width[s]),
- "snr": float(p.sources.snr[s]),
- "kineticScore": float(p.sources.kinetic_score[s]),
- "noise": None,
- "unavailable": "no noise estimate (no finite dF_ls "
- "residuals) for an active source",
- "observedMinutes": float(minutes),
- "events": None,
- "ratePerMin": None,
- "sizeRaw": None,
- "sizeDff": None,
- "ratesPerMin": None,
- "f0Median": _median(f0[keep, s]),
- }
- )
- continue
-
- def rate(c):
- """Events per observed minute (None without observed time)."""
- return float(c / minutes) if minutes > 0 else None
-
- out["sources"].append(
- {
+ out["sources"].append({
"rc": [float(v) for v in p.sources.rc[s]],
"width": float(p.sources.width[s]),
"snr": float(p.sources.snr[s]),
"kineticScore": float(p.sources.kinetic_score[s]),
- "noise": float(sigma[s]),
+ "noise": None,
+ "unavailable": "no noise estimate (no finite dF_ls residuals) for an active source",
"observedMinutes": float(minutes),
- "events": int(counts[s, 0]),
- "ratePerMin": rate(counts[s, 0]),
- "sizeRaw": _quantiles(np.concatenate(raw_all[s] or [[]])),
- "sizeDff": _quantiles(np.concatenate(dff_all[s] or [[]])),
- "ratesPerMin": {
- f"{kk:g}": rate(counts[s, ks.index(kk)]) for kk in RATE_KS
- },
+ "events": None,
+ "ratePerMin": None,
+ "sizeRaw": None,
+ "sizeDff": None,
+ "ratesPerMin": None,
"f0Median": _median(f0[keep, s]),
- }
- )
+ })
+ continue
+
+ def rate(c: float | np.integer) -> float | None:
+ """Events per observed minute (None without observed time).
+
+ Returns
+ -------
+ float | None
+ c divided by the observed minutes, or None when there are none.
+ """
+ return float(c / minutes) if minutes > 0 else None
+
+ out["sources"].append({
+ "rc": [float(v) for v in p.sources.rc[s]],
+ "width": float(p.sources.width[s]),
+ "snr": float(p.sources.snr[s]),
+ "kineticScore": float(p.sources.kinetic_score[s]),
+ "noise": float(sigma[s]),
+ "observedMinutes": float(minutes),
+ "events": int(counts[s, 0]),
+ "ratePerMin": rate(counts[s, 0]),
+ "sizeRaw": _quantiles(np.concatenate(raw_all[s] or [[]])),
+ "sizeDff": _quantiles(np.concatenate(dff_all[s] or [[]])),
+ "ratesPerMin": {f"{kk:g}": rate(counts[s, ks.index(kk)]) for kk in RATE_KS},
+ "f0Median": _median(f0[keep, s]),
+ })
out["keptMinutes"] = float(keep.sum() / hz / 60.0)
out["synchronyFrames"] = int(sync_frames)
out["synchrony"] = synchrony(per_trial, sync_frames)
diff --git a/src/giant_python/export/f0_injected.py b/src/giant_python/export/f0_injected.py
index 36c820d2..caf4e9b7 100644
--- a/src/giant_python/export/f0_injected.py
+++ b/src/giant_python/export/f0_injected.py
@@ -1,46 +1,51 @@
-"""GFP kind of the F0 network's training data: trials of a copy with
-injected events, whose ``activity`` is the injected photons as drawn.
+"""GFP kind of the F0 network's training data.
+
+Trials of a copy with injected events, whose activity is the injected
+photons as drawn.
A copy made by :func:`giant_python.simulation.injection.inject_session`
-and registered (``giant register``) holds the original recording plus
+and registered (giant register) holds the original recording plus
injected events. Its activity here is the copy's raw samples minus the
original's, formed into the copy's registered 80 Hz frames exactly as
-registration forms the movie (kernel ``ceil(line rate / alignHz)`` lines,
-resampling weights from channel 0's valid samples), so that ``movie -
-activity`` is the original recording on the copy's grid, noise included:
+registration forms the movie (kernel ceil(line rate / alignHz) lines,
+resampling weights from channel 0's valid samples), so that movie -
+activity is the original recording on the copy's grid, noise included:
the training target is the recording itself and the injected events are in
the input only. No SILo run is involved.
Per trial the file has the layout of :mod:`~giant_python.export.
f0_training` (slap2-f0's reader reads it unchanged), with:
-* ``activity``: the drawn injected photons at every pixel of the crop
+* activity: the drawn injected photons at every pixel of the crop
(activity channel; zero in other written channels);
-* ``activity_expected`` (``expected=True``): the noiseless expectation of
+* activity_expected (expected=True): the noiseless expectation of
this trial's events (footprints rebuilt from the truth; image footprints
cannot be and are refused);
-* ``mask/footprint_support``: pixels within each injected footprint's radius
- plus sqrt(2) px (bilinear interpolation); ``sources/peak_row``, ``_col``:
+* mask/footprint_support: pixels within each injected footprint's radius
+ plus sqrt(2) px (bilinear interpolation); sources/peak_row, _col:
each footprint's peak pixel;
-* attributes ``kind`` = ``gfp_injected``, ``injectionTruth``,
- ``originalTrial``, ``injectedSources``, ``injectedEvents``,
- ``movieDtLines`` (the kernel) and, with the expectation,
- ``drawnOverExpected`` (summed photons over frames whose kernel stays in
+* attributes kind = gfp_injected, injectionTruth,
+ originalTrial, injectedSources, injectedEvents,
+ movieDtLines (the kernel) and, with the expectation,
+ drawnOverExpected (summed photons over frames whose kernel stays in
the trial; 1 within Poisson noise). The SILo QC attributes are NaN.
"""
from __future__ import annotations
+import argparse
import math
import time
+from collections.abc import Callable, Sequence
from dataclasses import asdict, replace
from pathlib import Path
from types import SimpleNamespace
-from typing import Optional
+from typing import TYPE_CHECKING
import numpy as np
from .. import __version__
+from ..io.slap2_raster import RasterLayout
from ..viewer.trial import Session
from .f0_training import (
EXPORTER,
@@ -62,26 +67,44 @@
write_summary,
)
+if TYPE_CHECKING:
+ from ..simulation.injection import GaussianFootprint, InjectionSettings
+
KIND = "gfp_injected"
-def _injection_settings(truth: dict):
- """The truth's :class:`~giant_python.simulation.injection.
- InjectionSettings`."""
+def _injection_settings(truth: dict) -> InjectionSettings:
+ """Build the truth's :class:`~giant_python.simulation.injection.InjectionSettings`.
+
+ Returns
+ -------
+ InjectionSettings
+ The injection settings recorded in truth["settings"].
+ """
from ..simulation import injection as inj
- return inj.InjectionSettings(
- **{
- k: tuple(v) if isinstance(v, list) else v
- for k, v in truth["settings"].items()
- }
- )
+ return inj.InjectionSettings(**{
+ k: tuple(v) if isinstance(v, list) else v for k, v in truth["settings"].items()
+ })
+
+
+def injected_footprints(truth_path: dict, need_model: bool) -> list[GaussianFootprint | None]:
+ """Each injected source's footprint, rebuilt from the truth's recorded parameters (Gaussians).
+ With need_model an image footprint, which the truth keeps only as a
+ sampled patch, is refused.
-def injected_footprints(truth_path: dict, need_model: bool):
- """Each injected source's footprint, rebuilt from the truth's recorded
- parameters (Gaussians); with ``need_model`` an image footprint, which
- the truth keeps only as a sampled patch, is refused."""
+ Returns
+ -------
+ list[GaussianFootprint | None]
+ One footprint per injected source; None for a non-Gaussian footprint when
+ need_model is not set.
+
+ Raises
+ ------
+ ValueError
+ If need_model is set and a footprint is not a Gaussian.
+ """
from ..simulation import injection as inj
out = []
@@ -106,34 +129,55 @@ def injected_footprints(truth_path: dict, need_model: bool):
return out
-def kernel_lines(layout, align_hz: float) -> int:
- """The registration's frame kernel in lines, ``ceil(line rate /
- alignHz)`` (:func:`giant_python.registration.multiroi.open_trial`)."""
- return int(math.ceil((1.0 / layout.line_period_s) / float(align_hz)))
+def kernel_lines(layout: RasterLayout, align_hz: float) -> int:
+ """Return the registration's frame kernel in lines.
+
+ The kernel is ceil(line rate / alignHz)
+ (:func:`giant_python.registration.multiroi.open_trial`).
+
+ Returns
+ -------
+ int
+ The frame kernel, in lines.
+ """
+ return math.ceil((1.0 / layout.line_period_s) / float(align_hz))
def injected_frames(
truth: dict,
- settings,
- copy_alignment,
+ settings: InjectionSettings,
+ copy_alignment: str | Path,
d: int,
t: int,
flat: np.ndarray,
- ds_lines,
+ ds_lines: np.ndarray,
align_hz: float,
device: str = "cpu",
expected: bool = False,
- copy_raw=None,
-):
- """The injected photons of path ``d``, original trial ``t``, as drawn
- (copy minus original raw samples) and, with ``expected``, their
- noiseless expectation (this trial's events), formed into the copy's
- registered frames as registration forms the movie (kernel
+ copy_raw: str | Path | None = None,
+) -> tuple[np.ndarray, np.ndarray | None, tuple[int, int] | None, int]:
+ """Return the injected photons of path d, original trial t, as drawn.
+
+ The photons as drawn (copy minus original raw samples) and, with
+ expected, their noiseless expectation (this trial's events), formed
+ into the copy's registered frames as registration forms the movie (kernel
:func:`kernel_lines`, resampling weights from channel 0's valid
- samples) at the frame lines ``ds_lines``, read at full-frame pixels
- ``flat``. Returns ``(drawn, expected or None, grid, dt)``: ``(frames,
- pixels)`` float32 arrays, the frame grid ``(rows, cols)`` and the
- kernel in lines."""
+ samples) at the frame lines ds_lines, read at full-frame pixels
+ flat. Returns (drawn, expected or None, grid, dt): (frames,
+ pixels) float32 arrays, the frame grid (rows, cols) and the
+ kernel in lines.
+
+ Returns
+ -------
+ drawn : np.ndarray
+ The injected photons as drawn, (frames, pixels) float32.
+ expected : np.ndarray or None
+ Their noiseless expectation, (frames, pixels) float32; None unless expected.
+ grid : tuple[int, int] or None
+ The registered frame grid (rows, cols); None when no frame was formed.
+ dt : int
+ The registration's frame kernel in lines.
+ """
from ..io.slap2_raster import (
INVALID_SAMPLE,
raster_layout,
@@ -164,9 +208,7 @@ def injected_frames(
# behind the DMD curtain where it left them out (see io.slap2_raster)
from ..registration.outputs import unlit_masked
- orig_all = read_raster_samples(
- layout, (c0, c1), mask_unlit=unlit_masked(copy_alignment)
- )
+ orig_all = read_raster_samples(layout, (c0, c1), mask_unlit=unlit_masked(copy_alignment))
orig = orig_all[ch]
new = read_raster_samples(copy, (c0, c1))[ch]
bad = orig == INVALID_SAMPLE
@@ -174,9 +216,7 @@ def injected_frames(
del new
layers = []
if ch != 0: # channel 0's valid samples set the resampling weights
- layers.append(
- np.where(orig_all[0] == INVALID_SAMPLE, INVALID_SAMPLE, 0.0)
- )
+ layers.append(np.where(orig_all[0] == INVALID_SAMPLE, INVALID_SAMPLE, 0.0))
del orig_all
layers.append(np.where(bad, INVALID_SAMPLE, diff))
if expected:
@@ -196,18 +236,12 @@ def injected_frames(
lo, hi = (int(v) for v in detail["lines"])
al_orig = inj.read_alignment(detail["alignment"])
geo = inj.trial_geometry(layout, al_orig, (lo, hi))
- traces = inj.event_traces(
- events, pos.shape[0], (lo, hi), layout.line_period_s, settings
- )
- model = inj.SampleModel(
- layout, geo, pos, fp, traces, settings.photon_scale
- )
+ traces = inj.event_traces(events, pos.shape[0], (lo, hi), layout.line_period_s, settings)
+ model = inj.SampleModel(layout, geo, pos, fp, traces, settings.photon_scale)
exp = np.zeros(orig.shape, np.float32)
for a in range(c0, c1, 128):
cyc = np.arange(a, min(c1, a + 128))
- exp[model.slots[:, None], (cyc - c0)[None, :]] = model.expected(
- cyc
- ).T
+ exp[model.slots[:, None], (cyc - c0)[None, :]] = model.expected(cyc).T
layers.append(np.where(bad, INVALID_SAMPLE, exp))
del exp
del orig, diff
@@ -215,23 +249,27 @@ def injected_frames(
del layers
first = samples.shape[0] - (2 if expected else 1) # the drawn layer
al = inj.read_alignment(copy_alignment)
- out = np.full(
- (samples.shape[0] - first, times.size, flat.size), np.nan, np.float32
- )
+ out = np.full((samples.shape[0] - first, times.size, flat.size), np.nan, np.float32)
grid = None
- for idx, frames, _ in iter_registered_frames(
- copy, samples, c0, al, times, dt, device, 64
- ):
+ for idx, frames, _ in iter_registered_frames(copy, samples, c0, al, times, dt, device, 64):
f = frames.cpu().numpy()[first:]
grid = (f.shape[2], f.shape[3])
out[:, idx] = f.reshape(f.shape[0], f.shape[1], -1)[:, :, flat]
return out[0], (out[1] if expected else None), grid, dt
-def _settings(settings, alignment_file) -> dict:
- """The exporter's frame settings for a copy (SILo's SLAP2 defaults;
- channels and frame rate from the trial's alignment file; the activity
- channel is the injected one)."""
+def _settings(settings: InjectionSettings, alignment_file: str | Path) -> dict:
+ """Return the exporter's frame settings for a copy.
+
+ SILo's SLAP2 defaults; channels and frame rate from the trial's
+ alignment file; the activity channel is the injected one.
+
+ Returns
+ -------
+ dict
+ The frame settings: num_channels, activity_channel (one-based), motion_thresh,
+ discard_initial_s, nan_thresh, ratio, align_hz and photon_scale.
+ """
import h5py
with h5py.File(alignment_file, "r") as f:
@@ -249,22 +287,37 @@ def _settings(settings, alignment_file) -> dict:
}
-def peak_positions(truth_path: dict, pos) -> np.ndarray:
- """Each injected footprint's peak on the copy's grid ``(sources, 2)``:
- its position ``pos`` plus the recorded peak pixel's offset from the
- source (zero for Gaussians; image footprints may peak off centre)."""
+def peak_positions(truth_path: dict, pos: np.ndarray) -> np.ndarray:
+ """Each injected footprint's peak on the copy's grid (sources, 2).
+
+ The peak is its position pos plus the recorded peak pixel's offset
+ from the source (zero for Gaussians; image footprints may peak off centre).
+
+ Returns
+ -------
+ np.ndarray
+ The peak positions on the copy's grid, (sources, 2) float64.
+ """
pos = np.asarray(pos, np.float64).reshape(-1, 2)
- off = np.asarray(truth_path["peak_pixel_rc"], np.float64).reshape(
- -1, 2
- ) - np.asarray(truth_path["positions_rc"], np.float64).reshape(-1, 2)
+ off = np.asarray(truth_path["peak_pixel_rc"], np.float64).reshape(-1, 2) - np.asarray(
+ truth_path["positions_rc"], np.float64
+ ).reshape(-1, 2)
prm = truth_path["footprint"]["params"]
gauss = np.array([q.get("kind") == "gaussian" for q in prm], dtype=bool)
off[gauss] = 0.0
return pos + off
-def _support(pos, radii, crop: tuple, valid_crop) -> np.ndarray:
- """Crop pixels within each injected source's radius (valid ones)."""
+def _support(
+ pos: np.ndarray, radii: Sequence[float], crop: tuple, valid_crop: np.ndarray
+) -> np.ndarray:
+ """Crop pixels within each injected source's radius (valid ones).
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask over the crop, True for valid pixels within any source's radius.
+ """
r0, r1, c0, c1 = crop
qr, qc = np.mgrid[r0:r1, c0:c1]
sup = np.zeros(qr.shape, bool)
@@ -273,8 +326,27 @@ def _support(pos, radii, crop: tuple, valid_crop) -> np.ndarray:
return sup & valid_crop
-def _export_trial(job, truth, settings, t_orig, device, expected):
- """One trial of the GFP kind (see the module's description)."""
+def _export_trial(
+ job: TrialJob,
+ truth: dict,
+ settings: InjectionSettings,
+ t_orig: int,
+ device: str,
+ expected: bool,
+) -> dict:
+ """One trial of the GFP kind (see the module's description).
+
+ Returns
+ -------
+ dict
+ The trial's record (as written to the summary), with drawnOverExpected when
+ expected is set.
+
+ Raises
+ ------
+ TrialSkipped
+ If the copy's frame grid differs from the movie's.
+ """
st = job.settings
stack, al, disc, valid = _load(job)
T, _, R, C = stack.shape
@@ -302,9 +374,7 @@ def _export_trial(job, truth, settings, t_orig, device, expected):
job.provenance.get("copy_raw"),
)
if tuple(grid) != (R, C):
- raise TrialSkipped(
- f"copy frames {grid} differ from the movie's {(R, C)}"
- )
+ raise TrialSkipped(f"copy frames {grid} differ from the movie's {(R, C)}")
chans = list(job.options.channels or (ach,))
act = arrays["activity"]
for i, ch in enumerate(chans): # every occurrence of the injected one
@@ -312,9 +382,7 @@ def _export_trial(job, truth, settings, t_orig, device, expected):
act[i] = np.nan_to_num(drawn).reshape(T, r1 - r0, c1 - c0)
if exp is not None:
arrays["activity_expected"] = (
- np.nan_to_num(exp)
- .reshape(1, T, r1 - r0, c1 - c0)
- .astype(np.float32)
+ np.nan_to_num(exp).reshape(1, T, r1 - r0, c1 - c0).astype(np.float32)
)
pth = truth["paths"][job.path]
detail = pth["trials_detail"][t_orig]
@@ -324,9 +392,7 @@ def _export_trial(job, truth, settings, t_orig, device, expected):
# each footprint's extent plus sqrt(2) px: bilinear interpolation
# reaches the diagonal neighbours
radii = [float(q["radius_px"]) + math.sqrt(2.0) for q in prm]
- arrays["mask/footprint_support"] = _support(pos, radii, crop, vc).astype(
- np.uint8
- )
+ arrays["mask/footprint_support"] = _support(pos, radii, crop, vc).astype(np.uint8)
peak = peak_positions(pth, pos)
pr, pc = np.rint(peak[:, 0]).astype(int), np.rint(peak[:, 1]).astype(int)
inside = (pr >= r0) & (pr < r1) & (pc >= c0) & (pc < c1)
@@ -354,21 +420,25 @@ def _export_trial(job, truth, settings, t_orig, device, expected):
inner = (ds - reach > lo) & (ds + reach < hi)
ok = np.isfinite(drawn) & np.isfinite(exp) & (~disc & inner)[:, None]
e = float(exp[ok].sum())
- q["drawnOverExpected"] = (
- float(drawn[ok].sum()) / e if e > 0 else np.nan
- )
+ q["drawnOverExpected"] = float(drawn[ok].sum()) / e if e > 0 else np.nan
attrs = {k: _attr_value(v) for k, v in q.items() if k != "file"}
_write(job, arrays, attrs)
return q
-def _reconcile(out_dir: Path, d: int, present, summary, label, log):
- """Remove the path's earlier trial files a default export does not
- write (the reader finds files, not summaries); record them."""
- jobs = [
- SimpleNamespace(out_file=out_dir / f"Path{d}" / f"trial_{k:03d}.h5")
- for k in present
- ]
+def _reconcile(
+ out_dir: Path,
+ d: int,
+ present: Sequence[int],
+ summary: dict,
+ label: str,
+ log: Callable[[str], None],
+) -> None:
+ """Remove the path's earlier trial files a default export does not write.
+
+ The reader finds files, not summaries; record them.
+ """
+ jobs = [SimpleNamespace(out_file=out_dir / f"Path{d}" / f"trial_{k:03d}.h5") for k in present]
removed = _remove_unscheduled(out_dir, d, jobs)
if removed:
summary.setdefault("removed", {})[f"Path{d}"] = removed
@@ -378,9 +448,24 @@ def _reconcile(out_dir: Path, d: int, present, summary, label, log):
)
-def _run_trial(job, truth, settings, t_orig, device, expected) -> dict:
- """One trial's record (``error`` instead when it was not exported; a
- failed trial loses its earlier file)."""
+def _run_trial(
+ job: TrialJob,
+ truth: dict,
+ settings: InjectionSettings,
+ t_orig: int,
+ device: str,
+ expected: bool,
+) -> dict:
+ """One trial's record.
+
+ The record has error instead when the trial was not exported; a
+ failed trial loses its earlier file.
+
+ Returns
+ -------
+ dict
+ The trial's record, with seconds when exported or error when not.
+ """
t0 = time.time()
try:
q = _export_trial(job, truth, settings, t_orig, device, expected)
@@ -393,9 +478,23 @@ def _run_trial(job, truth, settings, t_orig, device, expected) -> dict:
return q
-def _selection(options, truth: dict, originals: list) -> tuple:
- """The copy's paths and trial columns to export, each once; refuses
- numbers the copy does not have."""
+def _selection(options: ExportOptions, truth: dict, originals: list) -> tuple:
+ """Return the copy's paths and trial columns to export, each once.
+
+ Refuses numbers the copy does not have.
+
+ Returns
+ -------
+ paths : list[int]
+ The copy's one-based paths to export, sorted.
+ cols : list[int]
+ The copy's one-based trial columns to export, sorted.
+
+ Raises
+ ------
+ ValueError
+ If a requested path or trial is not among the copy's.
+ """
paths = sorted(int(d) for d in truth["paths"])
if options.paths:
bad = sorted(set(options.paths) - set(paths))
@@ -412,38 +511,39 @@ def _selection(options, truth: dict, originals: list) -> tuple:
def export_injected(
- copy_dir,
- out_dir,
- options: Optional[ExportOptions] = None,
+ copy_dir: str | Path,
+ out_dir: str | Path,
+ options: ExportOptions | None = None,
device: str = "cpu",
expected: bool = False,
- log=print,
+ log: Callable[[str], None] = print,
) -> dict:
- """Export a registered injected copy as the GFP kind of F0 training
- data (see the module's description).
+ """Export a registered injected copy as the GFP kind of F0 training data.
+
+ See the module's description.
Parameters
----------
copy_dir : str or Path
- The copy's folder: ``trial_table.h5`` (registered), ``raw/``,
- ``motion_correction/`` and ``injection_truth.h5``.
+ The copy's folder: trial_table.h5 (registered), raw/,
+ motion_correction/ and injection_truth.h5.
out_dir : str or Path
- Output folder (``Path/trial_.h5`` numbered by the copy's
- trials, ``export_summary.json``).
+ Output folder (Path/trial_.h5 numbered by the copy's
+ trials, export_summary.json).
options : ExportOptions, optional
- ``channels``, ``var_fac``, ``deflate``, ``label``, ``giant_ref``,
- ``paths`` and ``trials`` (the copy's one-based trials) apply; the
+ channels, var_fac, deflate, label, giant_ref,
+ paths and trials (the copy's one-based trials) apply; the
kernel, placement, blur, mask and event options do not (no SILo).
device : str
- Where the copy's frames are formed (``cpu`` or ``cuda``).
+ Where the copy's frames are formed (cpu or cuda).
expected : bool
- Also write ``activity_expected`` and ``drawnOverExpected``.
+ Also write activity_expected and drawnOverExpected.
log : callable
Returns
-------
dict
- The summary written to ``export_summary.json``.
+ The summary written to export_summary.json.
"""
from ..simulation import injection as inj
@@ -508,9 +608,7 @@ def export_injected(
"copy_raw": str(copy_dir / "raw"),
},
)
- q = _run_trial(
- job, truth, settings, originals[k - 1], device, expected
- )
+ q = _run_trial(job, truth, settings, originals[k - 1], device, expected)
summary["trials"].append(q)
write_summary(out_dir, summary)
log(
@@ -521,8 +619,8 @@ def export_injected(
return summary
-def add_arguments(p) -> None:
- """``giant export-f0-injected``'s arguments."""
+def add_arguments(p: argparse.ArgumentParser) -> None:
+ """Add arguments for giant export-f0-injected."""
p.add_argument(
"copy",
help="the injected copy's folder (trial_table.h5 registered, raw/, "
@@ -552,18 +650,10 @@ def add_arguments(p) -> None:
default="mean",
help="varFacDS: per-pixel mean (default) or every frame",
)
- p.add_argument(
- "--deflate", type=int, default=1, help="HDF5 gzip level (default 1)"
- )
- p.add_argument(
- "--label", default="", help="label (default: the copy's folder name)"
- )
- p.add_argument(
- "--giant-ref", default="", help="GIAnT version or commit (metadata)"
- )
- p.add_argument(
- "--paths", type=int, nargs="+", default=None, help="one-based paths"
- )
+ p.add_argument("--deflate", type=int, default=1, help="HDF5 gzip level (default 1)")
+ p.add_argument("--label", default="", help="label (default: the copy's folder name)")
+ p.add_argument("--giant-ref", default="", help="GIAnT version or commit (metadata)")
+ p.add_argument("--paths", type=int, nargs="+", default=None, help="one-based paths")
p.add_argument(
"--trials",
type=int,
@@ -573,8 +663,14 @@ def add_arguments(p) -> None:
)
-def run_command(args) -> int:
- """Handle ``giant export-f0-injected``; nonzero if any trial failed."""
+def run_command(args: argparse.Namespace) -> int:
+ """Handle giant export-f0-injected; nonzero if any trial failed.
+
+ Returns
+ -------
+ int
+ 1 if any trial failed to export, else 0.
+ """
options = ExportOptions(
channels=tuple(args.channels) if args.channels else None,
var_fac=args.var_fac,
diff --git a/src/giant_python/export/f0_layout.py b/src/giant_python/export/f0_layout.py
index 017dadec..7f524ebe 100644
--- a/src/giant_python/export/f0_layout.py
+++ b/src/giant_python/export/f0_layout.py
@@ -9,7 +9,7 @@
draws raw photon samples and forms frames as the recording's were formed, so
that its noise has each pixel's own sampling. It does not read raw
recordings; this module writes what it needs, one small file per trial and
-imaging path, ``_F0LAYOUT.h5``:
+imaging path, _F0LAYOUT.h5:
* which samples every raw pixel gets (the raster's slots: line within the
cycle, position on the line, pixel, and the slot that shares photon pulses
@@ -27,12 +27,12 @@
registration's movies; it is written for clarity, not speed.
Registrations that undid the online motion correction
-(``compensateOnline``) are supported from version 4 of the file. There a
+(compensateOnline) are supported from version 4 of the file. There a
sample is not placed at its slot's raster pixel but moved by its line's
online offset minus the frame's own (rows follow y, columns x;
:mod:`giant_python.registration.compensation`), so the file also holds the
-offsets of every line of the trial's cycles (``lines/x``, ``lines/y_eff``)
-and each frame's own offset (``frames/ref_xy``).
+offsets of every line of the trial's cycles (lines/x, lines/y_eff)
+and each frame's own offset (frames/ref_xy).
Conventions: arrays as h5py reads them, in NumPy's orientation. Slot lines
and frame lines are one-based, as everywhere in GIAnT; cycles, pixel
@@ -44,20 +44,24 @@
import argparse
import logging
import time
+from collections.abc import Sequence
from pathlib import Path
-from typing import Optional, Sequence, Union
+from typing import TYPE_CHECKING
import h5py
import numpy as np
-from ..io.slap2_raster import INVALID_SAMPLE
+from ..io.slap2_raster import INVALID_SAMPLE, RasterLayout
+
+if TYPE_CHECKING:
+ import torch
log = logging.getLogger(__name__)
LAYOUT_VERSION = 4
"""Version of the file layout. 4: every slot's raster position
-(``slots/row``, ``slots/col``); registrations with online compensation
-(``lines/x``, ``lines/y_eff``, ``frames/ref_xy``, ``y_lead``)."""
+(slots/row, slots/col); registrations with online compensation
+(lines/x, lines/y_eff, frames/ref_xy, y_lead)."""
READABLE_VERSIONS = (3, 4)
"""Versions :func:`read_layout` reads. A version 3 file (registrations
@@ -65,16 +69,16 @@
list."""
HEIGHT_BINS = 1024
-"""Bins of the pulse-height histograms: heights 1 .. ``HEIGHT_BINS`` raw
+"""Bins of the pulse-height histograms: heights 1 .. HEIGHT_BINS raw
units, the last bin holding every larger one."""
SPLIT_BINS = 20
"""Bins of the split-fraction histogram over (0, 1)."""
JOINT_BINS = 64
-"""Height bins of the joint histogram of split pulses: bin ``i`` holds the
-heights ``i * HEIGHT_BINS / JOINT_BINS + 1 .. (i + 1) * HEIGHT_BINS /
-JOINT_BINS`` (16 raw units each), the last one every larger height."""
+"""Height bins of the joint histogram of split pulses: bin i holds the
+heights i * HEIGHT_BINS / JOINT_BINS + 1 .. (i + 1) * HEIGHT_BINS /
+JOINT_BINS (16 raw units each), the last one every larger height."""
DIM_ZERO_SHARE = 0.95
"""A pair of consecutive samples counts as dim when both are zero in at
@@ -147,7 +151,7 @@
_REGISTERED = "_REGISTERED_DOWNSAMPLED-"
-def sharing_slots(layout) -> tuple:
+def sharing_slots(layout: RasterLayout) -> tuple:
"""Which consecutive samples share photon pulses.
A pulse on the boundary between two consecutive samples of a line is
@@ -172,7 +176,7 @@ def sharing_slots(layout) -> tuple:
Whether nothing precedes, or follows, the slot that could share a
pulse with it: it starts or ends its line, or the scan jumps there.
A slot beside a sample that is not a raster slot (a gap in
- ``slot_pos``) is neither: that sample is not seen.
+ slot_pos) is neither: that sample is not seen.
"""
from ..registration.stats.gain import next_slots
@@ -190,12 +194,17 @@ def sharing_slots(layout) -> tuple:
return np.where(jump, -1, nxt), start, end
-def layout_path(movie_path: Union[str, Path]) -> Path:
- """The layout file of a registered movie.
+def layout_path(movie_path: str | Path) -> Path:
+ """Return the layout file of a registered movie.
+
+ _REGISTERED_DOWNSAMPLED-80Hz.h5 (or .tif) gives
+ _F0LAYOUT.h5 in the same folder; any other name
+ _F0LAYOUT.h5.
- ``_REGISTERED_DOWNSAMPLED-80Hz.h5`` (or ``.tif``) gives
- ``_F0LAYOUT.h5`` in the same folder; any other name
- ``_F0LAYOUT.h5``.
+ Returns
+ -------
+ Path
+ The layout file, in the movie's folder.
"""
p = Path(movie_path)
if _REGISTERED in p.name:
@@ -203,20 +212,20 @@ def layout_path(movie_path: Union[str, Path]) -> Path:
return p.with_name(f"{p.stem}_F0LAYOUT.h5")
-def slot_statistics(samples) -> dict:
+def slot_statistics(samples: torch.Tensor) -> dict:
"""Mean and share of zeros of every slot.
Parameters
----------
samples : torch.Tensor of int16
- ``(channels, slots, cycles)`` raw samples, -32768 where invalid.
+ (channels, slots, cycles) raw samples, -32768 where invalid.
Returns
-------
dict
- ``mean`` and ``zero_share`` ``(channels, slots)`` float32 over each
- slot's valid samples (NaN without any) and ``valid_share``
- ``(channels, slots)`` float32.
+ mean and zero_share (channels, slots) float32 over each
+ slot's valid samples (NaN without any) and valid_share
+ (channels, slots) float32.
"""
import torch
@@ -246,16 +255,18 @@ def slot_statistics(samples) -> dict:
return out
-def pulse_statistics(samples, nxt: np.ndarray, line_end=None) -> dict:
+def pulse_statistics(
+ samples: torch.Tensor, nxt: np.ndarray, line_end: np.ndarray | None = None
+) -> dict:
"""Single-photon pulses measured on dim pairs of consecutive samples.
A photon's pulse falls into one sample, or is split between a sample
- and the next one on its line. For a pair of consecutive slots ``(a,
- b)`` that is dim (:data:`DIM_ZERO_SHARE`), a cycle in which ``a`` is
- non-zero, while the samples before ``a`` and after ``b`` on the line
- are zero, holds one whole event that arrived in ``a``: its height is
- ``x_a + x_b``, and it is split when ``b`` is non-zero too, by the
- fraction ``x_a / (x_a + x_b)``. Only the events of the earlier slot are
+ and the next one on its line. For a pair of consecutive slots (a,
+ b) that is dim (:data:`DIM_ZERO_SHARE`), a cycle in which a is
+ non-zero, while the samples before a and after b on the line
+ are zero, holds one whole event that arrived in a: its height is
+ x_a + x_b, and it is split when b is non-zero too, by the
+ fraction x_a / (x_a + x_b). Only the events of the earlier slot are
counted: one of the later slot that is split leaves the pair. The
share of split events among the counted ones is therefore the
probability that an event reaches into the next sample, whatever the
@@ -269,18 +280,18 @@ def pulse_statistics(samples, nxt: np.ndarray, line_end=None) -> dict:
more than chance coincidences; they carry most of the covariance of
consecutive samples.
- The sample before ``a`` must be a slot: where a run of samples starts
+ The sample before a must be a slot: where a run of samples starts
(the line's first sample, or after a jump of the scan) the sample
before it is not recorded but still passes parts of its pulses on, and
- they would be counted as small pulses of ``a``. The sample after ``b``
- must be a slot or not exist (``b`` ends its run): a line can hold
+ they would be counted as small pulses of a. The sample after b
+ must be a slot or not exist (b ends its run): a line can hold
samples that are not raster slots, and a pulse split with one would be
counted truncated.
Parameters
----------
samples : torch.Tensor of int16
- ``(channels, slots, cycles)`` raw samples of all slots of the lines
+ (channels, slots, cycles) raw samples of all slots of the lines
concerned, -32768 where invalid.
nxt : ndarray of int
Each slot's next slot on its line, -1 for none
@@ -295,24 +306,24 @@ def pulse_statistics(samples, nxt: np.ndarray, line_end=None) -> dict:
Returns
-------
dict
- Per channel: ``height_single`` and ``height_split`` ``(channels,
- HEIGHT_BINS)`` int64 histograms of the heights of the unsplit and
- the split events of the pairs' earlier slots, ``split_fraction``
- ``(channels, SPLIT_BINS)`` int64, ``split_joint`` ``(channels,
- JOINT_BINS, SPLIT_BINS)`` int64 (split events by height and
+ Per channel: height_single and height_split (channels,
+ HEIGHT_BINS) int64 histograms of the heights of the unsplit and
+ the split events of the pairs' earlier slots, split_fraction
+ (channels, SPLIT_BINS) int64, split_joint (channels,
+ JOINT_BINS, SPLIT_BINS) int64 (split events by height and
fraction; its sums over either axis are the two histograms before),
- ``pairs`` (dim pairs used) and ``pair_cycles`` (their cycles in
- which the pair was isolated), each ``(channels,)``. Without dim
+ pairs (dim pairs used) and pair_cycles (their cycles in
+ which the pair was isolated), each (channels,). Without dim
pairs the histograms are empty: the recording's pulses cannot be
measured this way, and brighter pairs, in which unrelated pulses
often coincide, are not used instead. Among the counted events, the
share that are two unrelated pulses is about the pulse rate per
- pair cycle, ``(sum(height_single) + sum(height_split)) /
- pair_cycles``.
+ pair cycle, (sum(height_single) + sum(height_split)) /
+ pair_cycles.
"""
import torch
- n_ch, n_slots, n_cycles = samples.shape
+ n_ch, n_slots, _n_cycles = samples.shape
nxt = np.asarray(nxt, dtype=np.int64)
first = np.flatnonzero(nxt >= 0)
second = nxt[first]
@@ -338,9 +349,16 @@ def pulse_statistics(samples, nxt: np.ndarray, line_end=None) -> dict:
return out
dev = samples.device
- def rows(ch, idx):
- """Samples of slots ``idx`` (zeros and valid where ``idx`` is -1:
- no neighbour on the line)."""
+ def rows(ch: int, idx: np.ndarray) -> torch.Tensor:
+ """Return the samples of slots idx.
+
+ Zeros and valid where idx is -1: no neighbour on the line.
+
+ Returns
+ -------
+ torch.Tensor
+ The samples of those slots in channel ch, (len(idx), cycles).
+ """
x = samples[ch, torch.from_numpy(np.maximum(idx, 0)).to(dev)]
none = torch.from_numpy(idx < 0).to(dev)[:, None]
return torch.where(none, torch.zeros_like(x), x)
@@ -356,21 +374,14 @@ def rows(ch, idx):
z = (ok & (xa == 0) & (xb == 0)).sum(1).to(torch.float64)
n_valid[sl] = n.cpu().numpy()
both_zero[sl] = (z / n.clamp(min=1)).cpu().numpy()
- dim = np.flatnonzero(
- (n_valid >= MIN_PAIR_CYCLES) & (both_zero >= DIM_ZERO_SHARE)
- )
+ dim = np.flatnonzero((n_valid >= MIN_PAIR_CYCLES) & (both_zero >= DIM_ZERO_SHARE))
out["pairs"][ch] = dim.size
cycles = 0
for a in range(0, dim.size, PAIR_CHUNK):
sel = dim[a : a + PAIR_CHUNK]
xa, xb = rows(ch, first[sel]), rows(ch, second[sel])
xp, xq = rows(ch, before[sel]), rows(ch, after[sel])
- alone = (
- (xa != INVALID_SAMPLE)
- & (xb != INVALID_SAMPLE)
- & (xp == 0)
- & (xq == 0)
- )
+ alone = (xa != INVALID_SAMPLE) & (xb != INVALID_SAMPLE) & (xp == 0) & (xq == 0)
xa = torch.where(alone, xa, 0).to(torch.int64)
xb = torch.where(alone, xb, 0).to(torch.int64)
height = xa + xb
@@ -382,28 +393,20 @@ def rows(ch, idx):
("height_split", split),
):
h = height[mask].clamp(1, HEIGHT_BINS) - 1
- out[key][ch] += (
- torch.bincount(h, minlength=HEIGHT_BINS).cpu().numpy()
- )
+ out[key][ch] += torch.bincount(h, minlength=HEIGHT_BINS).cpu().numpy()
frac = xa[split].to(torch.float64) / height[split]
bins = (frac * SPLIT_BINS).to(torch.int64).clamp(0, SPLIT_BINS - 1)
- out["split_fraction"][ch] += (
- torch.bincount(bins, minlength=SPLIT_BINS).cpu().numpy()
- )
+ out["split_fraction"][ch] += torch.bincount(bins, minlength=SPLIT_BINS).cpu().numpy()
tall = (height[split].clamp(1, HEIGHT_BINS) - 1) * JOINT_BINS
tall = tall // HEIGHT_BINS
- both = torch.bincount(
- tall * SPLIT_BINS + bins, minlength=JOINT_BINS * SPLIT_BINS
- )
- out["split_joint"][ch] += (
- both.reshape(JOINT_BINS, SPLIT_BINS).cpu().numpy()
- )
+ both = torch.bincount(tall * SPLIT_BINS + bins, minlength=JOINT_BINS * SPLIT_BINS)
+ out["split_joint"][ch] += both.reshape(JOINT_BINS, SPLIT_BINS).cpu().numpy()
out["pair_cycles"][ch] = cycles
return out
def burst_cells(parts: np.ndarray) -> np.ndarray:
- """The type of each burst, for counting how often each type occurs.
+ """Return the type of each burst, for counting how often each type occurs.
A burst of one sample is typed by its total in steps of 10 raw units
(41 bins, the last holding every larger total); a burst of two by its
@@ -416,12 +419,12 @@ def burst_cells(parts: np.ndarray) -> np.ndarray:
Parameters
----------
parts : ndarray
- ``(bursts, length)`` samples of bursts of one length (1-4).
+ (bursts, length) samples of bursts of one length (1-4).
Returns
-------
ndarray of int64
- ``(bursts,)`` cell of each burst.
+ (bursts,) cell of each burst.
"""
parts = np.asarray(parts, dtype=np.float64)
n = parts.shape[1]
@@ -437,8 +440,10 @@ def burst_cells(parts: np.ndarray) -> np.ndarray:
def _keep_bursts(out: dict, ch: int, found: list) -> None:
- """Store up to ``BURST_EXAMPLES`` of the bursts found of each length,
- spread evenly over them, with their cells."""
+ """Store up to BURST_EXAMPLES of the bursts found of each length.
+
+ They are spread evenly over the bursts found, and stored with their cells.
+ """
for n, items in enumerate(found, start=1):
if not items:
continue
@@ -453,9 +458,20 @@ def _keep_bursts(out: dict, ch: int, found: list) -> None:
out["burst_examples"][ch, n - 1] = keep
-def _count_bursts(out, ch, xs, ok, use, edges, found, sums) -> None:
- """Count the bursts of one chunk of chains in the cycles ``use``; the
- chains' levels come from their other cycles."""
+def _count_bursts(
+ out: dict,
+ ch: int,
+ xs: list[torch.Tensor],
+ ok: torch.Tensor,
+ use: torch.Tensor,
+ edges: torch.Tensor,
+ found: list[list],
+ sums: list[np.ndarray],
+) -> None:
+ """Count the bursts of one chunk of chains in the cycles use.
+
+ The chains' levels come from their other cycles.
+ """
import torch
n_s = int(edges.numel())
@@ -471,8 +487,14 @@ def _count_bursts(out, ch, xs, ok, use, edges, found, sums) -> None:
good = ok & use
free = good & (xs[0] == 0)
- def per_stratum(values):
- """Sum the chains' values by stratum."""
+ def per_stratum(values: torch.Tensor) -> np.ndarray:
+ """Sum the chains' values by stratum.
+
+ Returns
+ -------
+ np.ndarray
+ The sum of values over the chains inside each stratum.
+ """
v = values.to(torch.float64).cpu().numpy()
return np.bincount(st[inside], weights=v[inside], minlength=n_s)
@@ -499,10 +521,11 @@ def per_stratum(values):
out["burst_counts"][ch, BURST_MAX] += int(longer.cpu().numpy()[lib].sum())
-def burst_statistics(samples, nxt: np.ndarray) -> dict:
- """The events of a recording: a library of bursts of consecutive
- non-zero samples, and how often each type of burst occurs at different
- brightness.
+def burst_statistics(samples: torch.Tensor, nxt: np.ndarray) -> dict:
+ """Collect the events of a recording.
+
+ The events are a library of bursts of consecutive non-zero samples, and how
+ often each type of burst occurs at different brightness.
The acquisition records an event of the detector as one to a few
consecutive non-zero samples: one pulse, alone or on the boundary of two
@@ -536,28 +559,28 @@ def burst_statistics(samples, nxt: np.ndarray) -> dict:
Parameters
----------
samples : torch.Tensor of int16
- ``(channels, slots, cycles)`` raw samples, -32768 where invalid.
+ (channels, slots, cycles) raw samples, -32768 where invalid.
nxt : ndarray of int
Each slot's sharing partner (:func:`sharing_slots`), -1 for none.
Returns
-------
dict
- ``burst_counts`` ``(channels, BURST_MAX + 1)`` int64: bursts of 1
- to ``BURST_MAX`` samples and longer ones in the chains below
- ``BURST_LEVEL``; ``burst_examples`` ``(channels, BURST_MAX)``
- int64: examples kept of each length; ``burst_1`` ... ``burst_4``:
- ``(channels, BURST_EXAMPLES, length)`` int16, the samples of the
+ burst_counts (channels, BURST_MAX + 1) int64: bursts of 1
+ to BURST_MAX samples and longer ones in the chains below
+ BURST_LEVEL; burst_examples (channels, BURST_MAX)
+ int64: examples kept of each length; burst_1 ... burst_4:
+ (channels, BURST_EXAMPLES, length) int16, the samples of the
kept bursts in scan order, spread evenly over those found (rows
- beyond ``burst_examples`` are 0); ``burst_cell_1`` ...
- ``burst_cell_4``: ``(channels, BURST_EXAMPLES)`` int16, their
- cells; ``strata_edges`` ``(strata + 1,)``; ``strata_free``
- ``(channels, strata)`` int64: samples in which a burst could have
- started (the sample before zero, all six valid); ``strata_mean``
- ``(channels, strata)``: mean sample of the starting slots in the
- counted cycles; ``strata_bursts`` ``(channels, strata, cells)``
- int64: bursts by cell; and ``strata_longer`` ``(channels,
- strata)`` int64: bursts longer than ``BURST_MAX``.
+ beyond burst_examples are 0); burst_cell_1 ...
+ burst_cell_4: (channels, BURST_EXAMPLES) int16, their
+ cells; strata_edges (strata + 1,); strata_free
+ (channels, strata) int64: samples in which a burst could have
+ started (the sample before zero, all six valid); strata_mean
+ (channels, strata): mean sample of the starting slots in the
+ counted cycles; strata_bursts (channels, strata, cells)
+ int64: bursts by cell; and strata_longer (channels,
+ strata) int64: bursts longer than BURST_MAX.
"""
import torch
@@ -592,10 +615,7 @@ def burst_statistics(samples, nxt: np.ndarray) -> dict:
sums = [np.zeros(n_s), np.zeros(n_s)]
for a in range(0, starts.size, PAIR_CHUNK):
sel = starts[a : a + PAIR_CHUNK]
- xs = [
- samples[ch, torch.from_numpy(c[sel]).to(dev)].to(torch.int32)
- for c in chain
- ]
+ xs = [samples[ch, torch.from_numpy(c[sel]).to(dev)].to(torch.int32) for c in chain]
ok = xs[0] != INVALID_SAMPLE
for x in xs[1:]:
ok &= x != INVALID_SAMPLE
@@ -606,27 +626,30 @@ def burst_statistics(samples, nxt: np.ndarray) -> dict:
return out
-def _second_visits(nxt: np.ndarray, pixel: np.ndarray, line: np.ndarray):
- """Chains of a slot and the :data:`LEVEL_LAGS` slots after it, and the
- chains of the same pixels' next visits within the cycle.
+def _second_visits(
+ nxt: np.ndarray, pixel: np.ndarray, line: np.ndarray
+) -> tuple[list[np.ndarray], list[np.ndarray] | None]:
+ """Chains of a slot and the :data:`LEVEL_LAGS` slots after it, and of next visits.
+
+ The second chains are those of the same pixels' next visits within the cycle.
A pixel's next visit is its first one on a later line. Samples of one
line can share detector pulses, so a second sample of the pixel on the
same line is not an independent observation (measured against it, the
shared part of the noise would be taken for brightness).
- A slot whose ``pixel`` is negative is no visit of any pixel: slots of
+ A slot whose pixel is negative is no visit of any pixel: slots of
another plane that sample the same DMD pixels would otherwise stand
between a pixel's visits on this plane.
Returns
-------
chain, other : list of ndarray
- ``chain[k]``: the k-th slot after each starting slot; ``other[k]``:
+ chain[k]: the k-th slot after each starting slot; other[k]:
the slot of that pixel's next visit, the visits forming a chain of
- their own. ``other`` is None where fewer than
+ their own. other is None where fewer than
:data:`MIN_REVISITS` chains are visited again (a raster that
- samples each pixel once per cycle); ``chain`` then holds every
+ samples each pixel once per cycle); chain then holds every
chain.
"""
n = nxt.size
@@ -653,24 +676,23 @@ def _second_visits(nxt: np.ndarray, pixel: np.ndarray, line: np.ndarray):
def level_statistics(
- samples, nxt: np.ndarray, pixel: np.ndarray, line: np.ndarray
+ samples: torch.Tensor, nxt: np.ndarray, pixel: np.ndarray, line: np.ndarray
) -> dict:
- """Variance of a sample and its covariance with the samples after it on
- the line, by local brightness.
+ """Variance of a sample and its covariance with the samples after it on the line.
- With events that add up, both are proportional to the mean. On two
- recordings they rise faster at bright samples (where more than a tenth
- of the samples are non-zero): from the dimmest to the brightest
- samples of 847983, by 3% (variance), a quarter (covariance with the
- next sample) and more beyond. This table records it.
+ Both are taken by local brightness. With events that add up, both are
+ proportional to the mean. On two recordings they rise faster at bright
+ samples (where more than a tenth of the samples are non-zero): from the
+ dimmest to the brightest samples of 847983, by 3% (variance), a quarter
+ (covariance with the next sample) and more beyond. This table records it.
The moments are measured against a second observation of the same
tissue, so that brightness that changes with brain motion does not
count: the next visit of the same pixels within the cycle, on a later
line (some milliseconds later), or, for a raster that samples each
- pixel on one line per cycle, the same slots one cycle later. With ``x``
- and ``y`` the two observations of a slot and of the k-th slot after it,
- the covariance is the mean of ``x0 xk + y0 yk - x0 yk - y0 xk`` over
+ pixel on one line per cycle, the same slots one cycle later. With x
+ and y the two observations of a slot and of the k-th slot after it,
+ the covariance is the mean of x0 xk + y0 yk - x0 yk - y0 xk over
two (the two visits may differ by a constant factor, which is taken
from their means).
Chains are grouped by the mean of their samples over the trial.
@@ -678,7 +700,7 @@ def level_statistics(
Parameters
----------
samples : torch.Tensor of int16
- ``(channels, slots, cycles)`` raw samples, -32768 where invalid.
+ (channels, slots, cycles) raw samples, -32768 where invalid.
nxt : ndarray of int
Each slot's sharing partner (:func:`sharing_slots`), -1 for none.
pixel, line : ndarray of int
@@ -688,13 +710,13 @@ def level_statistics(
Returns
-------
dict
- ``level_edges`` ``(levels + 1,)``; ``level_samples`` ``(channels,
- levels)`` int64: pairs of observations; ``level_mean`` and
- ``level_zero`` ``(channels, levels)``: mean sample and share of
- zeros; ``level_moments`` ``(channels, levels, LEVEL_LAGS + 1)``:
+ level_edges (levels + 1,); level_samples (channels,
+ levels) int64: pairs of observations; level_mean and
+ level_zero (channels, levels): mean sample and share of
+ zeros; level_moments (channels, levels, LEVEL_LAGS + 1):
variance of a sample and covariance with the 1st to 8th sample
after it (raw units squared; 0 without samples); and
- ``level_revisits`` (scalar uint8): 1 if the second observation is
+ level_revisits (scalar uint8): 1 if the second observation is
the next visit within the cycle, 0 if the next cycle.
"""
import torch
@@ -749,9 +771,7 @@ def level_statistics(
vals = torch.stack(cols, 1)[good].cpu().numpy()
bins = b[good].cpu().numpy()
for j in range(vals.shape[1]):
- acc[:, j] += np.bincount(
- bins, weights=vals[:, j], minlength=n_l
- )
+ acc[:, j] += np.bincount(bins, weights=vals[:, j], minlength=n_l)
n = np.maximum(acc[:, 0], 1)
out["level_samples"][ch] = acc[:, 0].astype(np.int64)
out["level_mean"][ch] = acc[:, 1] / n
@@ -761,14 +781,14 @@ def level_statistics(
def trial_layout(
- dat: Union[str, Path],
+ dat: str | Path,
first_line: float,
last_line: float,
- adata: Union[str, Path],
- settings: Optional[dict] = None,
+ adata: str | Path,
+ settings: dict | None = None,
device: str = "cpu",
) -> dict:
- """The layout record of one registered trial and path.
+ """Build the layout record of one registered trial and path.
Parameters
----------
@@ -787,7 +807,7 @@ def trial_layout(
Returns
-------
dict
- ``attrs`` and the arrays :func:`write_layout` stores.
+ attrs and the arrays :func:`write_layout` stores.
Raises
------
@@ -795,16 +815,14 @@ def trial_layout(
For a registration whose frame times, window or online compensation
differ from the alignment file's.
"""
- from ..pipeline.reg_stats import _source, read_alignment
- from ..pipeline.reg_stats import registration_params
import torch
+ from ..pipeline.reg_stats import _source, read_alignment, registration_params
+
al = read_alignment(adata)
comp = bool(al["compensated"])
params = registration_params(al, settings)
- layout, source, ds = _source(
- dat, first_line, last_line, al, params, device
- )
+ layout, source, ds = _source(dat, first_line, last_line, al, params, device)
former, win = source.former, source.window
h, w = win.shape
pad_r, pad_c = al["out_shape"][0] - h, al["out_shape"][1] - w
@@ -816,9 +834,7 @@ def trial_layout(
# the raster pixels whose samples the frames use: with compensation
# every pixel of the plane (the window is the raster's extent, and a
# sample may land on another pixel), else those inside the window
- inside = (
- np.arange(former.pixels.size) if comp else source.pixels.cpu().numpy()
- )
+ inside = np.arange(former.pixels.size) if comp else source.pixels.cpu().numpy()
ids = former.pixels[inside] # one-based DMD pixel IDs, ascending
# window positions (zero-based) of those raster pixels
in_rows = former.rows[inside] - (int(win.trim_rows[0]) - 1)
@@ -832,9 +848,7 @@ def trial_layout(
nxt = nxt_all[slots]
nxt = np.where(nxt >= 0, renumber[np.maximum(nxt, 0)], -1)
samples = former._samples
- stats = slot_statistics(
- samples[:, torch.from_numpy(slots).to(samples.device)]
- )
+ stats = slot_statistics(samples[:, torch.from_numpy(slots).to(samples.device)])
shared = np.where(plane, nxt_all, -1)
pulses = pulse_statistics(samples, shared, line_end)
pulses.update(burst_statistics(samples, shared))
@@ -918,8 +932,8 @@ def trial_layout(
}
-def write_layout(path: Union[str, Path], record: dict) -> None:
- """Write a layout record (:func:`trial_layout`) to ``path``.
+def write_layout(path: str | Path, record: dict) -> None:
+ """Write a layout record (:func:`trial_layout`) to path.
The file is written under a temporary name and moved into place.
"""
@@ -946,31 +960,34 @@ def write_layout(path: Union[str, Path], record: dict) -> None:
tmp.unlink()
-def read_layout(path: Union[str, Path]) -> dict:
+def read_layout(path: str | Path) -> dict:
"""Read a layout file.
Returns
-------
dict
- ``attrs`` (dict) and the datasets under their paths
- (``frames/lines`` and so on) as NumPy arrays. A version 3 file is
- returned with ``slots/row`` and ``slots/col`` (its slots' pixels in
+ attrs (dict) and the datasets under their paths
+ (frames/lines and so on) as NumPy arrays. A version 3 file is
+ returned with slots/row and slots/col (its slots' pixels in
its pixel list).
+
+ Raises
+ ------
+ ValueError
+ If the file's layout version is not one of READABLE_VERSIONS.
"""
out = {}
with h5py.File(path, "r") as f:
version = int(f.attrs.get("layout_version", 0))
if version not in READABLE_VERSIONS:
raise ValueError(
- f"{path}: layout version {version}, expected one of "
- f"{READABLE_VERSIONS}"
+ f"{path}: layout version {version}, expected one of {READABLE_VERSIONS}"
)
out["attrs"] = {
- k: (v.item() if isinstance(v, np.generic) else v)
- for k, v in f.attrs.items()
+ k: (v.item() if isinstance(v, np.generic) else v) for k, v in f.attrs.items()
}
- def visit(name, obj):
+ def visit(name: str, obj: h5py.HLObject) -> None:
"""Collect every dataset."""
if isinstance(obj, h5py.Dataset):
out[name] = obj[()]
@@ -983,8 +1000,15 @@ def visit(name, obj):
return out
-def _corner_values(image: np.ndarray, rows: np.ndarray, cols: np.ndarray):
- """``image`` at ``rows`` x ``cols``, NaN outside it."""
+def _corner_values(image: np.ndarray, rows: np.ndarray, cols: np.ndarray) -> np.ndarray:
+ """``image`` at rows x cols, NaN outside it.
+
+ Returns
+ -------
+ np.ndarray
+ The values of image at rows x cols, NaN where a row or column lies outside
+ the image.
+ """
h, w = image.shape
out = image[np.clip(rows, 0, h - 1)][:, np.clip(cols, 0, w - 1)].copy()
out[(rows < 0) | (rows >= h)] = np.nan
@@ -993,23 +1017,23 @@ def _corner_values(image: np.ndarray, rows: np.ndarray, cols: np.ndarray):
def reference_frames(
- layout: dict, samples: np.ndarray, frames: Optional[Sequence[int]] = None
+ layout: dict, samples: np.ndarray, frames: Sequence[int] | None = None
) -> np.ndarray:
- """Registered frames of the samples of a layout file's slots.
+ """Return registered frames of the samples of a layout file's slots.
The definition of the file's contents: each raw pixel's value at a
- frame is the weighted mean of its valid samples within ``reach_lines``
+ frame is the weighted mean of its valid samples within reach_lines
of the frame's line, with weights ``exp(-|line distance| /
kernel_dt_lines)``; the pixel's freshness is the first channel's summed
- weights. A sample belongs to its slot's raster pixel (``slots/row``,
- ``slots/col`` in the window); in a file of a registration with online
- compensation it belongs to that pixel moved by ``(lines/y_eff -
- ref_y, lines/x - ref_x)`` rows and columns, the offsets of its line
- less the frame's own (``frames/ref_xy``), and is left out if that lies
- outside the window. The registered pixel ``(i, j)`` (zero-based, on the
+ weights. A sample belongs to its slot's raster pixel (slots/row,
+ slots/col in the window); in a file of a registration with online
+ compensation it belongs to that pixel moved by (lines/y_eff -
+ ref_y, lines/x - ref_x) rows and columns, the offsets of its line
+ less the frame's own (frames/ref_xy), and is left out if that lies
+ outside the window. The registered pixel (i, j) (zero-based, on the
window
- padded by ``margin``) reads the raw window at ``(i - margin + motion_r,
- j - margin + motion_c)``: the four pixels around that position, each
+ padded by margin) reads the raw window at (i - margin + motion_r,
+ j - margin + motion_c): the four pixels around that position, each
with its bilinear coefficient times its freshness. It is NaN where any
of the four has no valid sample or lies outside the window, and in
frames without motion.
@@ -1019,8 +1043,8 @@ def reference_frames(
layout : dict
A layout file's contents (:func:`read_layout`).
samples : ndarray
- ``(channels, slots, cycles)`` raw values of the file's slots (in
- its order) for the cycles ``cycle0 ... cycle0 + n_cycles - 1``;
+ (channels, slots, cycles) raw values of the file's slots (in
+ its order) for the cycles cycle0 ... cycle0 + n_cycles - 1;
-32768 marks invalid samples.
frames : sequence of int, optional
Zero-based frames to form (default: all).
@@ -1028,8 +1052,8 @@ def reference_frames(
Returns
-------
ndarray of float64
- ``(channels, frames, window_rows + 2 margin, window_cols + 2
- margin)``.
+ (channels, frames, window_rows + 2 margin, window_cols + 2
+ margin).
"""
at = layout["attrs"]
p, dt, reach = (
@@ -1048,7 +1072,7 @@ def reference_frames(
off_x = layout["lines/x"].astype(np.int64)
off_y = layout["lines/y_eff"].astype(np.int64)
ref = layout["frames/ref_xy"].astype(np.int64)
- n_ch, n_slots, n_cycles = samples.shape
+ n_ch, _n_slots, n_cycles = samples.shape
x = np.asarray(samples, dtype=np.float64)
valid = np.asarray(samples) != INVALID_SAMPLE
index = np.arange(lines.size) if frames is None else np.asarray(frames)
@@ -1059,9 +1083,7 @@ def reference_frames(
if not np.all(np.isfinite(motion[i])):
continue
# the cycles with a line in reach, and their samples' weights
- near = np.flatnonzero(
- (cycles * p + p >= t - reach) & (cycles * p + 1 <= t + reach)
- )
+ near = np.flatnonzero((cycles * p + p >= t - reach) & (cycles * p + 1 <= t + reach))
line = cycles[near][None, :] * p + slot_line[:, None] # one-based
dist = np.abs(t - line)
wgt = np.where(dist <= reach, np.exp(-dist / dt), 0.0)
@@ -1111,29 +1133,29 @@ def reference_frames(
def export_layouts(
- trial_table: Union[str, Path],
- out_dir: Optional[Union[str, Path]] = None,
+ trial_table: str | Path,
+ out_dir: str | Path | None = None,
*,
- datadr: Optional[Union[str, Path]] = None,
- moco: Optional[Union[str, Path]] = None,
+ datadr: str | Path | None = None,
+ moco: str | Path | None = None,
device: str = "cpu",
overwrite: bool = False,
- paths: Optional[Sequence[int]] = None,
- trials: Optional[Sequence[int]] = None,
+ paths: Sequence[int] | None = None,
+ trials: Sequence[int] | None = None,
) -> list:
"""Layout files of every registered trial of a trial table.
Parameters
----------
trial_table : str or Path
- A trial table with ``motion_correction`` (it is not changed).
+ A trial table with motion_correction (it is not changed).
out_dir : str or Path, optional
Folder for the files (default: next to each registered movie).
datadr, moco : str or Path, optional
The raw-data folder and the motion-correction folder, if they moved
since the table was written.
device : str
- ``'cpu'`` (default), ``'auto'``, ``'cuda'`` or ``'cuda:N'``: where
+ 'cpu' (default), 'auto', 'cuda' or 'cuda:N': where
each trial's samples are held.
overwrite : bool
Write files that exist again.
@@ -1143,8 +1165,16 @@ def export_layouts(
Returns
-------
list of dict
- Per trial: ``out``, ``error`` (None if written or kept) and
- ``seconds``.
+ Per trial: out, error (None if written or kept) and
+ seconds.
+
+ Raises
+ ------
+ ValueError
+ If the trial table has no slap2_info.
+ FileNotFoundError
+ If a trial's adata file is missing; this is caught and recorded in that
+ trial's error rather than propagated.
"""
from ..io.trial_table import read_trial_table
from ..pipeline.reg_stats import _grid, _selected, _table_settings
@@ -1202,13 +1232,12 @@ def export_layouts(
def add_arguments(parser: argparse.ArgumentParser) -> None:
- """Arguments of ``giant export-f0-layout``."""
+ """Arguments of giant export-f0-layout."""
parser.add_argument("trial_table", help="Path to trial_table.h5.")
parser.add_argument(
"--out",
default=None,
- help="Folder for the layout files (default: next to each "
- "registered movie).",
+ help="Folder for the layout files (default: next to each registered movie).",
)
parser.add_argument(
"--datadr",
@@ -1218,8 +1247,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--moco",
default=None,
- help="Motion-correction folder (default: /"
- "motion_correction).",
+ help="Motion-correction folder (default: /motion_correction).",
)
parser.add_argument(
"--device",
@@ -1241,7 +1269,13 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
def run_command(args: argparse.Namespace) -> int:
- """Handle ``giant export-f0-layout``; nonzero if a trial failed."""
+ """Handle giant export-f0-layout; nonzero if a trial failed.
+
+ Returns
+ -------
+ int
+ Process exit code: 1 if any trial failed, else 0.
+ """
if getattr(args, "verbose", False):
logging.basicConfig(level=logging.INFO)
results = export_layouts(
diff --git a/src/giant_python/export/f0_mask.py b/src/giant_python/export/f0_mask.py
index 80dd1eb7..13603eb2 100644
--- a/src/giant_python/export/f0_mask.py
+++ b/src/giant_python/export/f0_mask.py
@@ -1,34 +1,36 @@
-"""Activity mask of an F0 training trial: where the fine-tuning loss on a
-recording is zeroed because a source may be active.
+"""Activity mask of an F0 training trial.
+
+Where the fine-tuning loss on a recording is zeroed because a source may be
+active.
The mask comes from SILo's source-level fit, not from the pixel's own
-samples (a cut on the samples, such as ``movie > baseline + 2 SD``, keeps
+samples (a cut on the samples, such as movie > baseline + 2 SD, keeps
the samples whose noise happened to be low and biases the kept mean and
variance):
-* **When.** 200 Hz frames where a source's ``dF_denoised`` exceeds ``k``
- times its noise, the robust SD of ``dF_ls - dF_denoised`` over the path's
- kept frames; widened forward by ``widen_tau`` decay constants of the
- activity channel (SILo's ``tau_s``, 24 ms for iGluSnFR4f), moved to the
+* **When.** 200 Hz frames where a source's dF_denoised exceeds k
+ times its noise, the robust SD of dF_ls - dF_denoised over the path's
+ kept frames; widened forward by widen_tau decay constants of the
+ activity channel (SILo's tau_s, 24 ms for iGluSnFR4f), moved to the
nearest 80 Hz frame and widened on both sides by
- ``share_frames`` 80 Hz frames (frames formed from shared samples).
+ share_frames 80 Hz frames (frames formed from shared samples).
* **Where.** The source's footprint support in the trial (as the activity
- is placed) dilated by a disk of ``margin_px``.
-* **Spots without a source** (``spots='seeds'``). Seeds SILo kept no source
+ is placed) dilated by a disk of margin_px.
+* **Spots without a source** (spots='seeds'). Seeds SILo kept no source
for (its plan's seeds without a source, and sources the kinetics test
- rejected): a disk of ``margin_px + 1.5`` px in every frame.
+ rejected): a disk of margin_px + 1.5 px in every frame.
The numbers were chosen on the GFP control 847983 with injected events
-(GIAnT-Python export docs, ``f0_export.rst``).
+(GIAnT-Python export docs, f0_export.rst).
"""
from __future__ import annotations
from dataclasses import dataclass
-from typing import Optional
import numpy as np
-from scipy import ndimage
+from numpy.typing import ArrayLike
+from scipy import ndimage, sparse
SPOT_MODES = ("none", "seeds")
@@ -40,7 +42,7 @@ class MaskRule:
Attributes
----------
k : float
- Threshold on ``dF_denoised`` in units of the source's noise.
+ Threshold on dF_denoised in units of the source's noise.
margin_px : float
Disk dilation of each footprint's support (px).
widen_tau : float
@@ -50,8 +52,8 @@ class MaskRule:
80 Hz frames added on both sides (samples shared by neighbouring
frames).
spots : str
- ``'seeds'`` (mask seeds without a source in every frame) or
- ``'none'``.
+ 'seeds' (mask seeds without a source in every frame) or
+ 'none'.
"""
k: float = 3.0
@@ -61,23 +63,34 @@ class MaskRule:
spots: str = "none"
def check(self) -> None:
- """Refuse an invalid rule."""
+ """Refuse an invalid rule.
+
+ Raises
+ ------
+ ValueError
+ If k, margin_px or widen_tau is not finite and >= 0 (k also > 0),
+ share_frames is not an integer >= 0, or spots is not a known mode.
+ """
for name in ("k", "margin_px", "widen_tau"):
v = float(getattr(self, name))
if not (np.isfinite(v) and v >= 0):
raise ValueError(f"mask {name} {v!r} is not finite and >= 0")
if self.k <= 0:
raise ValueError("mask k must be > 0")
- if (
- int(self.share_frames) != self.share_frames
- or self.share_frames < 0
- ):
+ if int(self.share_frames) != self.share_frames or self.share_frames < 0:
raise ValueError("mask share_frames must be an integer >= 0")
if self.spots not in SPOT_MODES:
raise ValueError(f"mask spots must be one of {SPOT_MODES}")
def attrs(self) -> dict:
- """The rule as trial-file attributes."""
+ """Return the rule as trial-file attributes.
+
+ Returns
+ -------
+ dict
+ The activityMask* attributes (K, MarginPx, WidenTau, ShareFrames
+ and Spots) holding the rule's fields.
+ """
return {
"activityMaskK": float(self.k),
"activityMaskMarginPx": float(self.margin_px),
@@ -88,7 +101,13 @@ def attrs(self) -> dict:
def robust_sd(x: np.ndarray) -> float:
- """1.4826 times the median absolute deviation (NaN ignored)."""
+ """1.4826 times the median absolute deviation (NaN ignored).
+
+ Returns
+ -------
+ float
+ The robust standard deviation of the finite values, or NaN when there are none.
+ """
x = np.asarray(x, np.float64)
x = x[np.isfinite(x)]
if x.size == 0:
@@ -96,16 +115,30 @@ def robust_sd(x: np.ndarray) -> float:
return 1.4826 * float(np.median(np.abs(x - np.median(x))))
-def source_noise(ls: np.ndarray, den: np.ndarray, discard) -> np.ndarray:
- """Each source's noise: the robust SD of ``dF_ls - dF_denoised`` over
- the kept 200 Hz frames of the path (``(frames, sources)`` inputs)."""
+def source_noise(ls: np.ndarray, den: np.ndarray, discard: ArrayLike) -> np.ndarray:
+ """Each source's noise.
+
+ The robust SD of dF_ls - dF_denoised over the kept 200 Hz frames of
+ the path ((frames, sources) inputs).
+
+ Returns
+ -------
+ np.ndarray
+ The robust noise SD of each source, shape (sources,).
+ """
ok = ~np.asarray(discard, bool)
r = np.asarray(ls, np.float64)[ok] - np.asarray(den, np.float64)[ok]
return np.array([robust_sd(r[:, j]) for j in range(r.shape[1])])
-def nearest_frames(ds_lines, lines200) -> np.ndarray:
- """The nearest 80 Hz frame of each 200 Hz frame line."""
+def nearest_frames(ds_lines: ArrayLike, lines200: ArrayLike) -> np.ndarray:
+ """Find the nearest 80 Hz frame of each 200 Hz frame line.
+
+ Returns
+ -------
+ np.ndarray
+ The index of the nearest 80 Hz frame for each 200 Hz frame line, int64.
+ """
ds = np.asarray(ds_lines, np.float64)
x = np.asarray(lines200, np.float64)
if ds.size == 1:
@@ -116,24 +149,35 @@ def nearest_frames(ds_lines, lines200) -> np.ndarray:
def temporal_mask(
- den, sigma, lines200, discard200, ds_lines, rule: MaskRule, tau200
+ den: ArrayLike,
+ sigma: np.ndarray,
+ lines200: ArrayLike,
+ discard200: ArrayLike,
+ ds_lines: ArrayLike,
+ rule: MaskRule,
+ tau200: float,
) -> np.ndarray:
- """``(sources, frames80)`` bool: each source's masked 80 Hz frames.
+ """Mask each source's 80 Hz frames, (sources, frames80) bool.
Parameters
----------
den : ndarray (frames200, sources)
- ``dF_denoised`` of the trial.
+ dF_denoised of the trial.
sigma : ndarray (sources,)
:func:`source_noise`.
lines200, discard200 : ndarray (frames200,)
SILo's frame lines and discarded frames of the trial.
ds_lines : ndarray (frames80,)
- The movie's frame lines (``DSframes``).
+ The movie's frame lines (DSframes).
rule : MaskRule
tau200 : float
The activity channel's decay constant in 200 Hz frames (SILo's
- ``tau_full``, ``tau_s`` times the frame rate).
+ tau_full, tau_s times the frame rate).
+
+ Returns
+ -------
+ np.ndarray
+ The (sources, frames80) bool mask, True where a source's 80 Hz frame is masked.
"""
den = np.nan_to_num(np.asarray(den, np.float64))
n = den.shape[1] if den.ndim == 2 else 0
@@ -161,23 +205,30 @@ def temporal_mask(
def _disk(r: float) -> np.ndarray:
- """A disk structuring element of radius ``r`` px."""
+ """Build a disk structuring element of radius r px.
+
+ Returns
+ -------
+ np.ndarray
+ The (2n + 1, 2n + 1) bool disk, with n = ceil(r).
+ """
n = int(np.ceil(r))
y, x = np.mgrid[-n : n + 1, -n : n + 1]
return (x * x + y * y) <= r * r + 1e-9
def activity_mask(
- H,
- tm: Optional[np.ndarray],
+ H: sparse.spmatrix | None,
+ tm: np.ndarray | None,
shape: tuple,
crop: tuple,
rule: MaskRule,
- spots_rc: Optional[np.ndarray] = None,
+ spots_rc: np.ndarray | None = None,
n_frames: int = 0,
) -> np.ndarray:
- """The trial's activity mask in the crop, ``(frames, rows, cols)``
- uint8 (1: the loss is zeroed).
+ """Build the trial's activity mask in the crop.
+
+ (frames, rows, cols) uint8 (1: the loss is zeroed).
Parameters
----------
@@ -186,14 +237,19 @@ def activity_mask(
tm : ndarray (sources, frames) or None
:func:`temporal_mask`.
shape : tuple
- ``(rows, cols)`` of the trial frame.
+ (rows, cols) of the trial frame.
crop : tuple
- ``(r0, r1, c0, c1)`` of the written arrays.
+ (r0, r1, c0, c1) of the written arrays.
rule : MaskRule
spots_rc : ndarray (m, 2), optional
Seeds without a source in the trial frame (NaN rows ignored).
n_frames : int
Frames when there is no temporal mask.
+
+ Returns
+ -------
+ np.ndarray
+ The (frames, rows, cols) uint8 mask in the crop (1: the loss is zeroed).
"""
R, C = shape
r0, r1, c0, c1 = crop
@@ -220,9 +276,7 @@ def activity_mask(
rr, cc = rr + a0, cc + b0
ok = (rr >= r0) & (rr < r1) & (cc >= c0) & (cc < c1)
if ok.any(): # every masked frame x every pixel of the disk
- out[
- fr[:, None], (rr[ok] - r0)[None, :], (cc[ok] - c0)[None, :]
- ] = 1
+ out[fr[:, None], (rr[ok] - r0)[None, :], (cc[ok] - c0)[None, :]] = 1
if rule.spots == "seeds" and spots_rc is not None and len(spots_rc):
qr, qc = np.mgrid[r0:r1, c0:c1]
hit = np.zeros(qr.shape, bool)
diff --git a/src/giant_python/export/f0_qc.py b/src/giant_python/export/f0_qc.py
index 3487fd94..f5b8e3e4 100644
--- a/src/giant_python/export/f0_qc.py
+++ b/src/giant_python/export/f0_qc.py
@@ -1,28 +1,31 @@
-"""Quality values of an F0 training trial: how the rendered activity
-compares with the movie.
+"""Quality values of an F0 training trial.
-Ports of the QC in slap2-F0-network's ``exportF0TrainingData.m``
-(``peakFit``, ``diskFit``, ``shapeFit``, the event-triggered residual) and
-of its ``ringEventRatios.m`` (reference: ``slap2_f0.ringqc``). The values
+How the rendered activity compares with the movie.
+
+Ports of the QC in slap2-F0-network's exportF0TrainingData.m
+(peakFit, diskFit, shapeFit, the event-triggered residual) and
+of its ringEventRatios.m (reference: slap2_f0.ringqc). The values
are written as the trial file's attributes under the MATLAB names
-(``peakSlope``, ``peakR``, ``diskSlope``, ``diskR``, ``activitySlope``,
-``blurShapeRatio``, ``eventResidualFraction``, ``nEvents``,
-``eventRatioCore``, ``eventRatio2px``, ``eventRatioSources``,
-``eventRatioEvents``, ``eventRatioArtifactSources``), so that QC tables of
+(peakSlope, peakR, diskSlope, diskR, activitySlope,
+blurShapeRatio, eventResidualFraction, nEvents,
+eventRatioCore, eventRatio2px, eventRatioSources,
+eventRatioEvents, eventRatioArtifactSources), so that QC tables of
old and new exports line up.
-Conventions: the movie ``Y`` is ``(frames, pixels)`` over the trial's
+Conventions: the movie Y is (frames, pixels) over the trial's
row-major flat pixels, NaN where a pixel is not imaged and at discarded
-frames; footprints ``H`` are a sparse ``(pixels, sources)`` matrix and the
-sources' 80 Hz traces ``X`` are ``(sources, frames)``.
+frames; footprints H are a sparse (pixels, sources) matrix and the
+sources' 80 Hz traces X are (sources, frames).
"""
from __future__ import annotations
import warnings
+from collections.abc import Callable
from dataclasses import dataclass
import numpy as np
+from scipy import sparse
from scipy.ndimage import median_filter
from ..extraction.raster.localization import matlab_prctile
@@ -31,10 +34,15 @@
def movmedian_omitnan(x: np.ndarray, width: int = HPF_WIDTH) -> np.ndarray:
- """MATLAB ``movmedian(x, width, 2, 'omitnan')`` (endpoints shrink).
+ """MATLAB movmedian(x, width, 2, 'omitnan') (endpoints shrink).
- Each row's running median over ``width`` frames (odd), NaN left out;
+ Each row's running median over width frames (odd), NaN left out;
NaN where a window holds no value.
+
+ Returns
+ -------
+ np.ndarray
+ The running medians, same shape as x (at least 2-D).
"""
x = np.atleast_2d(np.asarray(x, dtype=np.float64))
h = width // 2
@@ -51,32 +59,63 @@ def movmedian_omitnan(x: np.ndarray, width: int = HPF_WIDTH) -> np.ndarray:
def hpf(x: np.ndarray) -> np.ndarray:
- """The rows minus their 81-frame running median (the fits' high
- pass)."""
+ """Subtract from the rows their 81-frame running median.
+
+ This is the fits' high pass.
+
+ Returns
+ -------
+ np.ndarray
+ The high-passed rows, same shape as x (at least 2-D).
+ """
x = np.atleast_2d(np.asarray(x, dtype=np.float64))
return x - movmedian_omitnan(x)
def _slope(yh: np.ndarray, ah: np.ndarray) -> float:
- """Least-squares slope of ``yh`` on ``ah`` over frames where both are
- finite (NaN when ``ah`` is zero there)."""
+ """Least-squares slope of yh on ah over frames where both are finite.
+
+ NaN when ah is zero there.
+
+ Returns
+ -------
+ float
+ The slope; NaN when ah is zero over the finite frames.
+ """
ok = np.isfinite(yh) & np.isfinite(ah)
den = float(np.sum(ah[ok] ** 2))
return float(np.sum(yh[ok] * ah[ok]) / den) if den > 0 else np.nan
def _corr(yh: np.ndarray, ah: np.ndarray, min_frames: int = 100) -> float:
- """Correlation over frames where both are finite (NaN with ``min_frames``
- or fewer, or a constant activity)."""
+ """Correlation over frames where both are finite.
+
+ NaN with min_frames or fewer, or a constant activity.
+
+ Returns
+ -------
+ float
+ The correlation coefficient; NaN with min_frames or fewer frames, or a constant
+ activity.
+ """
ok = np.isfinite(yh) & np.isfinite(ah)
if ok.sum() <= min_frames or np.std(ah[ok]) == 0:
return np.nan
return float(np.corrcoef(yh[ok], ah[ok])[0, 1])
-def peak_pixels(H) -> np.ndarray:
- """Each source's peak pixel (flat index of its largest footprint
- value; -1 for a source without footprint pixels)."""
+def peak_pixels(H: sparse.spmatrix) -> np.ndarray:
+ """Each source's peak pixel.
+
+ The flat index of its largest footprint value; -1 for a source without
+ footprint pixels.
+
+ Returns
+ -------
+ np.ndarray
+ The flat pixel index of each source's peak (int64, length sources); -1 for a source
+ without footprint pixels.
+ """
H = H.tocsc()
pk = np.full(H.shape[1], -1, np.int64)
for s in range(H.shape[1]):
@@ -86,11 +125,22 @@ def peak_pixels(H) -> np.ndarray:
return pk
-def peak_fit(H, X: np.ndarray, Y: np.ndarray, pk: np.ndarray):
- """Slope and correlation of the movie on the activity at each source's
- peak pixel (high-passed), with every source's activity at that pixel
- (``peakFit``). Returns two arrays of length ``sources`` (NaN for a
- source without pixels)."""
+def peak_fit(
+ H: sparse.spmatrix, X: np.ndarray, Y: np.ndarray, pk: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """Slope and correlation of the movie on the activity at each source's peak pixel.
+
+ High-passed, with every source's activity at that pixel (peakFit).
+ Returns two arrays of length sources (NaN for a source without
+ pixels).
+
+ Returns
+ -------
+ slope : np.ndarray
+ The slope per source (NaN for a source without pixels).
+ corr : np.ndarray
+ The correlation per source (NaN for a source without pixels).
+ """
n = pk.size
sl, r = np.full(n, np.nan), np.full(n, np.nan)
ok = pk >= 0
@@ -103,10 +153,21 @@ def peak_fit(H, X: np.ndarray, Y: np.ndarray, pk: np.ndarray):
return sl, r
-def _flux_fit(H, X, Y, idx):
- """Slope and correlation of the movie's flux over pixels ``idx`` on the
- activity's (high-passed; the movie's flux is NaN at a frame where any
- of the pixels is)."""
+def _flux_fit(
+ H: sparse.spmatrix, X: np.ndarray, Y: np.ndarray, idx: np.ndarray
+) -> tuple[float, float]:
+ """Slope and correlation of the movie's flux over pixels idx on the activity's.
+
+ High-passed; the movie's flux is NaN at a frame where any of the pixels
+ is.
+
+ Returns
+ -------
+ slope : float
+ The slope of the movie's flux on the activity's.
+ corr : float
+ Their correlation; NaN for both when there is no activity or 100 frames or fewer.
+ """
fy = Y[:, idx].astype(np.float64).sum(1)
fa = np.asarray(H[idx].sum(0)).ravel() @ X
yh, ah = hpf(fy)[0], hpf(fa)[0]
@@ -118,10 +179,26 @@ def _flux_fit(H, X, Y, idx):
return _slope(yh, ah), _corr(yh, ah)
-def disk_fit(H, X, Y, pk, shape, radius: float = 4.0):
- """Slope and correlation of the movie on the activity for the flux in
- the footprint-support pixels within ``radius`` px of each source's
- peak pixel (``diskFit``)."""
+def disk_fit(
+ H: sparse.spmatrix,
+ X: np.ndarray,
+ Y: np.ndarray,
+ pk: np.ndarray,
+ shape: tuple[int, int],
+ radius: float = 4.0,
+) -> tuple[np.ndarray, np.ndarray]:
+ """Slope and correlation of the movie on the activity for the flux near each peak.
+
+ The flux is in the footprint-support pixels within radius px of each
+ source's peak pixel (diskFit).
+
+ Returns
+ -------
+ slope : np.ndarray
+ The slope per source (NaN for a source without a peak pixel or a fit).
+ corr : np.ndarray
+ The correlation per source (NaN for a source without a peak pixel or a fit).
+ """
n = pk.size
sl, r = np.full(n, np.nan), np.full(n, np.nan)
sup = np.flatnonzero(np.asarray(H.getnnz(axis=1)) > 0)
@@ -133,12 +210,22 @@ def disk_fit(H, X, Y, pk, shape, radius: float = 4.0):
return sl, r
-def shape_fit(H, X, Y, valid: np.ndarray, pk: np.ndarray) -> np.ndarray:
- """Per source, the movie-on-activity slope of the flux in the core
- (valid pixels <= 1.5 px from the peak pixel) over that of the flux
- 1.5-3.5 px out (``shapeFit``): above 1 when the activity is broader
- than the movie's events, below 1 when more concentrated; scale-free.
- NaN with fewer than 5 core or 12 outer pixels, or a slope <= 0."""
+def shape_fit(
+ H: sparse.spmatrix, X: np.ndarray, Y: np.ndarray, valid: np.ndarray, pk: np.ndarray
+) -> np.ndarray:
+ """Per source, the core's movie-on-activity flux slope over the outer's.
+
+ The movie-on-activity slope of the flux in the core (valid pixels <= 1.5
+ px from the peak pixel) over that of the flux 1.5-3.5 px out
+ (shapeFit): above 1 when the activity is broader than the movie's
+ events, below 1 when more concentrated; scale-free. NaN with fewer than 5
+ core or 12 outer pixels, or a slope <= 0.
+
+ Returns
+ -------
+ np.ndarray
+ The ratio per source (length sources); NaN where it is not defined.
+ """
R, C = valid.shape
dr, dc = np.mgrid[-3:4, -3:4]
d = np.hypot(dr, dc).ravel()
@@ -162,19 +249,37 @@ def shape_fit(H, X, Y, valid: np.ndarray, pk: np.ndarray) -> np.ndarray:
def _events(x: np.ndarray) -> np.ndarray:
- """Frames of a trace's local maxima above its 99th percentile, with 8
- frames before and 16 after inside the trace."""
+ """Frames of a trace's local maxima above its 99th percentile.
+
+ Only maxima with 8 frames before and 16 after inside the trace.
+
+ Returns
+ -------
+ np.ndarray
+ The frame indices of the events.
+ """
thr = matlab_prctile(x, 99)
m = x[1:-1]
ev = np.flatnonzero((m > thr) & (m >= x[:-2]) & (m > x[2:])) + 1
return ev[(ev >= 8) & (ev <= x.size - 17)]
-def event_residual(H, X, Y, pk):
- """The event-triggered residual at the sources' peak pixels as a
- fraction of the event-triggered movie, events picked on each source's
- own 80 Hz trace (its 99th-percentile local maxima). Near 0 when the
- activity is removed. Returns ``(fraction, events)``."""
+def event_residual(
+ H: sparse.spmatrix, X: np.ndarray, Y: np.ndarray, pk: np.ndarray
+) -> tuple[float, int]:
+ """Compute the event-triggered residual at the sources' peak pixels.
+
+ The residual is a fraction of the event-triggered movie, events picked on
+ each source's own 80 Hz trace (its 99th-percentile local maxima). Near 0
+ when the activity is removed. Returns (fraction, events).
+
+ Returns
+ -------
+ fraction : float
+ The residual fraction; NaN when no event is usable.
+ events : int
+ The number of events averaged.
+ """
eta_y, eta_r, n_ev = np.zeros(25), np.zeros(25), 0
ok = np.flatnonzero(pk >= 0)
if ok.size == 0:
@@ -197,8 +302,10 @@ def event_residual(H, X, Y, pk):
@dataclass
class RingEventRatios:
- """Activity / movie event amplitudes near sources, events picked on
- the movie 3-5 px away (``ringEventRatios.m``)."""
+ """Activity / movie event amplitudes near sources.
+
+ Events picked on the movie 3-5 px away (ringEventRatios.m).
+ """
core: float = np.nan
near: float = np.nan
@@ -212,8 +319,16 @@ class RingEventRatios:
def _ring_events(sel: np.ndarray, discard: np.ndarray) -> list:
- """Ring events: local maxima of the high-passed ring signal above its
- 99th percentile, away from the trial's ends and discarded frames."""
+ """Ring events: local maxima of the high-passed ring signal.
+
+ Maxima above its 99th percentile, away from the trial's ends and
+ discarded frames.
+
+ Returns
+ -------
+ list
+ The frame indices of the ring events.
+ """
filled = np.nan_to_num(sel, nan=np.nanmedian(sel))
sel = sel - median_filter(filled, size=81, mode="nearest")
thr = np.nanpercentile(sel, 99)
@@ -228,10 +343,24 @@ def _ring_events(sel: np.ndarray, discard: np.ndarray) -> list:
]
-def _ring_source(movie, act_at, valid, box, discard, sums):
- """One source's ring events, added to ``sums`` (movie and activity
- amplitude per distance bin); returns the number of events (0 when the
- source does not count)."""
+def _ring_source(
+ movie: np.ndarray,
+ act_at: Callable[[np.ndarray], np.ndarray],
+ valid: np.ndarray,
+ box: tuple[np.ndarray, np.ndarray, np.ndarray],
+ discard: np.ndarray,
+ sums: np.ndarray,
+) -> int:
+ """One source's ring events, added to sums.
+
+ sums holds movie and activity amplitude per distance bin; returns the
+ number of events (0 when the source does not count).
+
+ Returns
+ -------
+ int
+ The number of ring events (0 when the source does not count).
+ """
rows, cols, dist = box
v = valid[rows, cols]
ring = v & (dist >= 3) & (dist <= 5)
@@ -262,22 +391,22 @@ def _ring_source(movie, act_at, valid, box, discard, sums):
def ring_event_ratios(
movie: np.ndarray,
- act_at,
+ act_at: Callable[[np.ndarray], np.ndarray],
mean_act: np.ndarray,
valid: np.ndarray,
pr: np.ndarray,
pc: np.ndarray,
discard: np.ndarray,
) -> RingEventRatios:
- """The selection-safe event ratios of one trial (cropped arrays).
+ """Compute the selection-safe event ratios of one trial (cropped arrays).
Parameters
----------
movie : ndarray (frames, rows, cols)
NaN where not imaged and at discarded frames.
act_at : callable
- ``act_at(flat)`` is the activity at flat pixel indices,
- ``(frames, n)``.
+ act_at(flat) is the activity at flat pixel indices,
+ (frames, n).
mean_act : ndarray (rows, cols)
The activity's time-mean.
valid : ndarray of bool (rows, cols)
@@ -288,7 +417,7 @@ def ring_event_ratios(
Returns
-------
RingEventRatios
- As ``slap2_f0.ringqc.ring_event_ratios`` on the written arrays.
+ As slap2_f0.ringqc.ring_event_ratios on the written arrays.
"""
R, C = valid.shape
discard = np.asarray(discard, bool)
@@ -302,9 +431,7 @@ def ring_event_ratios(
sums = np.zeros((2, 2))
out = RingEventRatios()
for r0, c0 in zip(np.asarray(pr, int), np.asarray(pc, int)):
- if not (
- RING_RAD <= r0 < R - RING_RAD and RING_RAD <= c0 < C - RING_RAD
- ):
+ if not (RING_RAD <= r0 < R - RING_RAD and RING_RAD <= c0 < C - RING_RAD):
continue
if not valid[r0, c0]:
continue
@@ -312,9 +439,7 @@ def ring_event_ratios(
if bad[rows, cols][dist <= 4].any():
out.n_artifact_sources += 1
continue
- n = _ring_source(
- movie, act_at, valid, (rows, cols, dist), discard, sums
- )
+ n = _ring_source(movie, act_at, valid, (rows, cols, dist), discard, sums)
if n:
out.n_sources += 1
out.n_events += n
diff --git a/src/giant_python/export/f0_training.py b/src/giant_python/export/f0_training.py
index 7f53827b..c3be952c 100644
--- a/src/giant_python/export/f0_training.py
+++ b/src/giant_python/export/f0_training.py
@@ -1,43 +1,43 @@
-"""Training data for the SLAP2 F0 network from a ``giant silo`` run.
+"""Training data for the SLAP2 F0 network from a giant silo run.
-The Python counterpart of slap2-F0-network's ``exportF0TrainingData.m``,
-built on the renderer of ``giant view`` (:mod:`giant_python.viewer.render`).
+The Python counterpart of slap2-F0-network's exportF0TrainingData.m,
+built on the renderer of giant view (:mod:`giant_python.viewer.render`).
For every imaging path and every trial that SILo analysed it writes
-``/Path/trial_.h5`` in the layout ``slap2_f0.io.TrialFile``
-reads, plus ``/export_summary.json`` with each trial's QC. Arrays are
+/Path/trial_.h5 in the layout slap2_f0.io.TrialFile
+reads, plus /export_summary.json with each trial's QC. Arrays are
written so that h5py reads them in C order, on the trial's 80 Hz registered
grid cropped to the box around the valid pixels (pixel coordinates zero-based
in the crop, MATLAB's row and column orientation):
-``movie`` (channel, frame, row, col) float32
+movie (channel, frame, row, col) float32
The registered movie, NaN at discarded frames and where not imaged.
-``activity`` (channel, frame, row, col) float32
+activity (channel, frame, row, col) float32
SILo's fitted activity on the same grid and timing; the training target
- is ``movie - activity``. Zero outside the footprints.
-``mean_image`` (channel, row, col) float32
+ is movie - activity. Zero outside the footprints.
+mean_image (channel, row, col) float32
Mean over all frames of each written channel (the MATLAB exporter wrote
- every channel of the file, which the reader indexes like ``movie``).
-``mask/valid``, ``mask/labeled``, ``mask/footprint_support`` (row, col) uint8
- Pixels missing in less than ``nanThresh`` of the frames (motion discards
+ every channel of the file, which the reader indexes like movie).
+mask/valid, mask/labeled, mask/footprint_support (row, col) uint8
+ Pixels missing in less than nanThresh of the frames (motion discards
counted); pixels brighter than 3 x the 25th percentile of the 3 x 3
median-filtered mean image; pixels any source's footprint covers.
-``frame/discard``, ``frame/motion_row``, ``frame/motion_col``,
-``frame/rec_neg_err``, ``frame/onlineMotion{X,Y,Z}shift``,
-``frame/valid_mean`` (frame,)
+frame/discard, frame/motion_row, frame/motion_col,
+frame/rec_neg_err, frame/onlineMotion{X,Y,Z}shift,
+frame/valid_mean (frame,)
Discarded frames (SILo's motion discards and frames whose kernel weight
lies mostly on SILo's discarded 200 Hz frames), the registration's
motion and error, the online motion record, the mean of the valid
pixels.
-``varfac`` (row, col), or (frame, row, col) with ``var_fac="full"``
- SLAP2's variance factor (``slap2/varFacDS``), its per-pixel mean.
-``sources/peak_row``, ``sources/peak_col`` (source,) int32
+varfac (row, col), or (frame, row, col) with var_fac="full"
+ SLAP2's variance factor (slap2/varFacDS), its per-pixel mean.
+sources/peak_row, sources/peak_col (source,) int32
Each kept source's peak pixel in the trial (-1: no footprint there).
The root attributes hold the QC (:mod:`~giant_python.export.f0_qc`) and the
-provenance under the MATLAB exporter's names, plus ``exporter``,
-``exporterVersion``, ``kernel``, ``kernelR``, ``kernelDt200Lines``,
-``alignmentMode``, ``siloRun``, ``baselineSource``, ``baselineFile`` and
-``f0Network`` (SILo's record of the network baseline of the trial).
+provenance under the MATLAB exporter's names, plus exporter,
+exporterVersion, kernel, kernelR, kernelDt200Lines,
+alignmentMode, siloRun, baselineSource, baselineFile and
+f0Network (SILo's record of the network baseline of the trial).
How the activity is rendered, and what differs from the MATLAB exporter:
@@ -46,33 +46,36 @@
(rigid, affine or patchwise; :func:`~giant_python.viewer.render.
place_footprints`), not by an offset searched for the best movie-activity
correlation.
-* **Time.** The 200 Hz traces become 80 Hz frames with the ``exact`` kernel
+* **Time.** The 200 Hz traces become 80 Hz frames with the exact kernel
by default (:func:`~giant_python.viewer.render.exact_weights`); the MATLAB
- exporter's weights (``kernel="exporter"``) smooth fast events twice and
+ exporter's weights (kernel="exporter") smooth fast events twice and
keep 0.93-0.95 of their 80 Hz peak.
-* **Blur.** None by default (a fixed ``blur`` is an option); the MATLAB
+* **Blur.** None by default (a fixed blur is an option); the MATLAB
exporter chose a blur per trial by matching the movie's core and ring
- slopes. ``blurShapeRatio`` still reports that core / ring slope ratio for
+ slopes. blurShapeRatio still reports that core / ring slope ratio for
the activity as written.
-* **Scale.** None: footprints (each summing to 1) times ``dF_denoised``
- (``activityGain`` 1), as the MATLAB exporter now writes it.
+* **Scale.** None: footprints (each summing to 1) times dF_denoised
+ (activityGain 1), as the MATLAB exporter now writes it.
"""
from __future__ import annotations
+import argparse
import json
import math
import re
import time
import warnings
+from collections.abc import Callable, Iterator
from concurrent.futures import ProcessPoolExecutor
from dataclasses import asdict, dataclass, field
from multiprocessing import get_context
from pathlib import Path
-from typing import Optional
import h5py
import numpy as np
+import numpy.typing as npt
+from scipy import sparse
from scipy.ndimage import median_filter
from .. import __version__
@@ -85,7 +88,7 @@
kernel_weights,
place_footprints,
)
-from ..viewer.run import SiloRun
+from ..viewer.run import PathData, SiloRun
from ..viewer.trial import Session, _marker_rc
from . import f0_events, f0_qc
from .f0_mask import MaskRule, activity_mask, source_noise, temporal_mask
@@ -101,18 +104,18 @@ class ExportOptions:
Attributes
----------
kernel : str
- Time kernel (``exact``, ``matched`` or ``exporter``; see
+ Time kernel (exact, matched or exporter; see
:func:`~giant_python.viewer.render.kernel_weights`).
blur : float
Gaussian blur (px) of the moved footprints (0: none).
interp : str
- How footprints are moved into the trial (``linear`` or ``cubic``;
+ How footprints are moved into the trial (linear or cubic;
:func:`~giant_python.viewer.render.place_footprints`).
channels : tuple of int, optional
One-based channels whose movie and activity are written (default:
SILo's activity channel).
var_fac : str
- ``mean`` (per-pixel mean of ``varFacDS``) or ``full`` (every frame).
+ mean (per-pixel mean of varFacDS) or full (every frame).
deflate : int
HDF5 gzip level of the arrays (with shuffle).
label : str
@@ -126,26 +129,26 @@ class ExportOptions:
ignore_sources : bool
Export as if SILo had found no sources (zero activity).
activity_mask : MaskRule, optional
- Write ``mask/activity`` (frames where the fine-tuning loss is
+ Write mask/activity (frames where the fine-tuning loss is
zeroed; :mod:`~giant_python.export.f0_mask`). None: not written.
event_stats : bool
- Write ``event_statistics.json`` (:mod:`~giant_python.export.
+ Write event_statistics.json (:mod:`~giant_python.export.
f0_events`).
"""
kernel: str = "exact"
blur: float = 0.0
interp: str = "linear"
- channels: Optional[tuple] = None
+ channels: tuple | None = None
var_fac: str = "mean"
deflate: int = 1
label: str = ""
giant_ref: str = ""
- paths: Optional[tuple] = None
- trials: Optional[tuple] = None
+ paths: tuple | None = None
+ trials: tuple | None = None
workers: int = 1
ignore_sources: bool = False
- activity_mask: Optional[MaskRule] = None
+ activity_mask: MaskRule | None = None
event_stats: bool = False
@@ -153,9 +156,9 @@ class ExportOptions:
class TrialJob:
"""Everything one trial's export needs (picklable for the workers).
- ``trial`` and ``path`` are one-based. ``x200`` is ``(n200, channels,
- sources)``; ``footprints`` the trial's canvas footprints ``(rows, cols,
- sources, values)``; both None for a path without sources.
+ trial and path are one-based. x200 is (n200, channels,
+ sources); footprints the trial's canvas footprints (rows, cols,
+ sources, values); both None for a path without sources.
"""
path: int
@@ -163,21 +166,21 @@ class TrialJob:
out_file: Path
movie_file: Path
alignment_file: Path
- baseline_file: Optional[Path]
+ baseline_file: Path | None
lines_per_cycle: int
settings: dict
options: ExportOptions
n_sources: int = 0
- footprints: Optional[tuple] = None
- tmap: Optional[TrialMap] = None
- x200: Optional[np.ndarray] = None
- lines200: Optional[np.ndarray] = None
- discard200: Optional[np.ndarray] = None
+ footprints: tuple | None = None
+ tmap: TrialMap | None = None
+ x200: np.ndarray | None = None
+ lines200: np.ndarray | None = None
+ discard200: np.ndarray | None = None
provenance: dict = field(default_factory=dict)
- mask_sigma: Optional[np.ndarray] = None
+ mask_sigma: np.ndarray | None = None
mask_tau200: float = 4.8
mask_tau_seconds: float = 0.024
- spots_rc: Optional[np.ndarray] = None
+ spots_rc: np.ndarray | None = None
spots_unplaced: bool = False
seeds_unknown: bool = False
@@ -187,23 +190,36 @@ class TrialSkipped(RuntimeError):
def _settings(run: SiloRun) -> dict:
- """SILo's frame settings of a run (SILo's SLAP2 defaults)."""
+ """Return SILo's frame settings of a run (SILo's SLAP2 defaults).
+
+ Returns
+ -------
+ dict
+ Channel counts, motion and NaN thresholds, frame-rate ratio, rates and photon
+ scale of the run.
+ """
return {
"num_channels": int(run.param("numChannels", 2)),
"activity_channel": int(run.param("activityChannel", 1)),
"motion_thresh": float(run.param("motionThresh", 2.0)),
"discard_initial_s": float(run.param("discardInitial_s", 0.0)),
"nan_thresh": float(run.param("nanThresh", 0.33)),
- "ratio": float(run.param("analyzeHz", 200.0))
- / float(run.param("alignHz", 80.0)),
+ "ratio": float(run.param("analyzeHz", 200.0)) / float(run.param("alignHz", 80.0)),
"align_hz": float(run.param("alignHz", 80.0)),
"photon_scale": float(run.param("photonScale", np.nan)),
}
def read_stack(path: Path, num_channels: int) -> np.ndarray:
- """A registered movie as ``(frames, channels, rows, cols)`` float32
- (MATLAB's orientation; channels interleaved by frame)."""
+ """Read a registered movie as (frames, channels, rows, cols) float32.
+
+ The orientation is MATLAB's; channels are interleaved by frame.
+
+ Returns
+ -------
+ np.ndarray
+ The movie, (frames, channels, rows, cols) float32.
+ """
path = Path(path)
if path.suffix == ".h5":
with h5py.File(path, "r") as f:
@@ -212,14 +228,17 @@ def read_stack(path: Path, num_channels: int) -> np.ndarray:
raw = _read_tiff_pages(path) # (pages, MATLAB col, MATLAB row)
raw = np.asarray(raw, np.float32).transpose(0, 2, 1)
n = raw.shape[0] // num_channels
- return raw[: n * num_channels].reshape(
- n, num_channels, raw.shape[1], raw.shape[2]
- )
+ return raw[: n * num_channels].reshape(n, num_channels, raw.shape[1], raw.shape[2])
-def _vec(f, name: str, n: Optional[int] = None):
- """A dataset of the alignment file as a flat float64 vector (None if
- missing)."""
+def _vec(f: h5py.File, name: str, n: int | None = None) -> np.ndarray | None:
+ """Read a dataset of the alignment file as a flat float64 vector.
+
+ Returns
+ -------
+ np.ndarray or None
+ The first n values (all if n is None); None if the dataset is missing.
+ """
if name not in f:
return None
v = np.asarray(f[name][()], np.float64).ravel()
@@ -227,7 +246,14 @@ def _vec(f, name: str, n: Optional[int] = None):
def read_alignment(path: Path, n_frames: int) -> dict:
- """The alignment file's frame lines, rate, error and motion records."""
+ """Read the alignment file's frame lines, rate, error and motion records.
+
+ Returns
+ -------
+ dict
+ ds_lines, align_hz, rec_neg_err, motion_row, motion_col and
+ online (the online motion shifts present, by name).
+ """
with h5py.File(path, "r") as f:
out = {
"ds_lines": _vec(f, "DSframes", n_frames),
@@ -252,11 +278,18 @@ def read_varfac(
path: Path,
crop: tuple,
mode: str,
- discard: Optional[np.ndarray] = None,
-) -> Optional[np.ndarray]:
- """``slap2/varFacDS`` in the crop: per-pixel mean ``(rows, cols)`` over
- kept frames (when ``discard`` is given) or every frame ``(frames, rows,
- cols)``; None without it."""
+ discard: np.ndarray | None = None,
+) -> np.ndarray | None:
+ """Read slap2/varFacDS in the crop.
+
+ The per-pixel mean (rows, cols) over kept frames (when discard is
+ given) or, with mode "full", every frame (frames, rows, cols).
+
+ Returns
+ -------
+ np.ndarray or None
+ The variance factor in the crop; None without it.
+ """
r0, r1, c0, c1 = crop
with h5py.File(path, "r") as f:
if "slap2/varFacDS" not in f:
@@ -271,11 +304,7 @@ def read_varfac(
return out
tot = np.zeros((c1 - c0, r1 - r0))
cnt = np.zeros((c1 - c0, r1 - r0))
- disc = (
- None
- if discard is None
- else np.asarray(discard, bool).ravel()[: ds.shape[0]]
- )
+ disc = None if discard is None else np.asarray(discard, bool).ravel()[: ds.shape[0]]
for a in range(0, ds.shape[0], 256):
b = min(ds.shape[0], a + 256)
blk = np.asarray(ds[a:b, c0:c1, r0:r1], np.float64)
@@ -291,10 +320,18 @@ def read_varfac(
def labeled_mask(mean_act: np.ndarray, valid: np.ndarray) -> np.ndarray:
- """Labeled pixels: the 3 x 3 median-filtered mean image (zero padding,
- as MATLAB's ``medfilt2``) above 3 x its 25th percentile; for a dim trial
+ """Return the labeled pixels of a trial.
+
+ The 3 x 3 median-filtered mean image (zero padding,
+ as MATLAB's medfilt2) above 3 x its 25th percentile; for a dim trial
where nearly every valid pixel would count, the percentile over the
- valid pixels instead."""
+ valid pixels instead.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask of the labeled pixels, (rows, cols).
+ """
nan = np.isnan(mean_act)
mf = median_filter(np.where(nan, np.inf, mean_act), 3, mode="constant")
mf[~np.isfinite(mf)] = np.nan
@@ -304,16 +341,32 @@ def labeled_mask(mean_act: np.ndarray, valid: np.ndarray) -> np.ndarray:
return lab
-def _nanmedian(x) -> float:
- """Median ignoring NaN (NaN when empty), without warnings."""
+def _nanmedian(x: npt.ArrayLike) -> float:
+ """Return the median ignoring NaN (NaN when empty), without warnings.
+
+ Returns
+ -------
+ float
+ The median of the finite values; NaN if there are none.
+ """
x = np.asarray(x, np.float64)
x = x[np.isfinite(x)]
return float(np.median(x)) if x.size else float("nan")
def _crop_box(valid: np.ndarray) -> tuple:
- """``(r0, r1, c0, c1)`` (end exclusive) of the box around the valid
- pixels."""
+ """Return (r0, r1, c0, c1) (end exclusive) of the box around the valid pixels.
+
+ Returns
+ -------
+ tuple of int
+ (r0, r1, c0, c1) of the box.
+
+ Raises
+ ------
+ TrialSkipped
+ If there are no valid pixels.
+ """
rows = np.flatnonzero(valid.any(1))
cols = np.flatnonzero(valid.any(0))
if rows.size == 0:
@@ -321,9 +374,31 @@ def _crop_box(valid: np.ndarray) -> tuple:
return int(rows[0]), int(rows[-1]) + 1, int(cols[0]), int(cols[-1]) + 1
-def _render(job: TrialJob, ds_lines, shape):
- """The trial's footprints in its frame, the sources' 80 Hz traces per
- SILo channel, the 80 Hz discard share and the kernel's record."""
+def _render(
+ job: TrialJob, ds_lines: np.ndarray, shape: tuple
+) -> tuple[sparse.csr_matrix, list[np.ndarray], np.ndarray, dict[str, float]]:
+ """Render the trial's footprints and the sources' 80 Hz traces.
+
+ The footprints are in its frame, the traces per SILo channel; also the
+ 80 Hz discard share and the kernel's record.
+
+ Returns
+ -------
+ H : sparse.csr_matrix
+ The trial's footprints in its frame.
+ x80 : list of np.ndarray
+ The sources' 80 Hz traces, one array per SILo channel.
+ share : np.ndarray
+ The 80 Hz frames' discard share.
+ info : dict
+ The kernel's record.
+
+ Raises
+ ------
+ TrialSkipped
+ If SILo has no map, footprints or traces for the trial, or the kernel cannot
+ match the movie.
+ """
if job.tmap is None:
raise TrialSkipped("SILo has no across-trial map for this trial")
if job.footprints is None or not len(job.footprints[0]):
@@ -364,10 +439,7 @@ def _render(job: TrialJob, ds_lines, shape):
job.lines_per_cycle,
)
x200 = np.nan_to_num(np.asarray(job.x200, np.float64))
- x80 = [
- np.asarray((w.T @ x200[:, c, :]).T, np.float64)
- for c in range(x200.shape[1])
- ]
+ x80 = [np.asarray((w.T @ x200[:, c, :]).T, np.float64) for c in range(x200.shape[1])]
H = place_footprints(
job.footprints,
job.n_sources,
@@ -380,9 +452,26 @@ def _render(job: TrialJob, ds_lines, shape):
return H, x80, share, info
-def _qc(job, H, Xa, Y, valid, crop, discard):
- """The QC values of the activity as written (see
- :mod:`~giant_python.export.f0_qc`)."""
+def _qc(
+ job: TrialJob,
+ H: sparse.spmatrix,
+ Xa: np.ndarray,
+ Y: np.ndarray,
+ valid: np.ndarray,
+ crop: tuple,
+ discard: np.ndarray,
+) -> tuple[np.ndarray, dict]:
+ """Compute the QC values of the activity as written.
+
+ See :mod:`~giant_python.export.f0_qc`.
+
+ Returns
+ -------
+ pk : np.ndarray
+ Each source's flat peak pixel (-1 without footprint pixels).
+ qc : dict
+ The QC values, by their names in the trial file's attributes.
+ """
shape = valid.shape
pk = f0_qc.peak_pixels(H)
sl, r = f0_qc.peak_fit(H, Xa, Y, pk)
@@ -419,16 +508,37 @@ def _qc(job, H, Xa, Y, valid, crop, discard):
}
-def _ring_qc(H, Xa, Y, valid, crop, pk, discard):
- """The ring-event ratios on the cropped arrays (a source counts only
- when its 17 x 17 px box lies inside the crop, as in the MATLAB
- exporter)."""
+def _ring_qc(
+ H: sparse.spmatrix,
+ Xa: np.ndarray,
+ Y: np.ndarray,
+ valid: np.ndarray,
+ crop: tuple,
+ pk: np.ndarray,
+ discard: np.ndarray,
+) -> f0_qc.RingEventRatios:
+ """Compute the ring-event ratios on the cropped arrays.
+
+ A source counts only when its 17 x 17 px box lies inside the crop, as in the
+ MATLAB exporter.
+
+ Returns
+ -------
+ f0_qc.RingEventRatios
+ The ring-event ratios.
+ """
r0, r1, c0, c1 = crop
R, C = valid.shape
cc = c1 - c0
- def act_at(flat):
- """Activity at the crop's flat pixels, ``(frames, n)``."""
+ def act_at(flat: np.ndarray) -> np.ndarray:
+ """Return the activity at the crop's flat pixels, (frames, n).
+
+ Returns
+ -------
+ np.ndarray
+ The activity, (frames, n).
+ """
full = (flat // cc + r0) * C + flat % cc + c0
return np.asarray(H[full] @ Xa).T
@@ -437,9 +547,7 @@ def act_at(flat):
far = -(10**6)
pr = np.where(pk >= 0, pk // C - r0, far)
pc = np.where(pk >= 0, pk % C - c0, far)
- return f0_qc.ring_event_ratios(
- movie, act_at, mean_act, valid[r0:r1, c0:c1], pr, pc, discard
- )
+ return f0_qc.ring_event_ratios(movie, act_at, mean_act, valid[r0:r1, c0:c1], pr, pc, discard)
NO_QC = {
@@ -459,7 +567,9 @@ def act_at(flat):
}
-def _create(f, name: str, data, deflate: int, chunks=None) -> None:
+def _create(
+ f: h5py.File, name: str, data: npt.ArrayLike, deflate: int, chunks: tuple | None = None
+) -> None:
"""Write a dataset with gzip and shuffle (one chunk unless given)."""
data = np.asarray(data)
if data.size == 0:
@@ -476,14 +586,32 @@ def _create(f, name: str, data, deflate: int, chunks=None) -> None:
def _movie_chunks(shape: tuple) -> tuple:
- """Chunks of a (channel, frame, row, col) array, as the MATLAB
- exporter's (one channel, 256 frames, 64 x 64 px)."""
+ """Return the chunks of a (channel, frame, row, col) array.
+
+ As the MATLAB exporter's (one channel, 256 frames, 64 x 64 px).
+
+ Returns
+ -------
+ tuple of int
+ The chunk shape.
+ """
return (1, min(256, shape[1]), min(64, shape[2]), min(64, shape[3]))
-def _load(job: TrialJob):
- """The movie stack, its alignment record, the motion discards and the
- valid pixels."""
+def _load(job: TrialJob) -> tuple[np.ndarray, dict, np.ndarray, np.ndarray]:
+ """Load the movie stack, its alignment record, the motion discards and the valid pixels.
+
+ Returns
+ -------
+ stack : np.ndarray
+ The movie, (frames, channels, rows, cols).
+ al : dict
+ The alignment record (:func:`read_alignment`).
+ disc : np.ndarray
+ Boolean mask of the frames discarded for motion.
+ valid : np.ndarray
+ Boolean mask of the valid pixels, (rows, cols).
+ """
st = job.settings
stack = read_stack(job.movie_file, st["num_channels"])
T = stack.shape[0]
@@ -500,10 +628,24 @@ def _load(job: TrialJob):
return stack, al, disc, valid
-def _activity(H, x80, chans: list, crop: tuple, shape: tuple, T: int):
- """The written channels' activity in the crop ``(channels, frames,
- rows, cols)`` float32, computed at the footprint pixels (zero
- elsewhere)."""
+def _activity(
+ H: sparse.spmatrix | None,
+ x80: list[np.ndarray] | None,
+ chans: list,
+ crop: tuple,
+ shape: tuple,
+ T: int,
+) -> np.ndarray:
+ """Compute the written channels' activity in the crop.
+
+ The activity is (channels, frames, rows, cols) float32, computed at the
+ footprint pixels (zero elsewhere).
+
+ Returns
+ -------
+ np.ndarray
+ The activity, (channels, frames, rows, cols) float32.
+ """
r0, r1, c0, c1 = crop
C = shape[1]
out = np.zeros((len(chans), T, r1 - r0, c1 - c0), np.float32)
@@ -522,8 +664,7 @@ def _activity(H, x80, chans: list, crop: tuple, shape: tuple, T: int):
def _write(job: TrialJob, arrays: dict, attrs: dict) -> None:
- """Write one trial file (through a temporary name, replacing an
- existing file)."""
+ """Write one trial file (through a temporary name, replacing an existing file)."""
dfl = job.options.deflate
out = Path(job.out_file)
out.parent.mkdir(parents=True, exist_ok=True)
@@ -533,14 +674,8 @@ def _write(job: TrialJob, arrays: dict, attrs: dict) -> None:
chunks = None
if name in ("movie", "activity"):
chunks = _movie_chunks(a.shape)
- elif name == "mask/activity":
- chunks = (min(256, a.shape[0]),) + tuple(
- min(64, n) for n in a.shape[1:]
- )
- elif name == "varfac" and np.ndim(a) == 3:
- chunks = (min(256, a.shape[0]),) + tuple(
- min(64, n) for n in a.shape[1:]
- )
+ elif name == "mask/activity" or name == "varfac" and np.ndim(a) == 3:
+ chunks = (min(256, a.shape[0]),) + tuple(min(64, n) for n in a.shape[1:])
_create(f, name, a, dfl, chunks)
for k, v in attrs.items():
f.attrs[k] = v
@@ -548,7 +683,13 @@ def _write(job: TrialJob, arrays: dict, attrs: dict) -> None:
def _provenance(job: TrialJob) -> dict:
- """String attributes naming the run, the baseline and the exporter."""
+ """Return the string attributes naming the run, the baseline and the exporter.
+
+ Returns
+ -------
+ dict
+ The attributes, by name.
+ """
p = job.provenance
return {
"label": p.get("label", ""),
@@ -563,16 +704,29 @@ def _provenance(job: TrialJob) -> dict:
}
-def _attr_value(v):
- """An HDF5 attribute value (lists as float64 arrays)."""
+def _attr_value(v: object) -> object:
+ """Return an HDF5 attribute value (lists as float64 arrays).
+
+ Returns
+ -------
+ object
+ A float64 array for a list, tuple or array; v otherwise.
+ """
if isinstance(v, (list, tuple, np.ndarray)):
return np.asarray(v, np.float64)
return v
def _map_shift(job: TrialJob) -> list:
- """The map's mean offset (trial minus canvas) over the footprint
- pixels: the counterpart of the MATLAB exporter's searched ``shiftRC``."""
+ """Return the map's mean offset (trial minus canvas) over the footprint pixels.
+
+ The counterpart of the MATLAB exporter's searched shiftRC.
+
+ Returns
+ -------
+ list of float
+ The mean row and column offset; NaN, NaN without a map or footprints.
+ """
if job.tmap is None or job.footprints is None:
return [np.nan, np.nan]
r = np.asarray(job.footprints[0], float)
@@ -583,15 +737,27 @@ def _map_shift(job: TrialJob) -> list:
return [float(np.mean(rt - r)), float(np.mean(ct - c))]
-def _support(H, shape) -> np.ndarray:
- """Pixels any footprint covers, ``(rows, cols)`` bool."""
+def _support(H: sparse.spmatrix | None, shape: tuple) -> np.ndarray:
+ """Return the pixels any footprint covers, (rows, cols) bool.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask of the pixels covered by a footprint.
+ """
if H is None:
return np.zeros(shape, bool)
return (np.asarray(H.getnnz(axis=1)) > 0).reshape(shape)
-def _frame_arrays(al: dict, disc, Y, valid) -> dict:
- """The per-frame datasets."""
+def _frame_arrays(al: dict, disc: np.ndarray, Y: np.ndarray, valid: np.ndarray) -> dict:
+ """Build the per-frame datasets.
+
+ Returns
+ -------
+ dict
+ The datasets, by name in the trial file.
+ """
out = {"frame/discard": disc.astype(np.uint8)}
for key in ("motion_row", "motion_col", "rec_neg_err"):
if al[key] is not None:
@@ -606,11 +772,19 @@ def _frame_arrays(al: dict, disc, Y, valid) -> dict:
def _baseline_qc(job: TrialJob, arrays: dict, crop: tuple) -> dict:
- """With the trial's network baseline: the time-mean of the training
+ """Compute QC from the trial's network baseline.
+
+ The time-mean of the training
target (movie - activity) over that of the baseline, at valid
footprint pixels and at valid labeled pixels outside the footprints
- (``targetOverBaselineSupport``, ``targetOverBaselineLabeled``; NaN
- without a baseline)."""
+ (targetOverBaselineSupport, targetOverBaselineLabeled; NaN
+ without a baseline).
+
+ Returns
+ -------
+ dict
+ targetOverBaselineSupport and targetOverBaselineLabeled.
+ """
out = {
"targetOverBaselineSupport": np.nan,
"targetOverBaselineLabeled": np.nan,
@@ -641,8 +815,24 @@ def _baseline_qc(job: TrialJob, arrays: dict, crop: tuple) -> dict:
return out
-def _arrays(job, stack, Y, H, x80, valid, crop, disc, pk) -> dict:
- """Every dataset of the trial file but the per-frame ones."""
+def _arrays(
+ job: TrialJob,
+ stack: np.ndarray,
+ Y: np.ndarray,
+ H: sparse.spmatrix | None,
+ x80: list[np.ndarray] | None,
+ valid: np.ndarray,
+ crop: tuple,
+ disc: np.ndarray,
+ pk: np.ndarray,
+) -> dict:
+ """Build every dataset of the trial file but the per-frame ones.
+
+ Returns
+ -------
+ dict
+ The datasets, by name in the trial file.
+ """
st, o = job.settings, job.options
ach = st["activity_channel"]
chans = list(o.channels or (ach,))
@@ -661,26 +851,18 @@ def _arrays(job, stack, Y, H, x80, valid, crop, disc, pk) -> dict:
out = {
"movie": movie,
"activity": _activity(H, x80, chans, crop, (R, C), T),
- "mean_image": mean_all[[ch - 1 for ch in chans], r0:r1, c0:c1].astype(
- np.float32
- ),
+ "mean_image": mean_all[[ch - 1 for ch in chans], r0:r1, c0:c1].astype(np.float32),
"mask/valid": valid[r0:r1, c0:c1].astype(np.uint8),
"mask/labeled": lab[r0:r1, c0:c1].astype(np.uint8),
- "mask/footprint_support": _support(H, (R, C))[r0:r1, c0:c1].astype(
- np.uint8
- ),
+ "mask/footprint_support": _support(H, (R, C))[r0:r1, c0:c1].astype(np.uint8),
}
vf = read_varfac(job.alignment_file, crop, o.var_fac, disc)
if vf is None:
vf = np.ones((r1 - r0, c1 - c0), np.float32)
out["varfac"] = vf
if H is not None:
- out["sources/peak_row"] = np.where(pk >= 0, pk // C - r0, -1).astype(
- np.int32
- )
- out["sources/peak_col"] = np.where(pk >= 0, pk % C - c0, -1).astype(
- np.int32
- )
+ out["sources/peak_row"] = np.where(pk >= 0, pk // C - r0, -1).astype(np.int32)
+ out["sources/peak_col"] = np.where(pk >= 0, pk % C - c0, -1).astype(np.int32)
return out
@@ -693,18 +875,39 @@ def _arrays(job, stack, Y, H, x80, valid, crop, disc, pk) -> dict:
}
-def registration_stem(movie_file) -> str:
- """The stem that a trial's registration files share: ``E1T3DMD2`` of
- ``E1T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.h5`` (and of its alignment
- data, statistics, layout and baseline files)."""
+def registration_stem(movie_file: str | Path) -> str:
+ """Return the stem that a trial's registration files share.
+
+ E1T3DMD2 of E1T3DMD2_REGISTERED_DOWNSAMPLED-80Hz.h5 (and of its alignment
+ data, statistics, layout and baseline files).
+
+ Returns
+ -------
+ str
+ The shared stem.
+ """
name = Path(movie_file).name
cut = name.find("_REGISTERED")
return name[:cut] if cut > 0 else Path(name).stem
-def _record(job, T, crop, valid, H, kern, qc, disc) -> dict:
- """The trial's summary record (also its attributes, without
- ``file``)."""
+def _record(
+ job: TrialJob,
+ T: int,
+ crop: tuple,
+ valid: np.ndarray,
+ H: sparse.spmatrix | None,
+ kern: dict,
+ qc: dict,
+ disc: np.ndarray,
+) -> dict:
+ """Build the trial's summary record (also its attributes, without file).
+
+ Returns
+ -------
+ dict
+ The record.
+ """
o, st = job.options, job.settings
r0, r1, c0, c1 = crop
ach = st["activity_channel"]
@@ -741,7 +944,13 @@ def _record(job, T, crop, valid, H, kern, qc, disc) -> dict:
def _export_trial(job: TrialJob) -> dict:
- """The work of :func:`export_trial`."""
+ """Do the work of :func:`export_trial`.
+
+ Returns
+ -------
+ dict
+ The trial's summary record.
+ """
o, st = job.options, job.settings
stack, al, disc, valid = _load(job)
T, _, R, C = stack.shape
@@ -761,10 +970,7 @@ def _export_trial(job: TrialJob) -> dict:
arrays.update(_frame_arrays(al, disc, Y, valid))
q = _record(job, T, crop, valid, H, kern, qc, disc)
q["labeledPixels"] = int(
- (
- arrays["mask/labeled"].astype(bool)
- & arrays["mask/valid"].astype(bool)
- ).sum()
+ (arrays["mask/labeled"].astype(bool) & arrays["mask/valid"].astype(bool)).sum()
)
q.update(_baseline_qc(job, arrays, crop))
if o.activity_mask is not None:
@@ -774,10 +980,32 @@ def _export_trial(job: TrialJob) -> dict:
return q
-def _mask(job, H, ds_lines, shape, crop, disc, arrays, Y) -> dict:
- """Add ``mask/activity`` to the arrays; return the rule and the
- masked shares (of the finite activity-channel samples at valid pixels
- in kept frames; at the footprint support) for the record."""
+def _mask(
+ job: TrialJob,
+ H: sparse.spmatrix | None,
+ ds_lines: np.ndarray,
+ shape: tuple,
+ crop: tuple,
+ disc: np.ndarray,
+ arrays: dict,
+ Y: np.ndarray,
+) -> dict:
+ """Add mask/activity to the arrays; return the rule and the masked shares.
+
+ The shares are of the finite activity-channel samples at valid pixels
+ in kept frames, and at the footprint support, for the record.
+
+ Returns
+ -------
+ dict
+ The rule's attributes, the mask's time constant in seconds and the masked
+ shares.
+
+ Raises
+ ------
+ TrialSkipped
+ If the mask cannot be made for the trial.
+ """
rule = job.options.activity_mask
T = disc.size
tm = None
@@ -837,8 +1065,13 @@ def _mask(job, H, ds_lines, shape, crop, disc, arrays, Y) -> dict:
def export_trial(job: TrialJob) -> dict:
- """Export one trial; returns its summary record (``error`` instead
- when it could not be exported)."""
+ """Export one trial.
+
+ Returns
+ -------
+ dict
+ The trial's summary record (error instead when it could not be exported).
+ """
t0 = time.time()
try:
q = _export_trial(job)
@@ -856,8 +1089,14 @@ def export_trial(job: TrialJob) -> dict:
# --------------------------------------------------------------- the run
-def _denoised(run: SiloRun, d: int) -> Optional[np.ndarray]:
- """``dF_denoised`` of path ``d``, ``(frames, channels, sources)``."""
+def _denoised(run: SiloRun, d: int) -> np.ndarray | None:
+ """Read dF_denoised of path d, (frames, channels, sources).
+
+ Returns
+ -------
+ np.ndarray or None
+ The traces; None if the run has none.
+ """
with h5py.File(run.experiment, "r") as f:
key = f"Path{d}/sources/temporal/dF_denoised"
if key not in f:
@@ -866,33 +1105,51 @@ def _denoised(run: SiloRun, d: int) -> Optional[np.ndarray]:
def _network_records(run: SiloRun) -> dict:
- """SILo's per-trial records of the network baseline (empty without)."""
+ """Return SILo's per-trial records of the network baseline (empty without).
+
+ Returns
+ -------
+ dict
+ The records, by path and trial.
+ """
try:
return json.loads(run.attrs.get("network_baseline") or "{}")
except (TypeError, ValueError):
return {}
-def _selection(options, run, session) -> tuple:
- """The one-based paths and trials to export, each once (``None``
- trials: SILo's own); refuses numbers the run or the trial table does
+def _selection(
+ options: ExportOptions, run: SiloRun, session: Session
+) -> tuple[list[int], list[int] | None]:
+ """Select the one-based paths and trials to export, each once.
+
+ None trials: SILo's own. Refuses numbers the run or the trial table does
not have. A repeated selector would have two workers write the same
- file."""
+ file.
+
+ Returns
+ -------
+ paths : list of int
+ The paths to export.
+ trials : list of int or None
+ The trials to export; None for SILo's own.
+
+ Raises
+ ------
+ ValueError
+ If a path is not among the run's paths or a trial is not in the trial table.
+ """
paths = sorted({int(d) for d in options.paths or run.paths})
bad = [d for d in paths if d not in run.paths]
if bad:
- raise ValueError(
- f"paths {bad} are not among the run's paths {run.paths}"
- )
+ raise ValueError(f"paths {bad} are not among the run's paths {run.paths}")
if not options.trials:
return paths, None
n = session.fn_reg_ds.shape[1]
trials = sorted({int(t) for t in options.trials})
bad = [t for t in trials if not 1 <= t <= n]
if bad:
- raise ValueError(
- f"trials {bad} are not among the trial table's trials 1..{n}"
- )
+ raise ValueError(f"trials {bad} are not among the trial table's trials 1..{n}")
return paths, trials
@@ -900,9 +1157,16 @@ def _selection(options, run, session) -> tuple:
def _remove_unscheduled(out_dir: Path, d: int, jobs: list) -> list:
- """Remove the earlier ``trial_.h5`` files of path ``d`` that a
- default export does not write (a trial SILo no longer analyses):
- the reader finds files, not summaries. Returns their names."""
+ """Remove the earlier trial_.h5 files of path d that an export does not write.
+
+ A default export does not write the files of a trial SILo no longer analyses:
+ the reader finds files, not summaries.
+
+ Returns
+ -------
+ list of str
+ The names of the removed files.
+ """
keep = {Path(j.out_file).name for j in jobs}
removed = []
folder = Path(out_dir) / f"Path{d}"
@@ -915,9 +1179,25 @@ def _remove_unscheduled(out_dir: Path, d: int, jobs: list) -> list:
return removed
-def _path_jobs(run, session, d, out_dir, options, prov, trials=None) -> list:
- """The trial jobs of one path (``trials``: one-based, checked by
- :func:`_selection`; ``None``: the trials SILo analysed)."""
+def _path_jobs(
+ run: SiloRun,
+ session: Session,
+ d: int,
+ out_dir: str | Path,
+ options: ExportOptions,
+ prov: dict,
+ trials: list[int] | None = None,
+) -> list:
+ """Build the trial jobs of one path.
+
+ trials: one-based, checked by :func:`_selection`; None: the trials SILo
+ analysed.
+
+ Returns
+ -------
+ list of TrialJob
+ The jobs, one per trial.
+ """
p = run.path(d)
st = _settings(run)
n = 0 if options.ignore_sources else p.sources.n
@@ -928,11 +1208,7 @@ def _path_jobs(run, session, d, out_dir, options, prov, trials=None) -> list:
elif (p.n_frames > 0).any(): # the trials SILo analysed
trials = [t for t in range(p.n_frames.size) if p.n_frames[t] > 0]
else: # no frame counts (a path without sources): registered movies
- trials = [
- t
- for t in range(session.fn_reg_ds.shape[1])
- if session.has_movie(d - 1, t)
- ]
+ trials = [t for t in range(session.fn_reg_ds.shape[1]) if session.has_movie(d - 1, t)]
recs = _network_records(run)
mask = _mask_inputs(run, p, st, x) if options.activity_mask else {}
jobs = []
@@ -976,19 +1252,25 @@ def _path_jobs(run, session, d, out_dir, options, prov, trials=None) -> list:
return jobs
-def _mask_inputs(run, p, st, x) -> dict:
- """What the activity mask needs from the path: each source's noise
+def _mask_inputs(run: SiloRun, p: PathData, st: dict, x: np.ndarray | None) -> dict:
+ """Collect what the activity mask needs from the path.
+
+ Each source's noise
(activity channel; None without traces), the activity channel's decay
- constant in 200 Hz frames (SILo's ``tau_full``, else ``tau_s`` times the
- frame rate; not channel 2's ``tau2``) and the canvas positions of seeds
+ constant in 200 Hz frames (SILo's tau_full, else tau_s times the
+ frame rate; not channel 2's tau2) and the canvas positions of seeds
without a source (kinetics-rejected sources and the plan's unused
- seeds)."""
+ seeds).
+
+ Returns
+ -------
+ dict
+ sigma, tau200, tau_seconds, spots and seeds_unknown.
+ """
out = {"sigma": None, "spots": np.zeros((0, 2))}
hz = float(run.param("analyzeHz", 200.0) or 200.0)
tau = run.param("tau_full", None)
- out["tau200"] = (
- float(tau) if tau else float(run.param("tau_s", 0.024)) * hz
- )
+ out["tau200"] = float(tau) if tau else float(run.param("tau_s", 0.024)) * hz
out["tau_seconds"] = out["tau200"] / hz
if x is not None and p.sources.n:
ach = st["activity_channel"]
@@ -1006,9 +1288,14 @@ def _mask_inputs(run, p, st, x) -> dict:
return out
-def _ls_trace(run, d: int, c: int) -> Optional[np.ndarray]:
- """``dF_ls`` of path ``d``, channel index ``c``, ``(frames,
- sources)`` (None without it)."""
+def _ls_trace(run: SiloRun, d: int, c: int) -> np.ndarray | None:
+ """Read dF_ls of path d, channel index c, (frames, sources).
+
+ Returns
+ -------
+ np.ndarray or None
+ The traces; None without them.
+ """
with h5py.File(run.experiment, "r") as f:
key = f"Path{d}/sources/temporal/dF_ls"
if key not in f:
@@ -1017,8 +1304,14 @@ def _ls_trace(run, d: int, c: int) -> Optional[np.ndarray]:
return np.asarray(ds[:, min(c, ds.shape[1] - 1), :], np.float32)
-def _json_safe(v):
- """NaN and infinities as None, NumPy values as Python ones."""
+def _json_safe(v: object) -> object:
+ """Return NaN and infinities as None, NumPy values as Python ones.
+
+ Returns
+ -------
+ object
+ v with NaN and infinities replaced by None and NumPy values by Python ones.
+ """
if isinstance(v, dict):
return {k: _json_safe(x) for k, x in v.items()}
if isinstance(v, (list, tuple, np.ndarray)):
@@ -1031,34 +1324,33 @@ def _json_safe(v):
def write_summary(out_dir: Path, summary: dict) -> None:
- """``export_summary.json`` (NaN written as null, as MATLAB's
- ``jsonencode``)."""
+ """Write export_summary.json (NaN written as null, as MATLAB's jsonencode)."""
path = Path(out_dir) / "export_summary.json"
path.write_text(json.dumps(_json_safe(summary), indent=1))
def export_run(
- run_dir,
- out_dir,
- table=None,
- moco_dir=None,
- baseline_dir=None,
- data_dir=None,
- options: Optional[ExportOptions] = None,
- log=print,
+ run_dir: str | Path,
+ out_dir: str | Path,
+ table: str | Path | None = None,
+ moco_dir: str | Path | None = None,
+ baseline_dir: str | Path | None = None,
+ data_dir: str | Path | None = None,
+ options: ExportOptions | None = None,
+ log: Callable[[str], object] = print,
) -> dict:
"""Export a SILo run as F0 training data.
Parameters
----------
run_dir : str or Path
- The ``giant silo`` run (its folder or ``source_extraction``).
+ The giant silo run (its folder or source_extraction).
out_dir : str or Path
- Output folder (``Path/trial_.h5``, ``export_summary.json``).
+ Output folder (Path/trial_.h5, export_summary.json).
table, moco_dir, baseline_dir, data_dir : str or Path, optional
- As ``giant view``: the trial table (default: in or above the run),
+ As giant view: the trial table (default: in or above the run),
the registered movies and alignment files (default: the table's
- ``savedr/motion_correction``), the network baselines (optional;
+ savedr/motion_correction), the network baselines (optional;
provenance and the target-over-baseline QC), the raw files (for
the lines per cycle; without them the kernels reach 3 dt).
options : ExportOptions, optional
@@ -1068,15 +1360,13 @@ def export_run(
Returns
-------
dict
- The summary written to ``export_summary.json``.
+ The summary written to export_summary.json.
"""
options = options or ExportOptions()
_check_options(options)
run = SiloRun(run_dir)
_check_channels(options.channels, _settings(run)["num_channels"])
- session = Session(
- table or find_table(Path(run_dir)), moco_dir, baseline_dir, data_dir
- )
+ session = Session(table or find_table(Path(run_dir)), moco_dir, baseline_dir, data_dir)
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
label = options.label or Path(run_dir).name
@@ -1121,18 +1411,23 @@ def export_run(
return summary
-def write_event_statistics(out_dir, run, paths, label, options) -> dict:
- """``event_statistics.json``: per path, SILo's event statistics
- (:func:`~giant_python.export.f0_events.path_statistics`)."""
+def write_event_statistics(
+ out_dir: str | Path, run: SiloRun, paths: list[int], label: str, options: ExportOptions
+) -> dict:
+ """Write event_statistics.json: per path, SILo's event statistics.
+
+ See :func:`~giant_python.export.f0_events.path_statistics`.
+
+ Returns
+ -------
+ dict
+ The statistics written.
+ """
stats = {
"label": label,
"giantRef": options.giant_ref,
"exporterVersion": __version__,
- "paths": [
- f0_events.path_statistics(run, d)
- for d in paths
- if not options.ignore_sources
- ],
+ "paths": [f0_events.path_statistics(run, d) for d in paths if not options.ignore_sources],
}
out = Path(out_dir) / "event_statistics.json"
tmp = out.with_name(out.name + ".tmp")
@@ -1142,9 +1437,17 @@ def write_event_statistics(out_dir, run, paths, label, options) -> dict:
def _check_options(o: ExportOptions) -> None:
- """Refuse invalid options before any trial: a trial that fails
+ """Refuse invalid options before any trial.
+
+ A trial that fails
removes its earlier file, so an option every trial would trip on
- must not get that far."""
+ must not get that far.
+
+ Raises
+ ------
+ ValueError
+ If an option is invalid.
+ """
if o.kernel not in ("exact", "matched", "exporter"):
raise ValueError(f"unknown kernel {o.kernel!r}")
if o.interp not in INTERP_ORDER:
@@ -1167,18 +1470,27 @@ def _check_options(o: ExportOptions) -> None:
o.activity_mask.check()
-def _check_channels(channels, num_channels: int) -> None:
- """Refuse channels outside the movie's one-based ``1..numChannels``."""
+def _check_channels(channels: tuple[int, ...] | None, num_channels: int) -> None:
+ """Refuse channels outside the movie's one-based 1..numChannels.
+
+ Raises
+ ------
+ ValueError
+ If a channel is outside 1..num_channels.
+ """
bad = [c for c in channels or () if not 1 <= int(c) <= num_channels]
if bad:
- raise ValueError(
- f"channels {bad} are not among the movie's channels "
- f"1..{num_channels}"
- )
+ raise ValueError(f"channels {bad} are not among the movie's channels 1..{num_channels}")
+
+def _run_jobs(jobs: list, workers: int) -> Iterator[dict]:
+ """Yield each job's record, in order of completion with several workers.
-def _run_jobs(jobs: list, workers: int):
- """Each job's record, in order of completion with several workers."""
+ Yields
+ ------
+ dict
+ The record of one exported trial.
+ """
if workers <= 1 or len(jobs) <= 1:
for job in jobs:
yield export_trial(job)
@@ -1189,7 +1501,13 @@ def _run_jobs(jobs: list, workers: int):
def _line(label: str, q: dict) -> str:
- """One progress line for a trial record."""
+ """Return one progress line for a trial record.
+
+ Returns
+ -------
+ str
+ The line: the trial's error, or its frame and source counts and QC figures.
+ """
head = f"[export-f0] {label} path {q['path']} trial {q['trial']}: "
if "error" in q:
return head + q["error"]
@@ -1202,19 +1520,28 @@ def _line(label: str, q: dict) -> str:
def find_table(run_dir: Path) -> Path:
- """The ``trial_table.h5`` in or above a run folder."""
+ """Find the trial_table.h5 in or above a run folder.
+
+ Returns
+ -------
+ Path
+ The first trial_table.h5 found in run_dir or its parents.
+
+ Raises
+ ------
+ FileNotFoundError
+ If there is no trial_table.h5 in or above run_dir.
+ """
for d in (run_dir, *run_dir.parents):
if (d / "trial_table.h5").exists():
return d / "trial_table.h5"
- raise FileNotFoundError(
- f"no trial_table.h5 in or above {run_dir}: give --table"
- )
+ raise FileNotFoundError(f"no trial_table.h5 in or above {run_dir}: give --table")
# ------------------------------------------------------------------ CLI
-def add_arguments(p) -> None:
+def add_arguments(p: argparse.ArgumentParser) -> None:
"""``giant export-f0``'s arguments."""
p.add_argument("run", help="the giant silo run folder")
p.add_argument("out", help="output folder (Path/trial_.h5)")
@@ -1260,16 +1587,14 @@ def add_arguments(p) -> None:
"--interp",
choices=tuple(INTERP_ORDER),
default="linear",
- help="how footprints move into the trial: linear "
- "(default) or cubic",
+ help="how footprints move into the trial: linear (default) or cubic",
)
p.add_argument(
"--channels",
type=int,
nargs="+",
default=None,
- help="one-based channels to write (default: SILo's "
- "activity channel)",
+ help="one-based channels to write (default: SILo's activity channel)",
)
p.add_argument(
"--var-fac",
@@ -1277,9 +1602,7 @@ def add_arguments(p) -> None:
default="mean",
help="varFacDS: per-pixel mean (default) or every frame",
)
- p.add_argument(
- "--deflate", type=int, default=1, help="HDF5 gzip level (default 1)"
- )
+ p.add_argument("--deflate", type=int, default=1, help="HDF5 gzip level (default 1)")
p.add_argument(
"--label",
default="",
@@ -1340,8 +1663,7 @@ def add_arguments(p) -> None:
"--mask-widen",
type=float,
default=d.widen_tau,
- help="mask widening after each crossing, in decay constants "
- f"(default {d.widen_tau:g})",
+ help=f"mask widening after each crossing, in decay constants (default {d.widen_tau:g})",
)
p.add_argument(
"--mask-share",
@@ -1354,8 +1676,7 @@ def add_arguments(p) -> None:
"--mask-spots",
choices=("none", "seeds"),
default=d.spots,
- help="also mask seeds without a source in every frame "
- f"(default {d.spots})",
+ help=f"also mask seeds without a source in every frame (default {d.spots})",
)
p.add_argument(
"--event-stats",
@@ -1365,8 +1686,14 @@ def add_arguments(p) -> None:
)
-def run_command(args) -> int:
- """Handle ``giant export-f0``; nonzero if any trial failed."""
+def run_command(args: argparse.Namespace) -> int:
+ """Handle giant export-f0; nonzero if any trial failed.
+
+ Returns
+ -------
+ int
+ 1 if any trial failed, otherwise 0.
+ """
options = ExportOptions(
kernel=args.kernel,
blur=args.blur,
diff --git a/src/giant_python/extraction/band/activity.py b/src/giant_python/extraction/band/activity.py
index 3422843d..1f87b4bb 100644
--- a/src/giant_python/extraction/band/activity.py
+++ b/src/giant_python/extraction/band/activity.py
@@ -2,24 +2,30 @@
from __future__ import annotations
-from typing import List, Tuple
-
import numpy as np
-import scipy.ndimage as ndimage
import torch
-from scipy import signal
+from scipy import ndimage, signal
from ...progress import progress
def _plane_column_maps(
sel_pix_idxs: np.ndarray, num_fast_zs: int, plane_size: int
-) -> Tuple[list, list, list]:
+) -> tuple[list, list, list]:
"""Precompute per-z column masks, indices, and remaps into local space.
Returns three lists (one entry per z): the boolean column mask, the column
indices of that plane's selected pixels, and a remap from global to local
- (per-plane) column index (``-1`` outside the plane).
+ (per-plane) column index (-1 outside the plane).
+
+ Returns
+ -------
+ z_masks : list
+ Per-z boolean column masks over the selected pixels.
+ z_col_idxs : list
+ Per-z column indices of that plane's selected pixels.
+ z_remaps : list
+ Per-z remap from global to local (per-plane) column index (-1 outside the plane).
"""
sel_pix_z = sel_pix_idxs // plane_size
z_masks = [torch.from_numpy(sel_pix_z == z) for z in range(num_fast_zs)]
@@ -28,9 +34,7 @@ def _plane_column_maps(
for z in range(num_fast_zs):
remap = torch.full((sel_pix_idxs.shape[0],), -1, dtype=torch.long)
if z_col_idxs[z].numel() > 0:
- remap[z_col_idxs[z]] = torch.arange(
- z_col_idxs[z].numel(), dtype=torch.long
- )
+ remap[z_col_idxs[z]] = torch.arange(z_col_idxs[z].numel(), dtype=torch.long)
z_remaps.append(remap)
return z_masks, z_col_idxs, z_remaps
@@ -50,13 +54,17 @@ def _valid_sel_cols_for_motion(
"""Return a per-selected-pixel mask of columns valid for one motion bin.
The valid region is the PSF-dilated reference support minus its
- horizontally-eroded border (erosion width ``2 * psf_w - 1``), evaluated at
+ horizontally-eroded border (erosion width 2 * psf_w - 1), evaluated at
this bin's motion shift.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask with one entry per selected pixel, True where the pixel's column is
+ valid for this motion bin.
"""
plane_size = dmd_pixels_per_column * dmd_pixels_per_row
- valid_pix_mask = np.zeros(
- (num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row), dtype=bool
- )
+ valid_pix_mask = np.zeros((num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row), dtype=bool)
valid_pix_mask[
ref_d,
ref_r + int(unique_motion_to_keep_yx[motion_idx, 0]),
@@ -70,9 +78,7 @@ def _valid_sel_cols_for_motion(
valid_pix_mask,
# Erode each plane with PSF-height rows and
# (2 * PSF-width - 1) columns.
- structure=np.ones(
- (1, psf2d.shape[0], psf2d.shape[1] * 2 - 1), dtype=bool
- ),
+ structure=np.ones((1, psf2d.shape[0], psf2d.shape[1] * 2 - 1), dtype=bool),
)
valid_pix_idxs = np.flatnonzero(valid_pix_mask)
valid_lookup = np.zeros(num_fast_zs * plane_size, dtype=bool)
@@ -84,9 +90,9 @@ def compute_rho(
residual: np.ndarray,
mot_inds_yx: np.ndarray,
unique_motion_to_keep_yx: np.ndarray,
- h_mots: List[torch.Tensor],
- d_mats: List[torch.Tensor],
- d_mats_expanded: List[torch.Tensor],
+ h_mots: list[torch.Tensor],
+ d_mats: list[torch.Tensor],
+ d_mats_expanded: list[torch.Tensor],
sel_pix_idxs: np.ndarray,
ref_d: np.ndarray,
ref_r: np.ndarray,
@@ -97,22 +103,22 @@ def compute_rho(
psf2d: np.ndarray,
verbose: bool = False,
) -> np.ndarray:
- """Compute the ``rho`` matched-filter response on the selected pixels.
+ """Compute the rho matched-filter response on the selected pixels.
- For each motion bin and z-plane, restricts ``H`` to that plane, forms the
- normalized ``HD`` and ``HD_expanded`` projections, and projects the
- residual onto ``HD - HD_expanded`` over the plane's valid columns.
+ For each motion bin and z-plane, restricts H to that plane, forms the
+ normalized HD and HD_expanded projections, and projects the
+ residual onto HD - HD_expanded over the plane's valid columns.
Parameters
----------
residual : ndarray of shape (n_superpixels, n_frames)
Noise-normalized residual from :func:`compute_residual`.
mot_inds_yx : ndarray of shape (n_frames,)
- Per-frame motion-bin index (``-1`` for dropped frames).
+ Per-frame motion-bin index (-1 for dropped frames).
unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2)
Kept 2-D motion vectors.
h_mots : list of torch.Tensor
- Per-motion sparse ``H`` from :func:`build_motion_h_matrices`.
+ Per-motion sparse H from :func:`build_motion_h_matrices`.
d_mats, d_mats_expanded : list of torch.Tensor
Per-plane base/expanded convolution matrices from
:func:`build_convolution_matrix`.
@@ -130,17 +136,13 @@ def compute_rho(
Returns
-------
ndarray of shape (n_sel, n_frames), float32
- The ``rho`` response (NaN where not computed).
+ The rho response (NaN where not computed).
"""
plane_size = dmd_pixels_per_column * dmd_pixels_per_row
- z_masks, z_col_idxs, z_remaps = _plane_column_maps(
- sel_pix_idxs, num_fast_zs, plane_size
- )
+ z_masks, z_col_idxs, z_remaps = _plane_column_maps(sel_pix_idxs, num_fast_zs, plane_size)
z_col_idxs_np = [zi.numpy() for zi in z_col_idxs]
- rho = np.full(
- (len(sel_pix_idxs), residual.shape[1]), np.nan, dtype=np.float32
- )
+ rho = np.full((len(sel_pix_idxs), residual.shape[1]), np.nan, dtype=np.float32)
for i in progress(
range(len(unique_motion_to_keep_yx)),
@@ -198,9 +200,7 @@ def compute_rho(
# column-normalized before subtracting, so ``hd_diff`` has
# zero-sum columns and is blind to spatially flat residual.
hd_expanded = torch.sparse.mm(h_sub, d_mats_expanded[z])
- hd_expanded = hd_expanded / torch.sum(
- hd_expanded, dim=0, keepdim=True
- )
+ hd_expanded = hd_expanded / torch.sum(hd_expanded, dim=0, keepdim=True)
hd_diff = hd - hd_expanded
# TEMPORARY: whiten each filter column to unit L2 norm so every
# selected pixel's rho has the same noise variance. The L1
@@ -229,9 +229,9 @@ def compute_rho(
def mask_high_nan_rho(rho: np.ndarray, thresh: float = 0.5) -> np.ndarray:
- """NaN-out rows of ``rho`` that are mostly NaN and return the NaN fraction.
+ """NaN-out rows of rho that are mostly NaN and return the NaN fraction.
- ``rho`` is modified in place. Rows whose NaN fraction exceeds ``thresh``
+ rho is modified in place. Rows whose NaN fraction exceeds thresh
are set entirely to NaN.
Parameters
@@ -264,7 +264,7 @@ def decay_kernel_1d(decay_tau_s: float, align_hz: float) -> np.ndarray:
Returns
-------
ndarray
- A 1-D kernel spanning ``3 * tau`` frames, summing to 1.
+ A 1-D kernel spanning 3 * tau frames, summing to 1.
"""
decay_tau_frames = decay_tau_s * align_hz
k1d = np.exp(
@@ -278,15 +278,13 @@ def decay_kernel_1d(decay_tau_s: float, align_hz: float) -> np.ndarray:
return k1d / np.sum(k1d)
-def smooth_rho(
- rho: np.ndarray, k1d: np.ndarray, verbose: bool = False
-) -> np.ndarray:
- """NaN-aware temporal smoothing of ``rho`` with a 1-D decay kernel.
+def smooth_rho(rho: np.ndarray, k1d: np.ndarray, verbose: bool = False) -> np.ndarray:
+ """NaN-aware temporal smoothing of rho with a 1-D decay kernel.
Convolves along time only, dividing the smoothed values by the smoothed
valid-sample count and NaN-ing samples whose effective count drops below
- ``0.75``. Rows are processed in chunks to bound temporary memory.
- ``rho`` is modified in place and also returned.
+ 0.75. Rows are processed in chunks to bound temporary memory.
+ rho is modified in place and also returned.
Parameters
----------
@@ -300,7 +298,7 @@ def smooth_rho(
Returns
-------
ndarray
- The smoothed ``rho``.
+ The smoothed rho.
"""
k2d = np.expand_dims(k1d, 0)
n_time = rho.shape[1]
@@ -321,9 +319,7 @@ def smooth_rho(
rc_valid = rc[row_has_data]
rho_num = np.nan_to_num(rc_valid, nan=0.0)
- rho_den = signal.convolve(
- np.isfinite(rc_valid).astype(np.float32), k2d, mode="same"
- )
+ rho_den = signal.convolve(np.isfinite(rc_valid).astype(np.float32), k2d, mode="same")
rho_num = signal.convolve(rho_num, k2d, mode="same")
valid_den = rho_den > 0.75
np.divide(rho_num, rho_den, out=rho_num, where=valid_den)
diff --git a/src/giant_python/extraction/band/annotation.py b/src/giant_python/extraction/band/annotation.py
index 39a72183..b62fc213 100644
--- a/src/giant_python/extraction/band/annotation.py
+++ b/src/giant_python/extraction/band/annotation.py
@@ -9,7 +9,6 @@
import os
import sys
from pathlib import Path
-from typing import Optional, Union
import numpy as np
@@ -33,7 +32,18 @@
def first_valid_trial(keep_trials: np.ndarray, dmd_ix: int) -> int:
- """Return this 0-based DMD's first kept trial, or raise ValueError."""
+ """Return this 0-based DMD's first kept trial, or raise ValueError.
+
+ Returns
+ -------
+ int
+ Index of the first kept trial for the DMD.
+
+ Raises
+ ------
+ ValueError
+ If the DMD has no kept trial.
+ """
indexes = np.flatnonzero(np.asarray(keep_trials)[dmd_ix])
if indexes.size == 0:
raise ValueError(f"No valid trials for DMD {dmd_ix + 1}")
@@ -41,7 +51,13 @@ def first_valid_trial(keep_trials: np.ndarray, dmd_ix: int) -> int:
def motion_median_from_adata(a_data: dict) -> tuple:
- """Round internal band motion then take per-axis (row,column,z) medians."""
+ """Round internal band motion then take per-axis (row,column,z) medians.
+
+ Returns
+ -------
+ tuple
+ Integer (row, column, z) median motion.
+ """
return (
int(np.nanmedian(np.round(a_data["motionDSr"]))),
int(np.nanmedian(np.round(a_data["motionDSc"]))),
@@ -50,12 +66,24 @@ def motion_median_from_adata(a_data: dict) -> tuple:
def _stdin_is_tty() -> bool:
- """Check for interactive stdin without importing a GUI toolkit."""
+ """Check for interactive stdin without importing a GUI toolkit.
+
+ Returns
+ -------
+ bool
+ True when stdin is attached to a terminal.
+ """
return bool(getattr(sys.stdin, "isatty", lambda: False)())
-def resolve_interactivity(override: Optional[bool] = None) -> bool:
- """Resolve override, then GIANT_HEADLESS, then terminal detection."""
+def resolve_interactivity(override: bool | None = None) -> bool:
+ """Resolve override, then GIANT_HEADLESS, then terminal detection.
+
+ Returns
+ -------
+ bool
+ True when interactive drawing is permitted.
+ """
if override is not None:
return bool(override)
if os.environ.get("GIANT_HEADLESS"):
@@ -64,7 +92,14 @@ def resolve_interactivity(override: Optional[bool] = None) -> bool:
def _empty_user_rois(n_dmds: int) -> dict:
- """Create neutral per-path ROI selections without implying annotations."""
+ """Create neutral per-path ROI selections without implying annotations.
+
+ Returns
+ -------
+ dict
+ Empty user_roi_masks, user_roi_superpixels, user_roi_labels and
+ roi_records lists keyed DMD1..DMD, plus annotated=False.
+ """
keys = [f"DMD{d + 1}" for d in range(n_dmds)]
return {
"user_roi_masks": {k: [] for k in keys},
@@ -75,13 +110,17 @@ def _empty_user_rois(n_dmds: int) -> dict:
}
-def load_annotations_h5(
- annotations_path: str, n_dmds: int, user_roi_geo: dict
-) -> tuple:
+def load_annotations_h5(annotations_path: str, n_dmds: int, user_roi_geo: dict) -> tuple:
"""Read and resolve band annotations; return the historical five-tuple.
Missing/unreadable files and selections with no usable ROIs return
(False, {}, {}, {}, {}). Geometry validation is delegated to pure helpers.
+
+ Returns
+ -------
+ tuple
+ (skip, masks, superpixels, labels, records): whether usable annotations were
+ found, then the per-DMD ROI masks, superpixels, labels and ROI records.
"""
if not os.path.exists(annotations_path):
return False, {}, {}, {}, {}
@@ -94,18 +133,29 @@ def load_annotations_h5(
def resolve_user_rois(
- annotation_dir: Union[str, Path],
+ annotation_dir: str | Path,
n_dmds: int,
user_roi_geo: dict,
*,
interactive: bool,
- ref_files: Optional[dict] = None,
+ ref_files: dict | None = None,
) -> dict:
- """Load usable annotations, or draw interactively or fail promptly."""
+ """Load usable annotations, or draw interactively or fail promptly.
+
+ Returns
+ -------
+ dict
+ ROI selection with user_roi_masks, user_roi_superpixels, user_roi_labels,
+ roi_records and annotated (True), loaded from file or freshly drawn.
+
+ Raises
+ ------
+ RuntimeError
+ If no usable ROIs are found at annotations.h5 and the process is not
+ interactive.
+ """
path = os.path.join(str(annotation_dir), "annotations.h5")
- skip, masks, superpixels, labels, records = load_annotations_h5(
- path, n_dmds, user_roi_geo
- )
+ skip, masks, superpixels, labels, records = load_annotations_h5(path, n_dmds, user_roi_geo)
if skip:
return {
"user_roi_masks": masks,
@@ -121,18 +171,22 @@ def resolve_user_rois(
"`giant annotate ` first, or run in an "
"interactive session (or pass interactive=True) to draw now."
)
- return _draw_and_save_user_rois(
- annotation_dir, n_dmds, user_roi_geo, ref_files
- )
+ return _draw_and_save_user_rois(annotation_dir, n_dmds, user_roi_geo, ref_files)
def _draw_and_save_user_rois(
- annotation_dir: Union[str, Path],
+ annotation_dir: str | Path,
n_dmds: int,
user_roi_geo: dict,
- ref_files: Optional[dict],
+ ref_files: dict | None,
) -> dict:
- """Launch the lazy ROI editor and save its records and masks."""
+ """Launch the lazy ROI editor and save its records and masks.
+
+ Returns
+ -------
+ dict
+ The editor's ROI selection, with annotated set to True.
+ """
from ...gui.roi_editor import run_user_roi_selection
os.makedirs(str(annotation_dir), exist_ok=True)
@@ -149,7 +203,14 @@ def _draw_and_save_user_rois(
def build_user_roi_geometry(trial_table: dict, lookup: dict) -> tuple:
- """Prepare per-DMD reference geometry and reference-file provenance."""
+ """Prepare per-DMD reference geometry and reference-file provenance.
+
+ Returns
+ -------
+ tuple
+ (user_roi_geo, ref_files): per-DMD reference geometry and the reference file
+ each DMD's geometry was built from, both keyed DMD1, DMD2, ...
+ """
user_roi_geo, ref_files = {}, {}
datadr = str(trial_table["datadr"])
keep_trials = trial_table["keep_trials"]
@@ -174,7 +235,7 @@ def build_user_roi_geometry(trial_table: dict, lookup: dict) -> tuple:
def annotate_band_rois(
- input: Union[str, Path, TrialTable],
+ input: str | Path | TrialTable,
params: BandParamsInput = None,
*,
execution: ExecutionInput = None,
@@ -185,8 +246,13 @@ def annotate_band_rois(
Existing usable annotations are loaded headlessly. No extraction or
source fitting occurs and in-memory trial tables are never reloaded.
Science, execution and annotation inputs are independently validated.
- This explicit step requests annotation regardless of ``enabled``;
- ``interactive`` still controls whether drawing is permitted.
+ This explicit step requests annotation regardless of enabled;
+ interactive still controls whether drawing is permitted.
+
+ Returns
+ -------
+ str
+ Path to annotations.h5 inside the trial table's annotation directory.
"""
_, run, policy = resolve_band_options(params, execution, annotations)
log(f"Loading trial table {input}", run.verbose)
diff --git a/src/giant_python/extraction/band/background.py b/src/giant_python/extraction/band/background.py
index cb1cdaf0..6e70890c 100644
--- a/src/giant_python/extraction/band/background.py
+++ b/src/giant_python/extraction/band/background.py
@@ -2,10 +2,9 @@
from __future__ import annotations
-from typing import Tuple
-
import numpy as np
import pandas as pd
+from numpy.typing import DTypeLike
from scipy.interpolate import CubicSpline
try:
@@ -15,13 +14,29 @@
def _collect_interp_columns(
- cols, s_c, s_r, sel_idxs_by_col_all, sel_rows, r0, r1
-):
+ cols: np.ndarray,
+ s_c: np.ndarray,
+ s_r: np.ndarray,
+ sel_idxs_by_col_all: dict[int, np.ndarray],
+ sel_rows: np.ndarray,
+ r0: int,
+ r1: int,
+) -> tuple[dict[int, np.ndarray], dict[int, np.ndarray], list[tuple[np.ndarray, int]]]:
"""Group a motion bin's reference pixels by column for interpolation.
- Columns with a single reference pixel become ``single_points`` (copied
- verbatim); columns with several become sorted ``(rows, source-index)``
+ Columns with a single reference pixel become single_points (copied
+ verbatim); columns with several become sorted (rows, source-index)
entries for linear interpolation.
+
+ Returns
+ -------
+ rows_by_col : dict[int, np.ndarray]
+ For each multi-point column, its reference rows sorted ascending.
+ idxs_by_col : dict[int, np.ndarray]
+ For each multi-point column, the source indices matching rows_by_col.
+ single_points : list[tuple[np.ndarray, int]]
+ For each single-reference-pixel column, the selected-pixel indices at that
+ row paired with the source index of the reference pixel.
"""
rows_by_col = {}
idxs_by_col = {}
@@ -46,18 +61,18 @@ def _collect_interp_columns(
# Preserve scientific parity with the reference interpolation branches.
-def _interp_columns( # noqa: C901
- out,
- rows_by_col,
- idxs_by_col,
- sel_idxs_by_col_all,
- sel_rows,
- data,
- frames,
- dtype,
- method="linear",
- spline_weight_cache=None,
-):
+def _interp_columns(
+ out: np.ndarray,
+ rows_by_col: dict[int, np.ndarray],
+ idxs_by_col: dict[int, np.ndarray],
+ sel_idxs_by_col_all: dict[int, np.ndarray],
+ sel_rows: np.ndarray,
+ data: np.ndarray,
+ frames: np.ndarray,
+ dtype: DTypeLike,
+ method: str = "linear",
+ spline_weight_cache: dict[tuple, np.ndarray] | None = None,
+) -> None:
"""Interpolate each multi-point column onto its selected pixels.
Selected rows that coincide with a reference row are copied exactly; those
@@ -67,12 +82,14 @@ def _interp_columns( # noqa: C901
to all complete frames in one matrix multiplication. Linear interpolation
is retained for columns with fewer than three samples and frames containing
missing source values.
+
+ Raises
+ ------
+ ValueError
+ If `method` is neither "linear" nor "cubic".
"""
if method not in {"linear", "cubic"}:
- raise ValueError(
- "interpolation method must be 'linear' or 'cubic', "
- f"got {method!r}"
- )
+ raise ValueError(f"interpolation method must be 'linear' or 'cubic', got {method!r}")
for c_int, rows in rows_by_col.items():
col_sel_pix_idxs = sel_idxs_by_col_all[c_int]
target_rows = sel_rows[col_sel_pix_idxs]
@@ -86,9 +103,7 @@ def _interp_columns( # noqa: C901
if np.any(exact):
exact_rows = np.flatnonzero(exact)
exact_src = src_idx[pos[exact]]
- out[np.ix_(col_sel_pix_idxs[exact_rows], frames)] = data[
- exact_src
- ][:, frames]
+ out[np.ix_(col_sel_pix_idxs[exact_rows], frames)] = data[exact_src][:, frames]
lo = pos - 1
hi = pos
@@ -114,10 +129,7 @@ def _interp_columns( # noqa: C901
hi_v = hi_v[nonzero]
row_lo = row_lo[nonzero]
row_hi = row_hi[nonzero]
- alpha = (
- (target_rows[interp_rows].astype(dtype) - row_lo)
- / (row_hi - row_lo)
- )[:, None]
+ alpha = ((target_rows[interp_rows].astype(dtype) - row_lo) / (row_hi - row_lo))[:, None]
target_indices = col_sel_pix_idxs[interp_rows]
linear_frame_mask = np.ones(frames.size, dtype=bool)
@@ -127,9 +139,7 @@ def _interp_columns( # noqa: C901
complete_frames = np.all(np.isfinite(source_values), axis=0)
if np.any(complete_frames):
source_rows = rows.astype(dtype, copy=False)
- target_interp_rows = target_rows[interp_rows].astype(
- dtype, copy=False
- )
+ target_interp_rows = target_rows[interp_rows].astype(dtype, copy=False)
origin = source_rows[0]
cache_key = (
tuple(source_rows - origin),
@@ -137,9 +147,7 @@ def _interp_columns( # noqa: C901
np.dtype(dtype).str,
)
spline_weights = (
- spline_weight_cache.get(cache_key)
- if spline_weight_cache is not None
- else None
+ spline_weight_cache.get(cache_key) if spline_weight_cache is not None else None
)
if spline_weights is None:
spline_weights = CubicSpline(
@@ -151,12 +159,8 @@ def _interp_columns( # noqa: C901
)(target_interp_rows).astype(dtype, copy=False)
if spline_weight_cache is not None:
spline_weight_cache[cache_key] = spline_weights
- cubic_values = (
- spline_weights @ source_values[:, complete_frames]
- )
- out[np.ix_(target_indices, frames[complete_frames])] = (
- cubic_values
- )
+ cubic_values = spline_weights @ source_values[:, complete_frames]
+ out[np.ix_(target_indices, frames[complete_frames])] = cubic_values
linear_frame_mask = ~complete_frames
if not np.any(linear_frame_mask):
@@ -177,9 +181,9 @@ def build_interp_data(
mot_inds_yx: np.ndarray,
height: int = 800,
width: int = 1280,
- dtype=np.float32,
+ dtype: DTypeLike = np.float32,
method: str = "cubic",
-) -> Tuple[np.ndarray, Tuple[int, int], Tuple[int, int]]:
+) -> tuple[np.ndarray, tuple[int, int], tuple[int, int]]:
"""Interpolate reference-pixel traces onto the selected-pixel grid.
For each kept motion bin, the reference pixels (shifted by the bin's
@@ -194,17 +198,17 @@ def build_interp_data(
ref_r, ref_c : ndarray
Reference-pixel row/column indices for this plane.
sel_pixels_2d : ndarray of shape (n_sel, 2)
- Selected-pixel ``[row, col]`` coordinates for this plane.
+ Selected-pixel [row, col] coordinates for this plane.
unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2)
Kept 2-D motion vectors.
mot_inds_yx : ndarray of shape (n_frames,)
- Per-frame motion-bin index (``-1`` for dropped frames).
+ Per-frame motion-bin index (-1 for dropped frames).
height, width : int
Sensor row/column extents used to window valid shifts.
dtype : numpy dtype
Working/output dtype.
method : {"linear", "cubic"}
- Interpolation along each column (default ``"cubic"``). Cubic mode uses
+ Interpolation along each column (default "cubic"). Cubic mode uses
a natural spline with precomputed geometry weights and falls back to
linear for columns with fewer than three samples or frames with missing
samples.
@@ -214,18 +218,20 @@ def build_interp_data(
out : ndarray of shape (n_sel, n_frames)
Interpolated background estimate (NaN where unsampled).
row_bounds : tuple of int
- ``(r0, r1)`` inclusive row window.
+ (r0, r1) inclusive row window.
col_bounds : tuple of int
- ``(c0, c1)`` inclusive column window.
+ (c0, c1) inclusive column window.
+
+ Raises
+ ------
+ ValueError
+ If `method` is neither "linear" nor "cubic".
"""
ref_r = np.asarray(ref_r, dtype=np.int32)
ref_c = np.asarray(ref_c, dtype=np.int32)
data = np.asarray(data, dtype=dtype)
if method not in {"linear", "cubic"}:
- raise ValueError(
- "interpolation method must be 'linear' or 'cubic', "
- f"got {method!r}"
- )
+ raise ValueError(f"interpolation method must be 'linear' or 'cubic', got {method!r}")
r0 = int(max(0, ref_r.min()) + unique_motion_to_keep_yx[:, 0].min())
r1 = int(min(height, ref_r.max()) + unique_motion_to_keep_yx[:, 0].max())
@@ -237,13 +243,10 @@ def build_interp_data(
sel_cols = sel_pixels_2d[:, 1]
sel_rows = sel_pixels_2d[:, 0]
unique_sel_cols = np.unique(sel_cols)
- sel_idxs_by_col_all = {
- int(c): np.flatnonzero(sel_cols == c) for c in unique_sel_cols
- }
+ sel_idxs_by_col_all = {int(c): np.flatnonzero(sel_cols == c) for c in unique_sel_cols}
frames_by_motion = [
- np.flatnonzero(mot_inds_yx == idx)
- for idx in range(len(unique_motion_to_keep_yx))
+ np.flatnonzero(mot_inds_yx == idx) for idx in range(len(unique_motion_to_keep_yx))
]
spline_weight_cache = {} if method == "cubic" else None
@@ -293,14 +296,12 @@ def baseline_window_frames(align_hz: float, baseline_window_s: float) -> int:
Returns
-------
int
- ``int(align_hz * baseline_window_s)``.
+ int(align_hz * baseline_window_s).
"""
return int(align_hz * baseline_window_s)
-def compute_rolling_baseline(
- interp_data: np.ndarray, baseline_window: int
-) -> np.ndarray:
+def compute_rolling_baseline(interp_data: np.ndarray, baseline_window: int) -> np.ndarray:
"""Compute a NaN-aware rolling-median baseline of the interpolated data.
Each frame's baseline is the median of its centered window, ignoring NaNs,
@@ -311,8 +312,8 @@ def compute_rolling_baseline(
The heavy lifting uses :func:`bottleneck.move_median` (a C sliding-window
median whose cost is close to the moving mean) when available, falling back
- to pandas' skip-list rolling median otherwise. ``bottleneck`` computes a
- *trailing* window, so the data is right-padded with NaNs by ``window // 2``
+ to pandas' skip-list rolling median otherwise. bottleneck computes a
+ *trailing* window, so the data is right-padded with NaNs by window // 2
and the result is sliced back to center each window on its frame.
Parameters
@@ -353,7 +354,8 @@ def compute_rolling_baseline(
# Fallback (no bottleneck): pandas rolls along the row axis, so transpose
# to (n_frames, n_sel), roll each column, and transpose back.
background = (
- pd.DataFrame(interp_data.T)
+ pd
+ .DataFrame(interp_data.T)
.rolling(window=window, center=True, min_periods=1)
.median()
.to_numpy()
@@ -378,7 +380,7 @@ def assemble_background(
"""Map the selected-pixel background back onto superpixels per motion bin.
For each kept motion bin and its frames, each superpixel's motion-shifted
- reference pixel is looked up in ``sel_pix_idxs`` and its background trace
+ reference pixel is looked up in sel_pix_idxs and its background trace
is copied onto that superpixel.
Parameters
@@ -388,7 +390,7 @@ def assemble_background(
unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2)
Kept 2-D motion vectors.
mot_inds_yx : ndarray of shape (n_frames,)
- Per-frame motion-bin index (``-1`` for dropped frames).
+ Per-frame motion-bin index (-1 for dropped frames).
sel_pix_idxs : ndarray of int
Sorted flat selected-pixel indices.
ref_d, ref_r, ref_c : ndarray
@@ -418,17 +420,13 @@ def assemble_background(
bg_idxs = np.searchsorted(sel_pix_idxs, shifted_indices)
idxs_mask = bg_idxs < sel_pix_idxs.size
- idxs_mask[idxs_mask] &= (
- sel_pix_idxs[bg_idxs[idxs_mask]] == shifted_indices[idxs_mask]
- )
+ idxs_mask[idxs_mask] &= sel_pix_idxs[bg_idxs[idxs_mask]] == shifted_indices[idxs_mask]
if np.any(idxs_mask):
valid_rows = np.flatnonzero(idxs_mask)
- background[np.ix_(valid_rows, motion_frames)] = (
- interp_data_background[
- np.ix_(bg_idxs[valid_rows], motion_frames)
- ]
- )
+ background[np.ix_(valid_rows, motion_frames)] = interp_data_background[
+ np.ix_(bg_idxs[valid_rows], motion_frames)
+ ]
return background
@@ -438,10 +436,10 @@ def fit_noise_variance_model(
background: np.ndarray,
v_im: np.ndarray,
vif: float = 1.38,
-) -> Tuple[np.ndarray, float, float]:
+) -> tuple[np.ndarray, float, float]:
"""Calibrate an affine noise-variance model and return per-sample std.
- Fits ``Var ~= Vk * (background * vIM) + Vb`` from the brightest pixels over
+ Fits Var ~= Vk * (background * vIM) + Vb from the brightest pixels over
the first valid frames, then returns the predicted standard deviation for
every sample.
@@ -452,7 +450,7 @@ def fit_noise_variance_model(
background : ndarray of shape (n_superpixels, n_frames)
Per-superpixel background estimate.
v_im : ndarray of shape (n_superpixels, n_frames)
- Inverse count image (``1 / lowResDataCt``).
+ Inverse count image (1 / lowResDataCt).
vif : float
Variance inflation factor.
@@ -465,18 +463,14 @@ def fit_noise_variance_model(
v_b : float
Fitted additive variance floor.
"""
- first_valid_frames = np.flatnonzero(
- np.any(~np.isnan(background[:, :1000]), axis=0)
- )
+ first_valid_frames = np.flatnonzero(np.any(~np.isnan(background[:, :1000]), axis=0))
var_im = np.nanvar(low_res_data_norm[:, first_valid_frames], axis=1)
v_b = np.nanpercentile(var_im, 5) * vif
- var_pred = np.nanmean(
- background[:, first_valid_frames], axis=1
- ) * np.nanmean(v_im[:, first_valid_frames], axis=1)
- sel_bright = var_pred > np.nanpercentile(var_pred, 90)
- v_k = np.nanpercentile(
- (var_im[sel_bright] - (v_b / vif)) / var_pred[sel_bright], 10
+ var_pred = np.nanmean(background[:, first_valid_frames], axis=1) * np.nanmean(
+ v_im[:, first_valid_frames], axis=1
)
+ sel_bright = var_pred > np.nanpercentile(var_pred, 90)
+ v_k = np.nanpercentile((var_im[sel_bright] - (v_b / vif)) / var_pred[sel_bright], 10)
data_std = np.sqrt(np.clip(v_k * background * v_im, 0, None) + v_b)
return data_std, v_k, v_b
@@ -500,6 +494,6 @@ def compute_residual(
Returns
-------
ndarray
- ``(low_res_data_norm - background) / data_std``.
+ (low_res_data_norm - background) / data_std.
"""
return (low_res_data_norm - background) / data_std
diff --git a/src/giant_python/extraction/band/geometry.py b/src/giant_python/extraction/band/geometry.py
index dd14cc4b..71c07bb6 100644
--- a/src/giant_python/extraction/band/geometry.py
+++ b/src/giant_python/extraction/band/geometry.py
@@ -5,17 +5,15 @@
from __future__ import annotations
-from typing import Tuple
-
import numpy as np
-import scipy.ndimage as ndimage
+from scipy import ndimage
def ref_pixs_to_drc(
ref_pixs: np.ndarray,
dmd_pixels_per_column: int,
dmd_pixels_per_row: int,
-) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Map flat reference-pixel indices to DMD (depth, column, row) indices.
Parameters
@@ -34,9 +32,7 @@ def ref_pixs_to_drc(
plane = int(dmd_pixels_per_column) * int(dmd_pixels_per_row)
npc = int(dmd_pixels_per_column)
ref_d = np.floor_divide(ref_pixs, plane).astype(np.int32)
- ref_c = np.floor_divide(
- ref_pixs - ref_d.astype(np.int64) * plane, npc
- ).astype(np.int32)
+ ref_c = np.floor_divide(ref_pixs - ref_d.astype(np.int64) * plane, npc).astype(np.int32)
ref_r = np.mod(ref_pixs, npc).astype(np.int32)
return ref_d, ref_c, ref_r
@@ -47,7 +43,7 @@ def build_subsample_matrix_inds(
) -> np.ndarray:
"""Build the superpixel -> reference-pixel index map for one DMD.
- For each superpixel, picks the element at index ``len(open_pixs) // 2``
+ For each superpixel, picks the element at index len(open_pixs) // 2
in sparse-mask order, for both odd and even counts; values are not sorted.
Parameters
@@ -55,12 +51,12 @@ def build_subsample_matrix_inds(
all_super_pixel_ids : ndarray of shape (n_superpixels, 1)
Superpixel ids for this DMD.
sparse_mask_inds : ndarray of shape (N, 2)
- ``[open_pixel (1-based), superpixel_id (1-based)]`` rows.
+ [open_pixel (1-based), superpixel_id (1-based)] rows.
Returns
-------
ndarray of shape (n_superpixels, 2), int32
- ``[ref_pixel (0-based), superpixel_id (1-based)]`` per superpixel.
+ [ref_pixel (0-based), superpixel_id (1-based)] per superpixel.
"""
num_super_pixels = all_super_pixel_ids.shape[0]
out = np.zeros((num_super_pixels, 2), dtype=np.int32)
@@ -74,7 +70,13 @@ def build_subsample_matrix_inds(
def _pad_to(psf2d: np.ndarray, height: int, width: int) -> np.ndarray:
- """Center-pad a 2-D PSF to ``(height, width)`` with its minimum value."""
+ """Center-pad a 2-D PSF to (height, width) with its minimum value.
+
+ Returns
+ -------
+ ndarray
+ The padded PSF of shape (height, width).
+ """
ph, pw = psf2d.shape
pad_r = (height - ph) // 2
pad_c = (width - pw) // 2
@@ -86,7 +88,13 @@ def _pad_to(psf2d: np.ndarray, height: int, width: int) -> np.ndarray:
def build_combined_psf(psfs: list) -> np.ndarray:
- """Stack per-DMD PSFs into a ``(n_dmds, H, W)`` array, center-padded."""
+ """Stack per-DMD PSFs into a (n_dmds, H, W) array, center-padded.
+
+ Returns
+ -------
+ ndarray of float32
+ Combined PSFs of shape (n_dmds, H, W).
+ """
height = max(p.shape[0] for p in psfs)
width = max(p.shape[1] for p in psfs)
combined = np.zeros((len(psfs), height, width), dtype=np.float32)
@@ -96,7 +104,7 @@ def build_combined_psf(psfs: list) -> np.ndarray:
def threshold_and_crop_psf(psf2d: np.ndarray) -> np.ndarray:
- """Zero values below ``max * exp(-3)`` and crop boundary zeros.
+ """Zero values below max * exp(-3) and crop boundary zeros.
Parameters
----------
@@ -128,7 +136,7 @@ def build_selected_pixel_mask(
dmd_pixels_per_column: int,
dmd_pixels_per_row: int,
psf2d: np.ndarray,
-) -> Tuple[np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray]:
"""Build the selected-pixel support mask over all kept motion shifts.
Marks every reference pixel shifted by each kept 2-D motion bin, then
@@ -148,13 +156,11 @@ def build_selected_pixel_mask(
Returns
-------
sel_pix_mask : ndarray of bool
- ``(num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row)`` support.
+ (num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row) support.
sel_pix_idxs : ndarray of int
Flattened indices of the selected pixels.
"""
- sel_pix_mask = np.zeros(
- (num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row), dtype=bool
- )
+ sel_pix_mask = np.zeros((num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row), dtype=bool)
for i in range(len(unique_motion_to_keep_yx)):
sel_pix_mask[
ref_d,
@@ -174,7 +180,7 @@ def pixel_coords_from_idxs(
dmd_pixels_per_column: int,
dmd_pixels_per_row: int,
) -> np.ndarray:
- """Convert flat selected-pixel indices to ``[z, row, col]`` coordinates.
+ """Convert flat selected-pixel indices to [z, row, col] coordinates.
Parameters
----------
@@ -186,7 +192,7 @@ def pixel_coords_from_idxs(
Returns
-------
ndarray of shape (n_sel, 3), int32
- ``[z, row, col]`` per selected pixel.
+ [z, row, col] per selected pixel.
"""
plane_size = dmd_pixels_per_column * dmd_pixels_per_row
pixel_coords = np.empty((len(sel_pix_idxs), 3), dtype=np.int32)
@@ -202,8 +208,8 @@ def selected_pixels_2d_for_plane(
plane_z: int,
dmd_pixels_per_column: int,
dmd_pixels_per_row: int,
-) -> Tuple[np.ndarray, np.ndarray]:
- """Return the in-plane ``[row, col]`` coords of one z-plane's pixels.
+) -> tuple[np.ndarray, np.ndarray]:
+ """Return the in-plane [row, col] coords of one z-plane's pixels.
Parameters
----------
@@ -217,18 +223,16 @@ def selected_pixels_2d_for_plane(
Returns
-------
z_idxs : ndarray
- Positions (into ``sel_pix_idxs``) of pixels in ``plane_z``.
+ Positions (into sel_pix_idxs) of pixels in plane_z.
sel_pixels_2d : ndarray of shape (n_plane, 2)
- ``[row, col]`` coordinates of those pixels.
+ [row, col] coordinates of those pixels.
"""
plane_size = dmd_pixels_per_column * dmd_pixels_per_row
sel_pix_z = sel_pix_idxs // plane_size
sel_pix_remainder = sel_pix_idxs % plane_size
z_idxs = np.flatnonzero(sel_pix_z == plane_z)
- sel_pixels_2d = np.column_stack(
- [
- sel_pix_remainder[z_idxs] // dmd_pixels_per_row,
- sel_pix_remainder[z_idxs] % dmd_pixels_per_row,
- ]
- )
+ sel_pixels_2d = np.column_stack([
+ sel_pix_remainder[z_idxs] // dmd_pixels_per_row,
+ sel_pix_remainder[z_idxs] % dmd_pixels_per_row,
+ ])
return z_idxs, sel_pixels_2d
diff --git a/src/giant_python/extraction/band/inputs.py b/src/giant_python/extraction/band/inputs.py
index 90489a5b..77506189 100644
--- a/src/giant_python/extraction/band/inputs.py
+++ b/src/giant_python/extraction/band/inputs.py
@@ -11,7 +11,6 @@
import os
from importlib import resources
from pathlib import Path
-from typing import Optional, Tuple, Union
import numpy as np
@@ -22,8 +21,8 @@
from .geometry import build_combined_psf, threshold_and_crop_psf
-def load_lookup_table(path: Union[str, Path], n_dmds: int) -> dict:
- """Load the band-registration lookup table (``bandRegLookupTable.h5``).
+def load_lookup_table(path: str | Path, n_dmds: int) -> dict:
+ """Load the band-registration lookup table (bandRegLookupTable.h5).
Parameters
----------
@@ -35,8 +34,8 @@ def load_lookup_table(path: Union[str, Path], n_dmds: int) -> dict:
Returns
-------
dict
- ``{"allSuperPixelIDs": {...}, "sparseMaskInds": {...},
- "fastZ2RefZ": {...}}``, each an inner dict keyed ``DMD{N}``.
+ {"allSuperPixelIDs": {...}, "sparseMaskInds": {...},
+ "fastZ2RefZ": {...}}, each an inner dict keyed DMD{N}.
Raises
------
@@ -50,19 +49,11 @@ def load_lookup_table(path: Union[str, Path], n_dmds: int) -> dict:
for d in range(n_dmds):
p = lt.get(f"Path{d + 1}", lt.get(f"DMD{d + 1}"))
if p is None:
- raise ValueError(
- f"Missing lookup-table group Path{d + 1} or DMD{d + 1}"
- )
+ raise ValueError(f"Missing lookup-table group Path{d + 1} or DMD{d + 1}")
key = f"DMD{d + 1}"
- all_super_pixel_ids[key] = (
- np.asarray(p["allSuperPixelIDs"]).reshape(-1, 1).astype(np.int32)
- )
- sparse_mask_inds[key] = np.asarray(p["sparseMaskInds"]).astype(
- np.int32
- )
- fastz_to_refz[key] = (
- np.asarray(p["fastZ2RefZ"]).reshape(-1, 1).astype(np.int32)
- )
+ all_super_pixel_ids[key] = np.asarray(p["allSuperPixelIDs"]).reshape(-1, 1).astype(np.int32)
+ sparse_mask_inds[key] = np.asarray(p["sparseMaskInds"]).astype(np.int32)
+ fastz_to_refz[key] = np.asarray(p["fastZ2RefZ"]).reshape(-1, 1).astype(np.int32)
return {
"allSuperPixelIDs": all_super_pixel_ids,
"sparseMaskInds": sparse_mask_inds,
@@ -71,22 +62,26 @@ def load_lookup_table(path: Union[str, Path], n_dmds: int) -> dict:
def _ref_stack_group(ref_stack: dict, dmd_ix: int) -> dict:
- """Return a Path/DMD reference subgroup; raise ValueError if missing."""
- group = ref_stack.get(
- f"Path{dmd_ix + 1}", ref_stack.get(f"DMD{dmd_ix + 1}")
- )
+ """Return a Path/DMD reference subgroup; raise ValueError if missing.
+
+ Returns
+ -------
+ dict
+ The Path group of ref_stack, falling back to DMD.
+
+ Raises
+ ------
+ ValueError
+ If neither the Path nor the DMD group exists in ref_stack.
+ """
+ group = ref_stack.get(f"Path{dmd_ix + 1}", ref_stack.get(f"DMD{dmd_ix + 1}"))
if group is None:
- raise ValueError(
- f"Missing reference-stack group Path{dmd_ix + 1} "
- f"or DMD{dmd_ix + 1}"
- )
+ raise ValueError(f"Missing reference-stack group Path{dmd_ix + 1} or DMD{dmd_ix + 1}")
return group
-def find_reference_file(
- datadr: Union[str, Path], dmd_ix: int
-) -> Optional[str]:
- """Find the REFERENCE tif for a DMD under ``datadr`` (recursive glob).
+def find_reference_file(datadr: str | Path, dmd_ix: int) -> str | None:
+ """Find the REFERENCE tif for a DMD under datadr (recursive glob).
Parameters
----------
@@ -98,7 +93,7 @@ def find_reference_file(
Returns
-------
str or None
- Path to the first matching REFERENCE tif, or ``None`` if none found.
+ Path to the first matching REFERENCE tif, or None if none found.
"""
patterns = (
f"**/*DMD{dmd_ix + 1}_CONFIG2-REFERENCE*",
@@ -112,38 +107,33 @@ def find_reference_file(
def load_reference_stack(
- datadr: Union[str, Path],
+ datadr: str | Path,
ref_stack_meta: dict,
dmd_ix: int,
-) -> Tuple[Optional[np.ndarray], np.ndarray, Optional[str]]:
+) -> tuple[np.ndarray | None, np.ndarray, str | None]:
"""Load the band reference stack for one DMD.
- Reads the REFERENCE tif from ``datadr`` but takes the channel list from the
+ Reads the REFERENCE tif from datadr but takes the channel list from the
trial table's embedded ref_stack metadata. The raw counts are scaled by
- ``1/100`` and reshaped to ``[channels, z, y, x]``.
+ 1/100 and reshaped to [channels, z, y, x].
Parameters
----------
datadr : str or Path
Raw-data directory.
ref_stack_meta : dict
- The trial table's ``ref_stack`` sub-struct.
+ The trial table's ref_stack sub-struct.
dmd_ix : int
0-based DMD index.
Returns
-------
ref_stack : ndarray or None
- ``[channels, z, y, x]`` stack, or ``None`` if no REFERENCE file found.
+ [channels, z, y, x] stack, or None if no REFERENCE file found.
channels : ndarray
Channel indices for this DMD.
ref_file : str or None
- The REFERENCE file used, or ``None``.
-
- Raises
- ------
- ValueError
- If the requested DMD has no Path/DMD reference metadata group.
+ The REFERENCE file used, or None.
"""
grp = _ref_stack_group(ref_stack_meta, dmd_ix)
channels = np.asarray(grp["channels"]).reshape(-1)
@@ -160,12 +150,12 @@ def load_reference_stack(
def default_psf(dilation: int) -> np.ndarray:
- """Load a bundled default PSF template (``assets/psfs/dil-NN.tif``).
+ """Load a bundled default PSF template (assets/psfs/dil-NN.tif).
Parameters
----------
dilation : int
- Dilation size selecting ``dil-{dilation:02d}.tif`` (e.g. ``17``).
+ Dilation size selecting dil-{dilation:02d}.tif (e.g. 17).
Returns
-------
@@ -173,12 +163,7 @@ def default_psf(dilation: int) -> np.ndarray:
The PSF template image.
"""
name = f"dil-{int(dilation):02d}.tif"
- resource = (
- resources.files("giant_python")
- .joinpath("assets")
- .joinpath("psfs")
- .joinpath(name)
- )
+ resource = resources.files("giant_python").joinpath("assets").joinpath("psfs").joinpath(name)
with resources.as_file(resource) as p:
return read_tiff(str(p)).astype(np.float32)
@@ -186,8 +171,8 @@ def default_psf(dilation: int) -> np.ndarray:
def load_psf(dilation: int, n_dmds: int) -> dict:
"""Load per-DMD PSFs from bundled assets, thresholded and cropped.
- Each DMD uses the same ``dil-NN.tif`` template from
- ``assets/psfs/``, center-padded to a common size when shapes differ.
+ Each DMD uses the same dil-NN.tif template from
+ assets/psfs/, center-padded to a common size when shapes differ.
Parameters
----------
@@ -199,21 +184,24 @@ def load_psf(dilation: int, n_dmds: int) -> dict:
Returns
-------
dict
- ``{"DMD{N}": psf2d}`` thresholded/cropped PSFs.
+ {"DMD{N}": psf2d} thresholded/cropped PSFs.
"""
psfs = [default_psf(dilation) for _ in range(n_dmds)]
psf_combined = build_combined_psf(psfs)
- return {
- f"DMD{i + 1}": threshold_and_crop_psf(psf_combined[i])
- for i in range(n_dmds)
- }
+ return {f"DMD{i + 1}": threshold_and_crop_psf(psf_combined[i]) for i in range(n_dmds)}
-def load_alignment_data_h5(path: Union[str, Path]) -> dict:
+def load_alignment_data_h5(path: str | Path) -> dict:
"""Read band alignment, negating saved offline shifts exactly once.
Online shifts and frame indexes are unchanged. Negation allocates arrays
and does not modify values owned by the raw reader.
+
+ Returns
+ -------
+ dict
+ The alignment data read from path, with motionDSr, motionDSc and
+ motionDSz negated (or None where absent).
"""
data = read_alignment_data_h5(path)
return {
@@ -226,27 +214,45 @@ def load_alignment_data_h5(path: Union[str, Path]) -> dict:
def _resolve_fn_adata(fn_adata: np.ndarray, moco_save_dr: str) -> np.ndarray:
- """Resolve alignment basenames, preserving empty entries and array rank."""
+ """Resolve alignment basenames, preserving empty entries and array rank.
+
+ Returns
+ -------
+ np.ndarray
+ Object array shaped (n_dmds, n_trials) of alignment-file paths joined onto
+ moco_save_dr; empty entries stay "".
+ """
n_dmds, n_trials = fn_adata.shape
out = np.empty((n_dmds, n_trials), dtype=object)
for d in range(n_dmds):
for t in range(n_trials):
entry = fn_adata[d, t]
- out[d, t] = (
- ""
- if entry in (None, "")
- else os.path.join(moco_save_dr, str(entry))
- )
+ out[d, t] = "" if entry in (None, "") else os.path.join(moco_save_dr, str(entry))
return out
-def load_trial_table(path: Union[str, Path, TrialTable]) -> dict:
+def load_trial_table(path: str | Path | TrialTable) -> dict:
"""Prepare a structural band view from a path OR an already loaded table.
Never reload a TrialTable. This does not probe files or read alignments;
- callers retain control of ``compute_keep_trials`` and ``read_align_info``.
- The view carries the original model as ``trial_table`` and its provenance
- as ``source_path``; all historical flattened runtime keys are retained.
+ callers retain control of compute_keep_trials and read_align_info.
+ The view carries the original model as trial_table and its provenance
+ as source_path; all historical flattened runtime keys are retained.
+
+ Returns
+ -------
+ dict
+ The structural band view: trial_table, source_path, directory paths
+ (datadr, savedr, moco_save_dr, annotation_save_dr,
+ src_extr_save_dr), align_params, n_dmds, n_trials, the
+ filename, first_line, last_line and absolute fn_adata arrays, and
+ ref_stack.
+
+ Raises
+ ------
+ ValueError
+ If the table has no SLAP2 info or no motion_correction/fn_adata, i.e. it is not
+ a registered SLAP2 band trial table.
"""
tt = path if isinstance(path, TrialTable) else TrialTable.from_h5(path)
slap2 = tt.slap2_info
@@ -262,16 +268,12 @@ def load_trial_table(path: Union[str, Path, TrialTable]) -> dict:
moco_save_dr = os.path.join(result_dr, "motion_correction")
align_params = {
key: to_serializable(val)
- for key, val in (
- motion_correction.get("align_params", {}) or {}
- ).items()
+ for key, val in (motion_correction.get("align_params", {}) or {}).items()
}
filenames = np.atleast_2d(np.asarray(tt.filename, dtype=object))
first_line = np.atleast_2d(np.asarray(slap2.first_line))
last_line = np.atleast_2d(np.asarray(slap2.last_line))
- fn_adata = np.atleast_2d(
- np.asarray(motion_correction["fn_adata"], dtype=object)
- )
+ fn_adata = np.atleast_2d(np.asarray(motion_correction["fn_adata"], dtype=object))
n_dmds, n_trials = filenames.shape
return {
"trial_table": tt,
@@ -295,9 +297,16 @@ def load_trial_table(path: Union[str, Path, TrialTable]) -> dict:
def compute_keep_trials(
fn_adata_abs: np.ndarray,
filename: np.ndarray,
- datadr: Union[str, Path],
+ datadr: str | Path,
) -> np.ndarray:
- """Keep trials only when both alignment and raw source files exist."""
+ """Keep trials only when both alignment and raw source files exist.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean array shaped (n_dmds, n_trials), True where both the alignment
+ file and the raw source file exist.
+ """
fn_adata_abs = np.atleast_2d(np.asarray(fn_adata_abs, dtype=object))
filename = np.atleast_2d(np.asarray(filename, dtype=object))
n_dmds, n_trials = fn_adata_abs.shape
@@ -322,7 +331,15 @@ def read_align_info(
keep_trials: np.ndarray,
n_dmds: int,
) -> tuple:
- """Read first-kept-trial alignHz per DMD and the last channel count."""
+ """Read first-kept-trial alignHz per DMD and the last channel count.
+
+ Returns
+ -------
+ align_hz : dict
+ {"DMD{N}": alignHz} from the first kept trial of each DMD that has one.
+ num_channels : int or None
+ numChannels from the last DMD with a kept trial, or None if no trial is kept.
+ """
fn_adata_abs = np.atleast_2d(np.asarray(fn_adata_abs, dtype=object))
keep_trials = np.atleast_2d(np.asarray(keep_trials))
align_hz = {}
diff --git a/src/giant_python/extraction/band/localization.py b/src/giant_python/extraction/band/localization.py
index 66087175..10451c40 100644
--- a/src/giant_python/extraction/band/localization.py
+++ b/src/giant_python/extraction/band/localization.py
@@ -1,42 +1,42 @@
"""Superpixel-space NMF source localization.
Ported from the source-localization block of
-``extractSLAP2IntegrationSources.py`` (ref 2519-2908). Given the peak seeds
+extractSLAP2IntegrationSources.py (ref 2519-2908). Given the peak seeds
from :mod:`giant_python.numerics.peaks` and the noise-normalized residual /
-per-motion ``H`` matrices from :mod:`giant_python.extraction.band.background`
+per-motion H matrices from :mod:`giant_python.extraction.band.background`
and :mod:`giant_python.extraction.band.operators`, this
-module fits Gaussian spatial profiles (``A``) and per-motion temporal weights
-(``phi``) that reconstruct the residual in superpixel space.
+module fits Gaussian spatial profiles (A) and per-motion temporal weights
+(phi) that reconstruct the residual in superpixel space.
Each outer iteration:
1. runs motion-binned multiplicative NMF (in random motion order) to get a
- per-motion superpixel target ``X_mots`` (:func:`multiplicative_nmf`),
+ per-motion superpixel target X_mots (:func:`multiplicative_nmf`),
2. fits the parametric Gaussian profiles to those targets with Adam
(:func:`fit_gaussian_profiles`),
-3. rebuilds ``A`` and least-squares-solves ``phi``
+3. rebuilds A and least-squares-solves phi
(:func:`fit_phi_all_motions`),
4. sorts sources by explained variance, and every fourth iteration prunes
- sources whose SNR falls below ``1/3``.
+ sources whose SNR falls below 1/3.
-The final per-source low-resolution SNR is returned alongside ``A``, ``phi``,
-the fitted ``source_params`` ``[z, y, x, sigma_y, sigma_x, tilt]``, and the
-(sorted/pruned) ``source_seeds``.
+The final per-source low-resolution SNR is returned alongside A, phi,
+the fitted source_params [z, y, x, sigma_y, sigma_x, tilt], and the
+(sorted/pruned) source_seeds.
This block is intentionally stochastic (random motion order via
-``torch.randperm`` in NMF and Adam). When :func:`fit_sources` receives a
-``seed``, each outer iteration draws from its own ``torch.Generator`` derived
-from ``(seed, iteration)``, so a run is reproducible and independent of the
-global torch RNG state; with ``seed=None`` the global RNG is used. The
-``randperm`` calls are preserved in the same order as the reference, but the
+torch.randperm in NMF and Adam). When :func:`fit_sources` receives a
+seed, each outer iteration draws from its own torch.Generator derived
+from (seed, iteration), so a run is reproducible and independent of the
+global torch RNG state; with seed=None the global RNG is used. The
+randperm calls are preserved in the same order as the reference, but the
unregularized QR temporal solve changes numerical results. The reference's
-loss-only ``phi`` recomputation and ``print``/warning diagnostics are dropped
+loss-only phi recomputation and print/warning diagnostics are dropped
(they do not affect the outputs and consume no RNG).
"""
from __future__ import annotations
-from typing import List, cast
+from typing import cast
import numpy as np
import torch
@@ -54,10 +54,10 @@ def sel_pix_gaussian_profile(
Parameters
----------
gaussian_params : torch.Tensor of shape (N, 6)
- Per-source ``[z, mu_y, mu_x, sigma_y, sigma_x, tilt]`` (the tilt is
- mapped to a correlation coefficient via ``tanh``).
+ Per-source [z, mu_y, mu_x, sigma_y, sigma_x, tilt] (the tilt is
+ mapped to a correlation coefficient via tanh).
pixel_coords_tensor : torch.Tensor of shape (n_sel, 3)
- Selected-pixel ``[z, row, col]`` coordinates.
+ Selected-pixel [z, row, col] coordinates.
Returns
-------
@@ -101,9 +101,9 @@ def sel_pix_patch_profile(
Parameters
----------
patch_params : torch.Tensor of shape (N, 5)
- Per-source ``[z, mu_y, mu_x, y_radius, x_radius]``.
+ Per-source [z, mu_y, mu_x, y_radius, x_radius].
pixel_coords_tensor : torch.Tensor of shape (n_sel, 3)
- Selected-pixel ``[z, row, col]`` coordinates.
+ Selected-pixel [z, row, col] coordinates.
Returns
-------
@@ -128,12 +128,12 @@ def sel_pix_patch_profile(
def init_source_params(source_seeds: np.ndarray) -> torch.Tensor:
- """Initialize ``[z, y, x, sigma_y=1, sigma_x=1, tilt=0]`` per source.
+ """Initialize [z, y, x, sigma_y=1, sigma_x=1, tilt=0] per source.
Parameters
----------
source_seeds : ndarray of shape (N, 3)
- Peak seeds ``[z, mu_y, mu_x]``.
+ Peak seeds [z, mu_y, mu_x].
Returns
-------
@@ -163,13 +163,13 @@ def build_a_patches(
Parameters
----------
source_seeds : ndarray of shape (N, 3)
- Peak seeds ``[z, mu_y, mu_x]``.
+ Peak seeds [z, mu_y, mu_x].
pixel_coords_tensor : torch.Tensor of shape (n_sel, 3)
Selected-pixel coordinates.
sel_pix_idxs : ndarray of int
- Flat selected-pixel indices into the ``n_pixels`` grid.
+ Flat selected-pixel indices into the n_pixels grid.
n_pixels : int
- Total number of image pixels (``z * rows * cols``).
+ Total number of image pixels (z * rows * cols).
d_xy : float
Half-width of the square support patch, in pixels.
@@ -187,24 +187,22 @@ def build_a_patches(
],
dim=1,
)
- a_patches[sel_pix_idxs, :] = sel_pix_patch_profile(
- patch_params, pixel_coords_tensor
- )
+ a_patches[sel_pix_idxs, :] = sel_pix_patch_profile(patch_params, pixel_coords_tensor)
return a_patches
def build_x_support_mots(
- h_mots: List[torch.Tensor],
+ h_mots: list[torch.Tensor],
a_patches: torch.Tensor,
sel_pix_idxs: np.ndarray,
n_motions: int,
-) -> List[torch.Tensor]:
+) -> list[torch.Tensor]:
"""Project each source's support patch into per-motion superpixel space.
Parameters
----------
h_mots : list of torch.Tensor
- Per-motion sparse superpixel<-pixel ``H`` matrices.
+ Per-motion sparse superpixel<-pixel H matrices.
a_patches : torch.Tensor of bool, shape (n_pixels, N)
Support mask from :func:`build_a_patches`.
sel_pix_idxs : ndarray of int
@@ -215,11 +213,10 @@ def build_x_support_mots(
Returns
-------
list of torch.Tensor of bool
- One ``(n_superpixels, N)`` support mask per motion bin.
+ One (n_superpixels, N) support mask per motion bin.
"""
return [
- torch.sparse.mm(h_mots[i], a_patches[sel_pix_idxs, :].float()) > 0
- for i in range(n_motions)
+ torch.sparse.mm(h_mots[i], a_patches[sel_pix_idxs, :].float()) > 0 for i in range(n_motions)
]
@@ -230,7 +227,7 @@ def project_spatial_profiles(
n_pixels: int,
a_patches: torch.Tensor,
) -> torch.Tensor:
- """Build the mass-normalized Gaussian spatial profiles ``A``.
+ """Build the mass-normalized Gaussian spatial profiles A.
The Gaussian profile is masked by the support patch and normalized so each
source's column sums to 1.
@@ -255,9 +252,7 @@ def project_spatial_profiles(
"""
n_sources = source_params.shape[0]
a = torch.zeros((n_pixels, n_sources), dtype=torch.float32)
- a[sel_pix_idxs, :] = sel_pix_gaussian_profile(
- source_params, pixel_coords_tensor
- )
+ a[sel_pix_idxs, :] = sel_pix_gaussian_profile(source_params, pixel_coords_tensor)
a[~a_patches] = 0
mass = torch.sum(a, dim=0, keepdim=True)
mass[mass <= 0] = 1
@@ -266,31 +261,41 @@ def project_spatial_profiles(
def _motion_frames(mot_inds_yx: np.ndarray, i: int) -> np.ndarray:
- """Return the frame indices belonging to motion bin ``i``."""
+ """Return the frame indices belonging to motion bin i.
+
+ Returns
+ -------
+ np.ndarray
+ Indices of the frames whose motion bin equals i.
+ """
return np.flatnonzero(mot_inds_yx == i)
-def solve_phi_motion(
- x: torch.Tensor, data_motion: torch.Tensor
-) -> torch.Tensor:
+def solve_phi_motion(x: torch.Tensor, data_motion: torch.Tensor) -> torch.Tensor:
"""Least-squares temporal weights for one motion's superpixel profiles.
- Uses column-pivoted QR, ``X[:, piv] = Q R``, to return a basic solution
- as in MATLAB's rectangular ``mldivide``: solve the leading independent
+ Uses column-pivoted QR, X[:, piv] = Q R, to return a basic solution
+ as in MATLAB's rectangular mldivide: solve the leading independent
triangular block and set the remaining pivoted coefficients to zero.
Rank-deficient and underdetermined systems therefore have at most
- ``rank(X)`` nonzero coefficients per frame, not a minimum-norm solution.
+ rank(X) nonzero coefficients per frame, not a minimum-norm solution.
No normal equations or ridge regularization are used.
- Numerical rank uses the cutoff ``max(X.shape) * eps * abs(R[0, 0])``.
+ Numerical rank uses the cutoff max(X.shape) * eps * abs(R[0, 0]).
Pivot ties and borderline rank decisions can differ from MATLAB.
Inputs must be real float32/float64 CPU tensors without gradients;
- ``x`` must be finite. Data frames containing any NaN or infinity return
+ x must be finite. Data frames containing any NaN or infinity return
NaN for all sources; only fully finite frames enter the solve. Missing
observations are not replaced with zeros or used for partial-frame fits.
- Returns ``phiáµ€`` (frames x sources), preserving the input dtype.
+ Returns phiáµ€ (frames x sources), preserving the input dtype.
Shared by the NMF fits here and the high-res trace solve in
:mod:`giant_python.extraction.band.traces`.
+
+ Returns
+ -------
+ torch.Tensor
+ phiáµ€ with shape (frames, sources), in the input dtype. Frames
+ containing any NaN or infinity are NaN for all sources.
"""
x_array = x.numpy()
data_array = data_motion.numpy()
@@ -311,9 +316,7 @@ def solve_phi_motion(
rank = int(np.count_nonzero(np.cumprod(diagonal > tolerance)))
if rank and np.any(valid_frames):
# Avoid copying the observation matrix in the usual all-finite case.
- finite_data = (
- data_array if np.all(valid_frames) else data_array[:, valid_frames]
- )
+ finite_data = data_array if np.all(valid_frames) else data_array[:, valid_frames]
phi[np.ix_(piv[:rank], valid_frames)] = solve_triangular(
r[:rank, :rank], q[:, :rank].T @ finite_data
)
@@ -322,27 +325,27 @@ def solve_phi_motion(
def fit_phi_all_motions(
a: torch.Tensor,
- h_mots: List[torch.Tensor],
+ h_mots: list[torch.Tensor],
sel_pix_idxs: np.ndarray,
data_for_nmf: torch.Tensor,
mot_inds_yx: np.ndarray,
n_motions: int,
phi_low_res: torch.Tensor,
) -> torch.Tensor:
- """Least-squares-solve the temporal weights ``phi`` for every motion bin.
+ """Least-squares-solve the temporal weights phi for every motion bin.
Parameters
----------
a : torch.Tensor of shape (n_pixels, N)
Spatial profiles.
h_mots : list of torch.Tensor
- Per-motion sparse ``H`` matrices.
+ Per-motion sparse H matrices.
sel_pix_idxs : ndarray of int
Flat selected-pixel indices.
data_for_nmf : torch.Tensor of shape (n_superpixels, n_frames)
The residual data being reconstructed.
mot_inds_yx : ndarray of shape (n_frames,)
- Per-frame motion-bin index (``-1`` for dropped frames).
+ Per-frame motion-bin index (-1 for dropped frames).
n_motions : int
Number of motion bins.
phi_low_res : torch.Tensor of shape (n_frames, N)
@@ -351,7 +354,7 @@ def fit_phi_all_motions(
Returns
-------
torch.Tensor
- ``phi_low_res`` with each motion's frames filled.
+ phi_low_res with each motion's frames filled.
"""
for i in range(n_motions):
frames = _motion_frames(mot_inds_yx, i)
@@ -362,8 +365,8 @@ def fit_phi_all_motions(
def multiplicative_nmf(
a: torch.Tensor,
- h_mots: List[torch.Tensor],
- x_support_mots: List[torch.Tensor],
+ h_mots: list[torch.Tensor],
+ x_support_mots: list[torch.Tensor],
sel_pix_idxs: np.ndarray,
data_for_nmf: torch.Tensor,
mot_inds_yx: np.ndarray,
@@ -371,21 +374,21 @@ def multiplicative_nmf(
sparse_fac: float,
max_iters: int,
generator: torch.Generator | None = None,
-) -> List[torch.Tensor]:
+) -> list[torch.Tensor]:
"""Motion-binned multiplicative NMF, producing per-motion spatial targets.
- Visits motion bins in a random order (``torch.randperm``). For each bin it
- projects ``A`` into superpixel space, initializes ``phi`` by projected
- least squares, then alternates multiplicative updates of ``phi`` and the
+ Visits motion bins in a random order (torch.randperm). For each bin it
+ projects A into superpixel space, initializes phi by projected
+ least squares, then alternates multiplicative updates of phi and the
spatial
- target ``X`` under the support constraint, periodically sparsifying ``X``.
+ target X under the support constraint, periodically sparsifying X.
Parameters
----------
a : torch.Tensor of shape (n_pixels, N)
Current spatial profiles.
h_mots : list of torch.Tensor
- Per-motion sparse ``H`` matrices.
+ Per-motion sparse H matrices.
x_support_mots : list of torch.Tensor of bool
Per-motion superpixel support masks.
sel_pix_idxs : ndarray of int
@@ -397,18 +400,18 @@ def multiplicative_nmf(
n_motions : int
Number of motion bins.
sparse_fac : float
- Sparsification floor subtracted from the max-normalized ``X``.
+ Sparsification floor subtracted from the max-normalized X.
max_iters : int
Multiplicative-update iterations per motion bin.
generator : torch.Generator or None
- RNG for the motion order; ``None`` uses the global torch RNG.
+ RNG for the motion order; None uses the global torch RNG.
Returns
-------
list of torch.Tensor
- Per-motion fitted superpixel spatial targets ``X_mots``.
+ Per-motion fitted superpixel spatial targets X_mots.
"""
- x_mots: List[torch.Tensor | None] = [None] * n_motions
+ x_mots: list[torch.Tensor | None] = [None] * n_motions
shuffled_indices = torch.randperm(n_motions, generator=generator)
for idx in shuffled_indices:
# randperm uses an integer dtype, so item() returns a Python int.
@@ -445,14 +448,14 @@ def multiplicative_nmf(
x_mots[i] = x
# randperm visits every slot exactly once, including the empty case.
- return cast(List[torch.Tensor], x_mots)
+ return cast(list[torch.Tensor], x_mots)
def fit_gaussian_profiles(
source_params: torch.Tensor,
source_seeds: np.ndarray,
- x_mots: List[torch.Tensor],
- h_mots: List[torch.Tensor],
+ x_mots: list[torch.Tensor],
+ h_mots: list[torch.Tensor],
pixel_coords_tensor: torch.Tensor,
a_patches: torch.Tensor,
sel_pix_idxs: np.ndarray,
@@ -466,9 +469,9 @@ def fit_gaussian_profiles(
"""Adam-fit the Gaussian source parameters to the per-motion NMF targets.
Optimizes location, scale, and tilt to make the projected Gaussian profiles
- match ``X_mots`` (one motion per epoch, in random rounds). Locations are
- clamped to +/- ``d_xy`` of the seed and sigmas to ``[0.3, 5]``. Stops early
- when consecutive full-round losses differ by less than ``gd_tol``.
+ match X_mots (one motion per epoch, in random rounds). Locations are
+ clamped to +/- d_xy of the seed and sigmas to [0.3, 5]. Stops early
+ when consecutive full-round losses differ by less than gd_tol.
Parameters
----------
@@ -479,7 +482,7 @@ def fit_gaussian_profiles(
x_mots : list of torch.Tensor
Per-motion NMF spatial targets.
h_mots : list of torch.Tensor
- Per-motion sparse ``H`` matrices.
+ Per-motion sparse H matrices.
pixel_coords_tensor : torch.Tensor of shape (n_sel, 3)
Selected-pixel coordinates.
a_patches : torch.Tensor of bool
@@ -497,7 +500,7 @@ def fit_gaussian_profiles(
gd_tol : float
Convergence tolerance on consecutive round losses.
generator : torch.Generator or None
- RNG for the motion order; ``None`` uses the global torch RNG.
+ RNG for the motion order; None uses the global torch RNG.
Returns
-------
@@ -507,13 +510,11 @@ def fit_gaussian_profiles(
optim_loc = source_params[:, 1:3].clone().requires_grad_(True)
optim_scale = source_params[:, 3:5].clone().requires_grad_(True)
optim_tilt = source_params[:, 5].unsqueeze(1).clone().requires_grad_(True)
- optimizer = torch.optim.Adam(
- [
- {"params": optim_loc, "lr": 10 * learning_rate},
- {"params": optim_scale, "lr": 0.1 * learning_rate},
- {"params": optim_tilt, "lr": 0.1 * learning_rate},
- ]
- )
+ optimizer = torch.optim.Adam([
+ {"params": optim_loc, "lr": 10 * learning_rate},
+ {"params": optim_scale, "lr": 0.1 * learning_rate},
+ {"params": optim_tilt, "lr": 0.1 * learning_rate},
+ ])
z_col = source_params[:, 0].unsqueeze(1)
loc_min = torch.from_numpy(source_seeds[:, 1:3] - 1.5).float()
@@ -563,10 +564,7 @@ def fit_gaussian_profiles(
total_loss += torch.sum((x_step - x_mots[i]) ** 2)
# This branch completes a nonempty motion round: loss is Tensor.
losses.append(cast(torch.Tensor, total_loss).item())
- if (
- epoch // n_motions > 0
- and abs(losses[-1] - losses[-2]) < gd_tol
- ):
+ if epoch // n_motions > 0 and abs(losses[-1] - losses[-2]) < gd_tol:
break
return torch.cat(
@@ -575,24 +573,36 @@ def fit_gaussian_profiles(
)
-def variance_sortorder(
- phi_low_res: torch.Tensor, n_sources: int
-) -> np.ndarray:
- """Return the descending-explained-variance source ordering."""
+def variance_sortorder(phi_low_res: torch.Tensor, n_sources: int) -> np.ndarray:
+ """Return the descending-explained-variance source ordering.
+
+ Returns
+ -------
+ np.ndarray
+ Source indices sorted by descending variance of phi_low_res
+ (first n_sources columns).
+ """
phi = phi_low_res[:, :n_sources].numpy()
variance = np.nansum((phi - np.nanmean(phi, axis=0)) ** 2, axis=0)
return np.argsort(-variance)
def reorder_sources(
- order,
+ order: np.ndarray | torch.Tensor,
source_params: torch.Tensor,
source_seeds: np.ndarray,
a: torch.Tensor,
a_patches: torch.Tensor,
- x_support_mots: List[torch.Tensor],
+ x_support_mots: list[torch.Tensor],
phi_low_res: torch.Tensor,
-):
+) -> tuple[
+ torch.Tensor,
+ np.ndarray,
+ torch.Tensor,
+ torch.Tensor,
+ list[torch.Tensor],
+ torch.Tensor,
+]:
"""Apply a source ordering / selection to every per-source array.
Parameters
@@ -608,8 +618,8 @@ def reorder_sources(
Returns
-------
tuple
- The reindexed ``(source_params, source_seeds, a, a_patches,
- x_support_mots, phi_low_res)``.
+ The reindexed (source_params, source_seeds, a, a_patches,
+ x_support_mots, phi_low_res).
"""
source_params = source_params[order, :]
source_seeds = source_seeds[order, :]
@@ -629,7 +639,7 @@ def reorder_sources(
def compute_source_snr(
a: torch.Tensor,
- h_mots: List[torch.Tensor],
+ h_mots: list[torch.Tensor],
sel_pix_idxs: np.ndarray,
data_for_nmf: torch.Tensor,
phi_low_res: torch.Tensor,
@@ -639,7 +649,7 @@ def compute_source_snr(
) -> torch.Tensor:
"""Per-source low-resolution SNR (explained variance / residual variance).
- Reconstructs the residual from ``A`` and ``phi``, then for each source sums
+ Reconstructs the residual from A and phi, then for each source sums
the squared explained signal and squared residual over the superpixels the
source contributes to.
@@ -648,7 +658,7 @@ def compute_source_snr(
a : torch.Tensor of shape (n_pixels, N)
Spatial profiles.
h_mots : list of torch.Tensor
- Per-motion sparse ``H`` matrices.
+ Per-motion sparse H matrices.
sel_pix_idxs : ndarray of int
Flat selected-pixel indices.
data_for_nmf : torch.Tensor of shape (n_superpixels, n_frames)
@@ -663,15 +673,13 @@ def compute_source_snr(
Returns
-------
torch.Tensor of shape (N,)
- Per-source SNR (``varExp / varResidual``).
+ Per-source SNR (varExp / varResidual).
"""
residual_recon = torch.full_like(data_for_nmf, float("nan"))
for i in range(n_motions):
frames = _motion_frames(mot_inds_yx, i)
x = torch.sparse.mm(h_mots[i], a[sel_pix_idxs, :])
- residual_recon[:, frames] = (
- data_for_nmf[:, frames] - x @ phi_low_res[frames, :].T
- )
+ residual_recon[:, frames] = data_for_nmf[:, frames] - x @ phi_low_res[frames, :].T
var_exp = torch.zeros(n_sources, dtype=torch.float32)
var_residual = torch.zeros(n_sources, dtype=torch.float32)
@@ -697,7 +705,7 @@ def compute_source_snr(
def fit_sources(
source_seeds: np.ndarray,
residual: np.ndarray,
- h_mots: List[torch.Tensor],
+ h_mots: list[torch.Tensor],
unique_motion_to_keep_yx: np.ndarray,
mot_inds_yx: np.ndarray,
sel_pix_idxs: np.ndarray,
@@ -719,19 +727,19 @@ def fit_sources(
Parameters
----------
source_seeds : ndarray of shape (N, 3)
- Peak seeds ``[z, mu_y, mu_x]`` from :mod:`giant_python.numerics.peaks`.
+ Peak seeds [z, mu_y, mu_x] from :mod:`giant_python.numerics.peaks`.
residual : ndarray of shape (n_superpixels, n_frames)
Noise-normalized residual to reconstruct.
h_mots : list of torch.Tensor
- Per-motion sparse ``H`` matrices.
+ Per-motion sparse H matrices.
unique_motion_to_keep_yx : ndarray of shape (n_motions, 2)
Kept 2-D motion vectors (only its length is used).
mot_inds_yx : ndarray of shape (n_frames,)
- Per-frame motion-bin index (``-1`` for dropped frames).
+ Per-frame motion-bin index (-1 for dropped frames).
sel_pix_idxs : ndarray of int
- Flat selected-pixel indices into the ``n_pixels`` grid.
+ Flat selected-pixel indices into the n_pixels grid.
pixel_coords : ndarray of shape (n_sel, 3)
- Selected-pixel ``[z, row, col]`` coordinates.
+ Selected-pixel [z, row, col] coordinates.
n_pixels : int
Total number of image pixels.
d_xy : float
@@ -749,10 +757,10 @@ def fit_sources(
verbose : bool
Show a progress bar over the outer NMF/fit iterations when set.
temporal_kernel : ndarray, optional
- Temporal matched-filter kernel, normally from ``decay_kernel_1d``.
- Applied with the activity image's NaN-aware ``smooth_rho`` before
+ Temporal matched-filter kernel, normally from decay_kernel_1d.
+ Applied with the activity image's NaN-aware smooth_rho before
motion binning, without compensating for motion differences. Leaves
- ``residual`` unchanged. Frames with insufficient filter coverage in
+ residual unchanged. Frames with insufficient filter coverage in
any row are excluded from NMF and SNR; their temporal weights remain
NaN. Motion bins with no remaining frames are also excluded. NMF,
low-resolution temporal weights and SNR all use the filtered data.
@@ -760,16 +768,22 @@ def fit_sources(
unfiltered residual.
seed : int or None
Nonnegative seed for the random motion order. Each outer iteration
- uses a generator seeded from ``(seed, iteration)``, so a change in
+ uses a generator seeded from (seed, iteration), so a change in
the number of Adam epochs in one iteration does not shift the draws
- of later iterations. ``None`` uses the global torch RNG.
+ of later iterations. None uses the global torch RNG.
Returns
-------
dict
- ``A`` (n_pixels, N), ``phi_low_res`` (n_frames, N), ``source_params``
- (N, 6), ``source_seeds`` (N, 3), ``source_snr`` (N,), and
- ``n_sources``.
+ A (n_pixels, N), phi_low_res (n_frames, N), source_params
+ (N, 6), source_seeds (N, 3), source_snr (N,), and
+ n_sources.
+
+ Raises
+ ------
+ ValueError
+ If temporal_kernel is given and no usable frames remain after NaN-aware temporal
+ filtering.
"""
n_sources = source_seeds.shape[0]
n_motions = unique_motion_to_keep_yx.shape[0]
@@ -781,23 +795,17 @@ def fit_sources(
# even if the caller supplied finite values for them.
nmf_residual = nmf_residual.copy()
nmf_residual[:, mot_inds_yx < 0] = np.nan
- nmf_residual = smooth_rho(
- nmf_residual, temporal_kernel, verbose=verbose
- )
+ nmf_residual = smooth_rho(nmf_residual, temporal_kernel, verbose=verbose)
# The shared filter retains NaNs at low-coverage samples. The dense
# NMF solves cannot accept these, so omit affected frames rather
# than interpreting missing observations as zero residuals.
valid_frames = np.all(np.isfinite(nmf_residual), axis=0)
retained = (mot_inds_yx >= 0) & valid_frames
if not np.any(retained):
- raise ValueError(
- "No usable frames remain after NaN-aware temporal filtering"
- )
+ raise ValueError("No usable frames remain after NaN-aware temporal filtering")
kept_motions = np.unique(mot_inds_yx[retained])
filtered_motion_inds = np.full_like(mot_inds_yx, -1)
- filtered_motion_inds[retained] = np.searchsorted(
- kept_motions, mot_inds_yx[retained]
- )
+ filtered_motion_inds[retained] = np.searchsorted(kept_motions, mot_inds_yx[retained])
mot_inds_yx = filtered_motion_inds
h_mots = [h_mots[i] for i in kept_motions]
n_motions = len(h_mots)
@@ -805,18 +813,12 @@ def fit_sources(
num_epochs = n_motions * 5
source_params = init_source_params(source_seeds)
- a_patches = build_a_patches(
- source_seeds, pixel_coords_tensor, sel_pix_idxs, n_pixels, d_xy
- )
- x_support_mots = build_x_support_mots(
- h_mots, a_patches, sel_pix_idxs, n_motions
- )
+ a_patches = build_a_patches(source_seeds, pixel_coords_tensor, sel_pix_idxs, n_pixels, d_xy)
+ x_support_mots = build_x_support_mots(h_mots, a_patches, sel_pix_idxs, n_motions)
a = project_spatial_profiles(
source_params, pixel_coords_tensor, sel_pix_idxs, n_pixels, a_patches
)
- phi_low_res = torch.full(
- (n_frames, n_sources), float("nan"), dtype=torch.float32
- )
+ phi_low_res = torch.full((n_frames, n_sources), float("nan"), dtype=torch.float32)
for outer_loop_iter in progress(
range(outer_loop_iters),
@@ -825,9 +827,7 @@ def fit_sources(
):
generator = None
if seed is not None:
- iter_seed = np.random.SeedSequence(
- [seed, outer_loop_iter]
- ).generate_state(1)[0]
+ iter_seed = np.random.SeedSequence([seed, outer_loop_iter]).generate_state(1)[0]
generator = torch.Generator().manual_seed(int(iter_seed))
x_mots = multiplicative_nmf(
a,
diff --git a/src/giant_python/extraction/band/motion_binning.py b/src/giant_python/extraction/band/motion_binning.py
index 91ff94db..cf461f04 100644
--- a/src/giant_python/extraction/band/motion_binning.py
+++ b/src/giant_python/extraction/band/motion_binning.py
@@ -2,14 +2,12 @@
from __future__ import annotations
-from typing import Tuple
-
import numpy as np
def bin_motion(
motion_r: np.ndarray, motion_c: np.ndarray, motion_z: np.ndarray
-) -> Tuple[np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray]:
"""Group frames into unique rounded (row, col, z) motion bins.
Parameters
@@ -20,9 +18,9 @@ def bin_motion(
Returns
-------
unique_motion : ndarray of shape (n_bins, 3)
- The unique rounded ``[row, col, z]`` motion vectors.
+ The unique rounded [row, col, z] motion vectors.
mot_inds : ndarray of shape (n_frames,)
- Index of each frame's motion bin into ``unique_motion``.
+ Index of each frame's motion bin into unique_motion.
"""
unique_motion, mot_inds = np.unique(
np.round(np.stack((motion_r, motion_c, motion_z), axis=1)),
@@ -40,11 +38,11 @@ def select_motion_bins(
motion_z: np.ndarray,
z_tol: float = 1.5,
min_frames: int = 100,
-) -> Tuple[np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray]:
"""Keep motion bins near the median z with enough frames.
- A bin is kept when its z is within ``z_tol`` of the median z (over all
- frames) and it contains more than ``min_frames`` frames. After filtering,
+ A bin is kept when its z is within z_tol of the median z (over all
+ frames) and it contains more than min_frames frames. After filtering,
the remaining frames are treated as having no z motion.
Parameters
@@ -63,15 +61,13 @@ def select_motion_bins(
Returns
-------
mot_inds_to_keep : ndarray
- Indices of the kept bins into ``unique_motion``.
+ Indices of the kept bins into unique_motion.
frames_to_keep : ndarray of bool
Per-frame mask of frames belonging to a kept bin.
"""
median_z = np.median(motion_z)
bin_counts = np.bincount(mot_inds, minlength=unique_motion.shape[0])
- keep_mask = (np.abs(unique_motion[:, 2] - median_z) <= z_tol) & (
- bin_counts > min_frames
- )
+ keep_mask = (np.abs(unique_motion[:, 2] - median_z) <= z_tol) & (bin_counts > min_frames)
mot_inds_to_keep = np.nonzero(keep_mask)[0]
frames_to_keep = np.isin(mot_inds, mot_inds_to_keep)
return mot_inds_to_keep, frames_to_keep
@@ -81,7 +77,7 @@ def bin_motion_yx(
motion_r: np.ndarray,
motion_c: np.ndarray,
frames_to_keep: np.ndarray,
-) -> Tuple[np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray]:
"""Bin kept frames into unique rounded (row, col) motion bins.
Parameters
@@ -89,22 +85,18 @@ def bin_motion_yx(
motion_r, motion_c : ndarray
Per-frame downsampled row/column motion.
frames_to_keep : ndarray of bool
- Frames to bin; dropped frames get index ``-1``.
+ Frames to bin; dropped frames get index -1.
Returns
-------
unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2)
- Unique rounded ``[row, col]`` motion vectors over the kept frames.
+ Unique rounded [row, col] motion vectors over the kept frames.
mot_inds_yx : ndarray of shape (n_frames,), int32
- Per-frame bin index into ``unique_motion_to_keep_yx``; ``-1`` for
+ Per-frame bin index into unique_motion_to_keep_yx; -1 for
frames not kept.
"""
mot_inds_yx = -1 * np.ones((frames_to_keep.shape[0],), dtype=np.int32)
- stacked = np.round(
- np.stack((motion_r, motion_c), axis=1)[frames_to_keep, :]
- )
- unique_motion_to_keep_yx, inv = np.unique(
- stacked, axis=0, return_inverse=True
- )
+ stacked = np.round(np.stack((motion_r, motion_c), axis=1)[frames_to_keep, :])
+ unique_motion_to_keep_yx, inv = np.unique(stacked, axis=0, return_inverse=True)
mot_inds_yx[frames_to_keep] = np.reshape(inv, -1)
return unique_motion_to_keep_yx, mot_inds_yx
diff --git a/src/giant_python/extraction/band/operators.py b/src/giant_python/extraction/band/operators.py
index 492affd5..387821e8 100644
--- a/src/giant_python/extraction/band/operators.py
+++ b/src/giant_python/extraction/band/operators.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Any, List, Tuple, cast
+from typing import Any, cast
import numpy as np
import torch
@@ -13,10 +13,10 @@
def expand_psf(
psf2d: np.ndarray, ex_fac: int = 2
-) -> Tuple[torch.Tensor, Tuple[int, int], torch.Tensor, Tuple[int, int]]:
+) -> tuple[torch.Tensor, tuple[int, int], torch.Tensor, tuple[int, int]]:
"""Normalize a PSF and build a center-aligned higher-resolution copy.
- The expanded PSF is an ``ex_fac``x up-sampled cubic-spline interpolation
+ The expanded PSF is an ex_facx up-sampled cubic-spline interpolation
that keeps the center aligned. Localization constructs its center/surround
filter separately with :func:`gaussian_kernel_2d`.
@@ -32,11 +32,11 @@ def expand_psf(
psf_tensor : torch.Tensor
Sum-normalized PSF.
psf_center : tuple of int
- ``(row, col)`` center of ``psf_tensor``.
+ (row, col) center of psf_tensor.
psf_tensor_expanded : torch.Tensor
Sum-normalized expanded PSF.
psf_center_expanded : tuple of int
- ``(row, col)`` center of ``psf_tensor_expanded``.
+ (row, col) center of psf_tensor_expanded.
"""
psf_arr = np.asarray(psf2d, dtype=np.float32)
psf_tensor = torch.from_numpy(psf_arr).float()
@@ -46,21 +46,11 @@ def expand_psf(
expanded_center_y = (psf_shape[0] * ex_fac - 1) / 2
expanded_center_x = (psf_shape[1] * ex_fac - 1) / 2
- orig_y = torch.linspace(
- -expanded_center_y, expanded_center_y, psf_shape[0]
- )
- orig_x = torch.linspace(
- -expanded_center_x, expanded_center_x, psf_shape[1]
- )
- expanded_y = torch.linspace(
- -expanded_center_y, expanded_center_y, psf_shape[0] * ex_fac
- )
- expanded_x = torch.linspace(
- -expanded_center_x, expanded_center_x, psf_shape[1] * ex_fac
- )
- interp_spline = RectBivariateSpline(
- orig_y.numpy(), orig_x.numpy(), psf_tensor.numpy()
- )
+ orig_y = torch.linspace(-expanded_center_y, expanded_center_y, psf_shape[0])
+ orig_x = torch.linspace(-expanded_center_x, expanded_center_x, psf_shape[1])
+ expanded_y = torch.linspace(-expanded_center_y, expanded_center_y, psf_shape[0] * ex_fac)
+ expanded_x = torch.linspace(-expanded_center_x, expanded_center_x, psf_shape[1] * ex_fac)
+ interp_spline = RectBivariateSpline(orig_y.numpy(), orig_x.numpy(), psf_tensor.numpy())
psf_tensor_expanded = torch.from_numpy(
interp_spline(expanded_y.numpy(), expanded_x.numpy())
).float()
@@ -73,13 +63,11 @@ def expand_psf(
return psf_tensor, psf_center, psf_tensor_expanded, psf_center_expanded
-def shrink_psf(
- psf2d: np.ndarray, scale_y: float = 1.0, scale_x: float = 0.75
-) -> np.ndarray:
+def shrink_psf(psf2d: np.ndarray, scale_y: float = 1.0, scale_x: float = 0.75) -> np.ndarray:
"""Spatially shrink a PSF on the same grid (TEMPORARY).
Resamples the PSF on a grid whose coordinates are divided by the per-axis
- scale so a ``scale < 1`` narrows the PSF's spatial footprint along that
+ scale so a scale < 1 narrows the PSF's spatial footprint along that
axis while keeping the same array shape and center; the result is
re-normalized to sum to 1. Used only for the temporary activity-image
experiment.
@@ -89,15 +77,15 @@ def shrink_psf(
psf2d : ndarray
The (cropped) PSF for this DMD.
scale_y : float
- Spatial shrink factor along the row (y) axis (``< 1`` shrinks,
- ``1`` is a no-op).
+ Spatial shrink factor along the row (y) axis (< 1 shrinks,
+ 1 is a no-op).
scale_x : float
- Spatial shrink factor along the column (x) axis (``< 1`` shrinks,
- ``1`` is a no-op).
+ Spatial shrink factor along the column (x) axis (< 1 shrinks,
+ 1 is a no-op).
Returns
-------
- ndarray of shape ``psf2d.shape``, float32
+ ndarray of shape psf2d.shape, float32
The shrunk, sum-normalized PSF.
"""
psf_arr = np.asarray(psf2d, dtype=np.float32)
@@ -115,13 +103,11 @@ def shrink_psf(
return shrunk
-def gaussian_kernel_2d(
- sigma: float, truncate: float = 4.0
-) -> Tuple[torch.Tensor, Tuple[int, int]]:
+def gaussian_kernel_2d(sigma: float, truncate: float = 4.0) -> tuple[torch.Tensor, tuple[int, int]]:
"""Build a sum-normalized isotropic 2-D Gaussian kernel (TEMPORARY).
Used by the temporary difference-of-Gaussians activity-image experiment,
- which replaces the PSF-derived ``D``/``D_expanded`` convolution matrices
+ which replaces the PSF-derived D/D_expanded convolution matrices
with an isotropic center/surround pair. The subtraction itself still
happens in :func:`compute_rho`, after per-column normalization.
@@ -136,9 +122,9 @@ def gaussian_kernel_2d(
Returns
-------
kernel : torch.Tensor
- Sum-normalized ``(2 * radius + 1, 2 * radius + 1)`` kernel.
+ Sum-normalized (2 * radius + 1, 2 * radius + 1) kernel.
center : tuple of int
- ``(row, col)`` center index of ``kernel``.
+ (row, col) center index of kernel.
"""
radius = int(np.ceil(truncate * sigma))
coords = np.arange(-radius, radius + 1, dtype=np.float64)
@@ -151,27 +137,27 @@ def gaussian_kernel_2d(
def build_convolution_matrix(
sel_pixels_2d: np.ndarray,
psf_tensor: torch.Tensor,
- psf_center: Tuple[int, int],
+ psf_center: tuple[int, int],
) -> torch.Tensor:
"""Build a dense PSF-convolution matrix for one plane's selected pixels.
- Entry ``(t, s)`` is the PSF weight for the offset from source pixel ``s``
- to target pixel ``t`` (zero where the offset falls outside the PSF). Used
- with both the base and expanded PSFs to form ``D``/``D_expanded``.
+ Entry (t, s) is the PSF weight for the offset from source pixel s
+ to target pixel t (zero where the offset falls outside the PSF). Used
+ with both the base and expanded PSFs to form D/D_expanded.
Parameters
----------
sel_pixels_2d : ndarray of shape (n_plane, 2)
- In-plane ``[row, col]`` coordinates.
+ In-plane [row, col] coordinates.
psf_tensor : torch.Tensor
Sum-normalized PSF (base or expanded).
psf_center : tuple of int
- ``(row, col)`` center of ``psf_tensor``.
+ (row, col) center of psf_tensor.
Returns
-------
torch.Tensor
- Dense ``(n_plane, n_plane)`` convolution matrix.
+ Dense (n_plane, n_plane) convolution matrix.
"""
n = sel_pixels_2d.shape[0]
if n == 0:
@@ -185,10 +171,7 @@ def build_convolution_matrix(
psf_np = psf_tensor.numpy()
psf_shape = psf_np.shape
valid_mask = (
- (rel_rows >= 0)
- & (rel_rows < psf_shape[0])
- & (rel_cols >= 0)
- & (rel_cols < psf_shape[1])
+ (rel_rows >= 0) & (rel_rows < psf_shape[0]) & (rel_cols >= 0) & (rel_cols < psf_shape[1])
)
out = np.zeros((n, n), dtype=np.float32)
out[valid_mask] = psf_np[rel_rows[valid_mask], rel_cols[valid_mask]]
@@ -202,41 +185,39 @@ def build_motion_h_matrices(
sel_pix_idxs: np.ndarray,
num_super_pixels: int,
dmd_pixels_per_row: int,
-) -> List[torch.Tensor]:
- """Build one sparse superpixel<-selected-pixel ``H`` per motion bin.
+) -> list[torch.Tensor]:
+ """Build one sparse superpixel<-selected-pixel H per motion bin.
- Each motion bin shifts the base ``H`` columns (image pixels) by its 2-D
+ Each motion bin shifts the base H columns (image pixels) by its 2-D
motion, then remaps them into selected-pixel column space.
Parameters
----------
sparse_h_inds : ndarray of shape (2, nnz)
- Base ``H`` COO row/column indices (from ``geometry.build_sparse_h``).
+ Base H COO row/column indices (from geometry.build_sparse_h).
sparse_h_vals : ndarray of shape (nnz,)
- Base ``H`` values.
+ Base H values.
unique_motion_to_keep_yx : ndarray of shape (n_yx_bins, 2)
Kept 2-D motion vectors.
sel_pix_idxs : ndarray of int
Sorted flat selected-pixel indices.
num_super_pixels : int
- Number of superpixels (``H`` row count).
+ Number of superpixels (H row count).
dmd_pixels_per_row : int
Grid geometry (column-shift stride).
Returns
-------
list of torch.Tensor
- One sparse COO ``(num_super_pixels, n_sel)`` tensor per motion bin.
+ One sparse COO (num_super_pixels, n_sel) tensor per motion bin.
"""
n_mot = len(unique_motion_to_keep_yx)
- h_mots: List[torch.Tensor | None] = [None] * n_mot
+ h_mots: list[torch.Tensor | None] = [None] * n_mot
base_sparse_rows = sparse_h_inds[0]
base_sparse_cols = sparse_h_inds[1]
motion_shifts = unique_motion_to_keep_yx[:, 0].astype(
np.int64, copy=False
- ) * dmd_pixels_per_row + unique_motion_to_keep_yx[:, 1].astype(
- np.int64, copy=False
- )
+ ) * dmd_pixels_per_row + unique_motion_to_keep_yx[:, 1].astype(np.int64, copy=False)
shifted_inds = np.empty((2, base_sparse_cols.shape[0]), dtype=np.int64)
shifted_inds[0] = base_sparse_rows
for i, pix_shift in enumerate(motion_shifts):
@@ -250,7 +231,7 @@ def build_motion_h_matrices(
dtype=torch.float32,
)
# Every slot is populated by the corresponding motion shift above.
- return cast(List[torch.Tensor], h_mots)
+ return cast(list[torch.Tensor], h_mots)
def build_sparse_h(
@@ -258,17 +239,17 @@ def build_sparse_h(
psf2d: np.ndarray,
dmd_pixels_per_column: int,
dmd_pixels_per_row: int,
-) -> Tuple[np.ndarray, np.ndarray]:
- """Build the sparse ``H`` PSF-convolution matrix (COO index/value arrays).
+) -> tuple[np.ndarray, np.ndarray]:
+ """Build the sparse H PSF-convolution matrix (COO index/value arrays).
- ``H`` projects image space (flattened ``z*(rows*cols) + row*cols + col``)
+ H projects image space (flattened z*(rows*cols) + row*cols + col)
into superpixel space by convolving each superpixel's reference pixel with
the PSF.
Parameters
----------
subsample_matrix_inds : ndarray of shape (n_superpixels, 2)
- ``[ref_pixel (0-based), superpixel_id (1-based)]`` per superpixel.
+ [ref_pixel (0-based), superpixel_id (1-based)] per superpixel.
psf2d : ndarray
The (thresholded/cropped) PSF for this DMD.
dmd_pixels_per_column, dmd_pixels_per_row : int
@@ -292,20 +273,12 @@ def build_sparse_h(
row_offsets = np.arange(psf_h, dtype=np.int32) - (psf_h // 2)
col_offsets = np.arange(psf_w, dtype=np.int32) - (psf_w // 2)
- row_offsets_flat = np.broadcast_to(
- row_offsets.reshape(-1, 1), (psf_h, psf_w)
- ).ravel()
- col_offsets_flat = np.broadcast_to(
- col_offsets.reshape(1, -1), (psf_h, psf_w)
- ).ravel()
+ row_offsets_flat = np.broadcast_to(row_offsets.reshape(-1, 1), (psf_h, psf_w)).ravel()
+ col_offsets_flat = np.broadcast_to(col_offsets.reshape(1, -1), (psf_h, psf_w)).ravel()
psf_vals_flat = psf2d.ravel()
- sparse_h_inds = np.zeros(
- (2, num_super_pixels * filter_size), dtype=np.int32
- )
- sparse_h_vals = np.zeros(
- (num_super_pixels * filter_size,), dtype=np.float32
- )
+ sparse_h_inds = np.zeros((2, num_super_pixels * filter_size), dtype=np.int32)
+ sparse_h_vals = np.zeros((num_super_pixels * filter_size,), dtype=np.float32)
sparse_h_inds[0] = np.repeat(subsample_matrix_inds[:, 1] - 1, filter_size)
for sp in range(num_super_pixels):
start = sp * filter_size
diff --git a/src/giant_python/extraction/band/result_assembly.py b/src/giant_python/extraction/band/result_assembly.py
index 41fb7ac2..c6ff82c2 100644
--- a/src/giant_python/extraction/band/result_assembly.py
+++ b/src/giant_python/extraction/band/result_assembly.py
@@ -6,7 +6,6 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Optional
import numpy as np
from torch import Tensor
@@ -26,7 +25,7 @@
class PathResult:
"""One path's numerical outputs, geometry, and assembly window lengths.
- ``a`` is (pixels, sources), ``source_params`` is (sources, 6), and
+ a is (pixels, sources), source_params is (sources, 6), and
trace_results contains named trial records.
Reference offsets use the INTERNAL band convention;
online shifts retain their saved displacement convention.
@@ -48,22 +47,37 @@ class PathResult:
denoise_window: int
baseline_window: int
draw_user_rois: bool = False
- soma_masks: Optional[list] = None
- soma_labels: Optional[list] = None
+ soma_masks: list | None = None
+ soma_labels: list | None = None
yx_shape: tuple = (0, 0)
def _with_nan_channel(arr: np.ndarray, num_channels: int) -> np.ndarray:
- """Map frames/sources to sources/channels/frames, filling channel 0."""
- out = np.full(
- (arr.shape[1], num_channels, arr.shape[0]), np.nan, dtype=arr.dtype
- )
+ """Map frames/sources to sources/channels/frames, filling channel 0.
+
+ Returns
+ -------
+ np.ndarray
+ Array of shape (sources, num_channels, frames), NaN except channel 0, which holds
+ arr transposed.
+ """
+ out = np.full((arr.shape[1], num_channels, arr.shape[0]), np.nan, dtype=arr.dtype)
out[:, 0, :] = arr.T
return out
-def _dmd_user_rois(user_rois: Optional[dict], key: str) -> tuple:
- """Select one DMD's resolved ROI masks, labels and superpixels."""
+def _dmd_user_rois(user_rois: dict | None, key: str) -> tuple:
+ """Select one DMD's resolved ROI masks, labels and superpixels.
+
+ Returns
+ -------
+ masks : list or None
+ The DMD's ROI masks; None when there is no resolved selection or no entry for key.
+ labels : list or None
+ The DMD's ROI labels; None under the same conditions.
+ superpixels : list
+ The DMD's per-ROI superpixel indices; empty when there is none.
+ """
if user_rois is None:
return None, None, []
return (
@@ -79,20 +93,21 @@ def assemble_path_summary(pr: PathResult, path_index: int = 0) -> PathSummary:
Offline reference offsets are negated once into MATLAB displacement.
Online shifts, frame lines, input arrays, and interpolation are unchanged.
Populated model entries share array views; empty templates retain layout.
+
+ Returns
+ -------
+ PathSummary
+ The path's concatenated sources, user ROIs, visualizations, frame information,
+ global fluorescence and z depths.
"""
results = pr.trace_results
d_f = np.concatenate([r.d_f for r in results], axis=0)
# F = dF_ls + intermediate F0 + backprojected fit residual.
f0_ls = np.concatenate(
- [
- r.f0_ls if r.f_residual is None else r.f0_ls + r.f_residual
- for r in results
- ],
+ [r.f0_ls if r.f_residual is None else r.f0_ls + r.f_residual for r in results],
axis=0,
)
- f_full, f0, d_f, _ = assemble_dff(
- d_f, f0_ls, pr.denoise_window, pr.baseline_window
- )
+ f_full, f0, d_f, _ = assemble_dff(d_f, f0_ls, pr.denoise_window, pr.baseline_window)
profiles = pr.a.numpy().T.reshape(
-1, pr.num_fast_zs, pr.dmd_pixels_per_column, pr.dmd_pixels_per_row
)
@@ -104,20 +119,13 @@ def assemble_path_summary(pr: PathResult, path_index: int = 0) -> PathSummary:
# Legacy manually constructed records have no transient outputs.
denoised = np.concatenate(
[
- (
- r.d_f_denoised
- if r.d_f_denoised is not None
- else np.full_like(r.d_f, np.nan)
- )
+ (r.d_f_denoised if r.d_f_denoised is not None else np.full_like(r.d_f, np.nan))
for r in results
],
axis=0,
)
events = np.concatenate(
- [
- r.events if r.events is not None else np.full_like(r.d_f, np.nan)
- for r in results
- ],
+ [r.events if r.events is not None else np.full_like(r.d_f, np.nan) for r in results],
axis=0,
)
denoised_channels = _with_nan_channel(denoised, pr.num_channels)
@@ -137,31 +145,21 @@ def assemble_path_summary(pr: PathResult, path_index: int = 0) -> PathSummary:
for j in range(profiles.shape[0])
]
frame_info = FrameInfo(
- trial_num_frames=np.concatenate(
- [[len(r.frame_line_idxs)] for r in results]
- ).reshape(-1, 1),
+ trial_num_frames=np.concatenate([[len(r.frame_line_idxs)] for r in results]).reshape(-1, 1),
discard_frames=np.any(np.isnan(f_full), axis=1).reshape(-1, 1),
- frame_line_idxs=np.concatenate(
- [r.frame_line_idxs for r in results], axis=0
- ).reshape(-1, 1),
- offlineXshifts=-np.concatenate(
- [r.reference_offsets[1] for r in results], axis=0
- ).reshape(-1, 1),
- offlineYshifts=-np.concatenate(
- [r.reference_offsets[0] for r in results], axis=0
- ).reshape(-1, 1),
- offlineZshifts=-np.concatenate(
- [r.reference_offsets[2] for r in results], axis=0
- ).reshape(-1, 1),
- onlineXshifts=np.concatenate(
- [r.online_shifts[1] for r in results], axis=0
- ).reshape(-1, 1),
- onlineYshifts=np.concatenate(
- [r.online_shifts[0] for r in results], axis=0
- ).reshape(-1, 1),
- onlineZshifts=np.concatenate(
- [r.online_shifts[2] for r in results], axis=0
- ).reshape(-1, 1),
+ frame_line_idxs=np.concatenate([r.frame_line_idxs for r in results], axis=0).reshape(-1, 1),
+ offlineXshifts=-np.concatenate([r.reference_offsets[1] for r in results], axis=0).reshape(
+ -1, 1
+ ),
+ offlineYshifts=-np.concatenate([r.reference_offsets[0] for r in results], axis=0).reshape(
+ -1, 1
+ ),
+ offlineZshifts=-np.concatenate([r.reference_offsets[2] for r in results], axis=0).reshape(
+ -1, 1
+ ),
+ onlineXshifts=np.concatenate([r.online_shifts[1] for r in results], axis=0).reshape(-1, 1),
+ onlineYshifts=np.concatenate([r.online_shifts[0] for r in results], axis=0).reshape(-1, 1),
+ onlineZshifts=np.concatenate([r.online_shifts[2] for r in results], axis=0).reshape(-1, 1),
)
annotation_enabled = False
user_rois = []
@@ -173,9 +171,7 @@ def assemble_path_summary(pr: PathResult, path_index: int = 0) -> PathSummary:
if len(pr.soma_masks) > 0
else np.zeros((0, pr.num_fast_zs, *pr.yx_shape), dtype=bool)
)
- fluorescence = np.concatenate(
- [r.user_roi_f for r in results], axis=0
- ).transpose(1, 2, 0)
+ fluorescence = np.concatenate([r.user_roi_f for r in results], axis=0).transpose(1, 2, 0)
labels = np.asarray(pr.soma_labels, dtype=object).reshape(-1)
user_rois = [
UserRoi(
diff --git a/src/giant_python/extraction/band/rois.py b/src/giant_python/extraction/band/rois.py
index 849e3fea..249b047d 100644
--- a/src/giant_python/extraction/band/rois.py
+++ b/src/giant_python/extraction/band/rois.py
@@ -9,11 +9,14 @@ def user_roi_superpixel_lists_from_masks(
sp_rows: np.ndarray,
sp_cols: np.ndarray,
) -> list:
- """Return indices of superpixels in each ROI, preserving overlap/order."""
- return [
- np.flatnonzero(np.asarray(mask)[sp_fastz, sp_rows, sp_cols])
- for mask in roi_masks
- ]
+ """Return indices of superpixels in each ROI, preserving overlap/order.
+
+ Returns
+ -------
+ list
+ One array per ROI mask, holding the indices of the superpixels inside that mask.
+ """
+ return [np.flatnonzero(np.asarray(mask)[sp_fastz, sp_rows, sp_cols]) for mask in roi_masks]
def compute_user_roi_geometry(
@@ -26,6 +29,14 @@ def compute_user_roi_geometry(
Reference is (channels,z,Y,X); fast-Z lookup is 1-based. Reference pixel
decomposition retains the original column-major convention and indexes.
+
+ Returns
+ -------
+ dict
+ ref, num_ref_z, yx_shape, best_ch (channel with the highest mean),
+ z_map (zero-based reference z per fast-Z plane), num_fast_z, the superpixel
+ coordinates sp_fastz, sp_rows and sp_cols, and sp_mask (boolean
+ (fast z, Y, X) mask of the valid superpixels).
"""
avg_motion_r, avg_motion_c, avg_motion_z = motion_median
num_ref_z = ref.shape[1]
@@ -75,6 +86,18 @@ def _read_roi_records(grp: dict, expected: tuple) -> tuple:
Takes a plain decoded mapping, NOT an HDF5 handle. Missing masks become
empty masks, missing records are skipped, and bad shapes reject the path.
+
+ Returns
+ -------
+ roi_masks : list
+ Boolean ROI masks, in record order.
+ labels : list
+ The ROI labels.
+ recs : list
+ Per-ROI records with type, label and, when present, position.
+ bad_shape : bool
+ True when a mask does not match expected; the lists then hold the records read
+ before it.
"""
n_rois = int(np.asarray(grp.get("n_rois", 0)).reshape(-1)[0])
roi_masks, labels, recs = [], [], []
@@ -82,7 +105,7 @@ def _read_roi_records(grp: dict, expected: tuple) -> tuple:
record = grp.get(f"roi_{i:03d}")
if record is None:
continue
- label = str(record.get("label", f"ROI{i+1}"))
+ label = str(record.get("label", f"ROI{i + 1}"))
roi_type = str(record.get("type", "polygon"))
if "mask" in record:
mask = np.asarray(record["mask"])
@@ -99,10 +122,15 @@ def _read_roi_records(grp: dict, expected: tuple) -> tuple:
return roi_masks, labels, recs, False
-def _load_one_path(
- raw: dict, dmd_ix: int, user_roi_geo: dict, out: dict
-) -> bool:
- """Resolve one decoded path against current geometry, without disk IO."""
+def _load_one_path(raw: dict, dmd_ix: int, user_roi_geo: dict, out: dict) -> bool:
+ """Resolve one decoded path against current geometry, without disk IO.
+
+ Returns
+ -------
+ bool
+ True when the path supplied at least one ROI record; False when it is missing or has
+ a mask shape mismatch (a neutral selection is recorded in out), or has no records.
+ """
key = f"DMD{dmd_ix + 1}"
path_key = f"Path{dmd_ix + 1}"
geo = user_roi_geo[key]
@@ -126,17 +154,27 @@ def _load_one_path(
out["user_roi_labels"][key] = labels
out["roi_records"][key] = records
if len(records) > 0:
- print(
- f"Loaded {len(records)} ROI(s) for {path_key} from annotations.h5"
- )
+ print(f"Loaded {len(records)} ROI(s) for {path_key} from annotations.h5")
return True
return False
-def resolve_annotation_records(
- raw: dict, n_dmds: int, user_roi_geo: dict
-) -> tuple:
- """Return selection status, masks, superpixels, labels, and ROI records."""
+def resolve_annotation_records(raw: dict, n_dmds: int, user_roi_geo: dict) -> tuple:
+ """Return selection status, masks, superpixels, labels, and ROI records.
+
+ Returns
+ -------
+ selected : bool
+ True when any path supplied ROI records.
+ user_roi_masks : dict
+ Per-DMD ROI masks (empty when not selected).
+ user_roi_superpixels : dict
+ Per-DMD superpixel indices of each ROI (empty when not selected).
+ user_roi_labels : dict
+ Per-DMD ROI labels (empty when not selected).
+ roi_records : dict
+ Per-DMD ROI records (empty when not selected).
+ """
out = {
"user_roi_masks": {},
"user_roi_superpixels": {},
diff --git a/src/giant_python/extraction/band/summary_images.py b/src/giant_python/extraction/band/summary_images.py
index 610b45fe..14da2bdb 100644
--- a/src/giant_python/extraction/band/summary_images.py
+++ b/src/giant_python/extraction/band/summary_images.py
@@ -1,32 +1,34 @@
"""Summary/visualization images: the mean image and the activity image.
-Ported from ``extractSLAP2IntegrationSources.py``. Groups the two per-DMD
-summary images written to ``experiment_summary.h5`` / consumed downstream:
+Ported from extractSLAP2IntegrationSources.py. Groups the two per-DMD
+summary images written to experiment_summary.h5 / consumed downstream:
* :func:`compute_mean_image` (ref 1913-1918) scatters the kept-frame mean
- trace onto the reference-pixel grid, producing the ``mean_im`` visualization.
+ trace onto the reference-pixel grid, producing the mean_im visualization.
* :func:`accumulate_activity_image` / :func:`finalize_activity_image` (ref
- 2358-2504) turn the smoothed ``rho`` from
- :mod:`giant_python.extraction.band.activity` into the ``act_im`` activity
+ 2358-2504) turn the smoothed rho from
+ :mod:`giant_python.extraction.band.activity` into the act_im activity
image that Phase-5 peak detection localizes sources in.
-The activity image is built by sweeping ``rho`` in temporal batches, finding
+The activity image is built by sweeping rho in temporal batches, finding
spatio-temporal local maxima (a voxel greater than its 6 spatial neighbors in
the same frame and its temporal neighbors), and accumulating their squared
value; it is then masked where data was never valid, has a local NaN-median
subtracted, and is zeroed at vertical support edges.
-The reference's optional ``profile_activity_map`` timing instrumentation is
+The reference's optional profile_activity_map timing instrumentation is
intentionally dropped (it only prints timings and does not affect output).
"""
from __future__ import annotations
+import itertools
+from collections.abc import Iterator
from typing import cast
import numpy as np
-import scipy.ndimage as ndimage
from numpy.typing import NDArray
+from scipy import ndimage
from ...numerics.morphology import fast_dilation
from ...progress import progress
@@ -49,8 +51,8 @@ def compute_mean_image(
"""Scatter the kept-frame mean trace onto the reference pixel grid.
The mean over kept frames is placed at each superpixel's reference pixel,
- shifted by the most common motion bin, producing the ``mean_im``
- visualization ``(channels, z, rows, cols)``.
+ shifted by the most common motion bin, producing the mean_im
+ visualization (channels, z, rows, cols).
Parameters
----------
@@ -70,14 +72,14 @@ def compute_mean_image(
num_channels : int
Number of acquisition channels (>= 2 fills the second channel).
low_res_data2_norm : ndarray, optional
- Count-normalized channel-2 traces (used when ``num_channels >= 2``).
+ Count-normalized channel-2 traces (used when num_channels >= 2).
Returns
-------
ndarray of float32
- ``mean_im`` with shape
- ``(num_channels, num_fast_zs, dmd_pixels_per_column,
- dmd_pixels_per_row)``.
+ mean_im with shape
+ (num_channels, num_fast_zs, dmd_pixels_per_column,
+ dmd_pixels_per_row).
"""
mean_im = np.full(
(num_channels, num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row),
@@ -87,9 +89,7 @@ def compute_mean_image(
most_common_mot = np.argmax(np.bincount(mot_inds))
sel_r = ref_r + int(unique_motion[most_common_mot, 0])
sel_c = ref_c + int(unique_motion[most_common_mot, 1])
- mean_im[0, ref_d, sel_r, sel_c] = np.nanmean(
- low_res_data_norm[:, frames_to_keep], axis=1
- )
+ mean_im[0, ref_d, sel_r, sel_c] = np.nanmean(low_res_data_norm[:, frames_to_keep], axis=1)
if num_channels >= 2:
# The two-channel input contract requires the second-channel array.
mean_im[1, ref_d, sel_r, sel_c] = np.nanmean(
@@ -107,13 +107,13 @@ def accumulate_activity_image(
batch_size: int = 1000,
verbose: bool = False,
) -> np.ndarray:
- """Accumulate squared spatio-temporal local maxima of ``rho``.
+ """Accumulate squared spatio-temporal local maxima of rho.
- ``rho`` (selected pixels x frames) is scattered into a padded spatial grid
+ rho (selected pixels x frames) is scattered into a padded spatial grid
one temporal batch at a time. Within each batch, a voxel is a local maximum
if it strictly exceeds its two temporal neighbors and its four in-plane
neighbors and is not adjacent (after a 3x3 dilation) to any NaN voxel. The
- squared values of local maxima are summed into ``act_im``.
+ squared values of local maxima are summed into act_im.
Parameters
----------
@@ -124,15 +124,15 @@ def accumulate_activity_image(
num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row : int
Spatial grid geometry.
batch_size : int
- Number of frames processed per batch (capped at ``n_frames``).
+ Number of frames processed per batch (capped at n_frames).
verbose : bool
Show a per-batch progress bar when set.
Returns
-------
ndarray of float32
- ``act_im`` with shape
- ``(num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row)``.
+ act_im with shape
+ (num_fast_zs, dmd_pixels_per_column, dmd_pixels_per_row).
"""
n_frames = rho.shape[1]
batch_size = min(batch_size, n_frames)
@@ -169,9 +169,7 @@ def accumulate_activity_image(
col_indices_roi = (col_indices - col_start).astype(np.intp, copy=False)
prealloc_size = int(min(batch_size + 2 * temporal_pad, n_frames))
- batch_rho = np.empty(
- (prealloc_size, num_fast_zs, roi_h, roi_w), dtype=np.float32
- )
+ batch_rho = np.empty((prealloc_size, num_fast_zs, roi_h, roi_w), dtype=np.float32)
nan_mask = np.empty_like(batch_rho, dtype=bool)
interior_shape = (
max(prealloc_size - 2, 0),
@@ -184,9 +182,7 @@ def accumulate_activity_image(
batch_rho_pow2_core = np.empty(interior_shape, dtype=np.float32)
time_indices_pre = np.arange(prealloc_size)[:, None]
- for batch_idx in progress(
- range(num_batches), desc="Creating activity map", verbose=verbose
- ):
+ for batch_idx in progress(range(num_batches), desc="Creating activity map", verbose=verbose):
batch_start = batch_idx * batch_size
batch_end = min(batch_start + batch_size, n_frames)
padded_start = max(0, batch_start - temporal_pad)
@@ -200,12 +196,8 @@ def accumulate_activity_image(
nm.fill(True)
time_indices = time_indices_pre[:curr_size]
batch_vals = rho[:, padded_start:padded_end].T
- br[time_indices, depth_indices, row_indices_roi, col_indices_roi] = (
- batch_vals
- )
- nm[time_indices, depth_indices, row_indices_roi, col_indices_roi] = (
- np.isnan(batch_vals)
- )
+ br[time_indices, depth_indices, row_indices_roi, col_indices_roi] = batch_vals
+ nm[time_indices, depth_indices, row_indices_roi, col_indices_roi] = np.isnan(batch_vals)
br[nm] = 0
core_t = curr_size - 2
@@ -237,9 +229,7 @@ def accumulate_activity_image(
np.multiply(b3c, lmc, out=b3c, casting="unsafe")
r_lo, r_hi = row_start + 1, row_stop - 1
c_lo, c_hi = col_start + 1, col_stop - 1
- act_im[:, r_lo:r_hi, c_lo:c_hi] += np.sum(
- b3c, axis=0, dtype=np.float32
- )
+ act_im[:, r_lo:r_hi, c_lo:c_hi] += np.sum(b3c, axis=0, dtype=np.float32)
return act_im
@@ -258,14 +248,14 @@ def finalize_activity_image(
) -> np.ndarray:
"""Subtract the local NaN-median and suppress vertical support edges.
- Pixels whose rho was mostly NaN (``nan_ct > 0.5``) or that were never
+ Pixels whose rho was mostly NaN (nan_ct > 0.5) or that were never
selected are set to NaN. When superpixel reference centers are supplied,
an axis-aligned window includes only valid pixels with similar signed
vertical offsets from their nearest same-column reference center.
No snake identity or shared trajectory is assumed. Without reference
- centers, a fixed 5x11 footprint is used. The output is ``act_im - median``
+ centers, a fixed 5x11 footprint is used. The output is act_im - median
in the original activity units. With geometry, neighborhoods
- below ``phase_min_samples`` use the mean of finite first-pass medians
+ below phase_min_samples use the mean of finite first-pass medians
in the full window, regardless of phase. Empty fallback
windows and pixels without reference geometry remain NaN.
Finally, finite input pixels within valid support are set to zero if the
@@ -279,7 +269,7 @@ def finalize_activity_image(
act_im : ndarray
Accumulated activity image (masked in place before subtraction).
sel_pix_idxs : ndarray of int
- Flattened selected-pixel indices into ``act_im``'s grid.
+ Flattened selected-pixel indices into act_im's grid.
nan_ct : ndarray of shape (n_sel,)
Per-selected-pixel rho NaN fraction from
:func:`giant_python.extraction.band.activity.mask_high_nan_rho`.
@@ -309,9 +299,7 @@ def finalize_activity_image(
"""
nan_mask = np.full_like(act_im, True, dtype=bool)
valid_sel_pix = np.flatnonzero(nan_ct <= 0.5)
- nan_mask[np.unravel_index(sel_pix_idxs[valid_sel_pix], nan_mask.shape)] = (
- False
- )
+ nan_mask[np.unravel_index(sel_pix_idxs[valid_sel_pix], nan_mask.shape)] = False
act_im[nan_mask] = np.nan
if ref_r is not None and ref_c is not None:
@@ -327,15 +315,11 @@ def finalize_activity_image(
min_samples=phase_min_samples,
)
else:
- med_act_im = ndimage.generic_filter(
- act_im, np.nanmedian, size=(1, 5, 11)
- )
+ med_act_im = ndimage.generic_filter(act_im, np.nanmedian, size=(1, 5, 11))
# Check original input support, not median support. The vertical-only
# footprint preserves horizontal edges and never combines depth planes.
valid_input = (~nan_mask) & np.isfinite(act_im)
- window_height = (
- phase_window_height if ref_r is not None and ref_c is not None else 5
- )
+ window_height = phase_window_height if ref_r is not None and ref_c is not None else 5
# With no output override, ndimage preserves the boolean input dtype.
vertical_interior = cast(
NDArray[np.bool_],
@@ -355,7 +339,7 @@ def finalize_activity_image(
# Preserve scientific parity of phase assignment and frozen fallback passes.
-def phase_matched_nanmedian( # noqa: C901
+def phase_matched_nanmedian(
image: np.ndarray,
valid_pix_idxs: np.ndarray,
ref_r: np.ndarray,
@@ -369,7 +353,7 @@ def phase_matched_nanmedian( # noqa: C901
) -> np.ndarray:
"""Local median conditioned on signed reference-band phase.
- For each selected pixel, phase is ``row - nearest_reference_row`` using
+ For each selected pixel, phase is row - nearest_reference_row using
only reference centers in the same column and depth. Distances are
vertical, not Euclidean, so adjacent-column center spacing cannot change
the sign/phase. Different bands may overlap in column space and have
@@ -380,14 +364,14 @@ def phase_matched_nanmedian( # noqa: C901
coincident branches cannot be distinguished from these coordinates alone.
Columns without centers have no phase: no interpolation across gaps or
extrapolation beyond scanned columns is attempted. Multi-plane images
- require ``ref_d`` to avoid borrowing geometry from a different plane.
+ require ref_d to avoid borrowing geometry from a different plane.
- Within a clipped, axis-aligned ``height x width`` window, take only finite
- pixels in ``valid_pix_idxs`` whose signed phase differs by at most
- ``phase_tolerance`` (default 0, exact equality). The center itself is
+ Within a clipped, axis-aligned height x width window, take only finite
+ pixels in valid_pix_idxs whose signed phase differs by at most
+ phase_tolerance (default 0, exact equality). The center itself is
included if finite. There is no
branch-membership restriction: nearby different snakes can contribute
- when their phases match. At least ``min_samples`` (default 5) are required
+ when their phases match. At least min_samples (default 5) are required
for first-pass statistics. Otherwise, use the nanmean of finite first-pass
medians in the full spatial window, regardless of phase. Fallback values
are never reused by other windows; an empty fallback remains NaN.
@@ -397,18 +381,27 @@ def phase_matched_nanmedian( # noqa: C901
Non-selected/nonfinite pixels and
pixels without geometry remain NaN. Sparse phase/support arrays and chunked
gathers bound working memory; only output images are dense.
+
+ Returns
+ -------
+ np.ndarray
+ The phase-conditioned local medians, with the shape of image and at least float32
+ precision; NaN at pixels that are not selected, not finite or without geometry.
+
+ Raises
+ ------
+ ValueError
+ If image is not a non-empty 3-D array, height or width is not a positive odd
+ integer, min_samples, chunk_size or phase_tolerance is out of range, the
+ reference coordinates are empty, mismatched, or not finite integers (ref_d is also
+ required for multi-plane images), or valid_pix_idxs is not a 1-D integer array of
+ in-bounds indices.
"""
image = np.asarray(image)
if image.ndim != 3 or any(size == 0 for size in image.shape):
- raise ValueError(
- "image must have non-empty shape (depth, row, column)"
- )
+ raise ValueError("image must have non-empty shape (depth, row, column)")
for name, value in (("height", height), ("width", width)):
- if (
- not isinstance(value, (int, np.integer))
- or value < 1
- or value % 2 == 0
- ):
+ if not isinstance(value, (int, np.integer)) or value < 1 or value % 2 == 0:
raise ValueError(f"{name} must be a positive odd integer")
for name, value in (
("min_samples", min_samples),
@@ -434,27 +427,17 @@ def phase_matched_nanmedian( # noqa: C901
if ref_d.size != ref_r.size:
raise ValueError("ref_d must have the same size as ref_r")
for coordinates in (ref_c, ref_d):
- if not np.all(np.isfinite(coordinates)) or np.any(
- coordinates != np.rint(coordinates)
- ):
- raise ValueError(
- "reference columns and depths must be finite integers"
- )
+ if not np.all(np.isfinite(coordinates)) or np.any(coordinates != np.rint(coordinates)):
+ raise ValueError("reference columns and depths must be finite integers")
ref_c, ref_d = ref_c.astype(np.intp), ref_d.astype(np.intp)
selected = np.asarray(valid_pix_idxs)
- if selected.ndim != 1 or (
- selected.size and not np.issubdtype(selected.dtype, np.integer)
- ):
- raise ValueError(
- "valid_pix_idxs must be a one-dimensional integer array"
- )
+ if selected.ndim != 1 or (selected.size and not np.issubdtype(selected.dtype, np.integer)):
+ raise ValueError("valid_pix_idxs must be a one-dimensional integer array")
if np.any(selected < 0) or np.any(selected >= image.size):
raise ValueError("valid_pix_idxs contains an out-of-bounds index")
selected = np.unique(selected.astype(np.intp))
- result = np.full(
- image.shape, np.nan, dtype=np.result_type(image.dtype, np.float32)
- )
+ result = np.full(image.shape, np.nan, dtype=np.result_type(image.dtype, np.float32))
if not selected.size:
return result
@@ -463,18 +446,14 @@ def phase_matched_nanmedian( # noqa: C901
# Group references by (depth, column); unlike the legacy filter, do not
# collapse all rows in a column to one shared trajectory.
references = {}
- for depth, column, row in zip(
- ref_d[in_bounds], ref_c[in_bounds], ref_r[in_bounds]
- ):
+ for depth, column, row in zip(ref_d[in_bounds], ref_c[in_bounds], ref_r[in_bounds]):
references.setdefault(int(depth * nc + column), []).append(row)
depths, rows, cols = np.unravel_index(selected, image.shape)
keys = depths * nc + cols
order = np.argsort(keys, kind="stable")
- boundaries = np.r_[
- 0, np.flatnonzero(np.diff(keys[order])) + 1, selected.size
- ]
+ boundaries = np.r_[0, np.flatnonzero(np.diff(keys[order])) + 1, selected.size]
phase = np.full(selected.size, np.nan)
- for start, stop in zip(boundaries[:-1], boundaries[1:]):
+ for start, stop in itertools.pairwise(boundaries):
positions = order[start:stop]
centers = references.get(int(keys[positions[0]]))
if centers is None:
@@ -485,8 +464,7 @@ def phase_matched_nanmedian( # noqa: C901
left = np.clip(insertion - 1, 0, centers.size - 1)
right = np.clip(insertion, 0, centers.size - 1)
nearest = np.where(
- np.abs(pixel_rows - centers[left])
- <= np.abs(pixel_rows - centers[right]),
+ np.abs(pixel_rows - centers[left]) <= np.abs(pixel_rows - centers[right]),
left,
right,
)
@@ -503,41 +481,39 @@ def phase_matched_nanmedian( # noqa: C901
values = image.ravel()[selected]
outputs = np.flatnonzero(np.isfinite(phase) & np.isfinite(values))
- def windows(output_positions):
- """Yield chunked spatial lookups and exact selected-pixel support."""
+ def windows(
+ output_positions: NDArray[np.intp],
+ ) -> Iterator[tuple[NDArray[np.intp], NDArray[np.intp], NDArray[np.bool_]]]:
+ """Yield chunked spatial lookups and exact selected-pixel support.
+
+ Yields
+ ------
+ positions : ndarray of intp
+ The output positions of the chunk.
+ lookup : ndarray of intp
+ Index among the selected pixels of each window sample of each position.
+ support : ndarray of bool
+ Whether each window sample is inside the image and is a selected pixel.
+ """
for start in range(0, output_positions.size, chunk_size):
positions = output_positions[start : start + chunk_size]
sample_r = rows[positions, None] + row_offsets
sample_c = cols[positions, None] + col_offsets
- inside = (
- (sample_r >= 0)
- & (sample_r < nr)
- & (sample_c >= 0)
- & (sample_c < nc)
- )
- sample_flat = (
- depths[positions, None] * nr + sample_r
- ) * nc + sample_c
- lookup = np.minimum(
- np.searchsorted(selected, sample_flat), selected.size - 1
- )
+ inside = (sample_r >= 0) & (sample_r < nr) & (sample_c >= 0) & (sample_c < nc)
+ sample_flat = (depths[positions, None] * nr + sample_r) * nc + sample_c
+ lookup = np.minimum(np.searchsorted(selected, sample_flat), selected.size - 1)
yield positions, lookup, inside & (selected[lookup] == sample_flat)
for positions, lookup, support in windows(outputs):
accept = (
support
& np.isfinite(values[lookup])
- & (
- np.abs(phase[lookup] - phase[positions, None])
- <= phase_tolerance
- )
+ & (np.abs(phase[lookup] - phase[positions, None]) <= phase_tolerance)
)
enough = np.count_nonzero(accept, axis=1) >= min_samples
if not np.any(enough):
continue
- samples = np.where(
- accept[enough], values[lookup[enough]], np.nan
- ).astype(result.dtype)
+ samples = np.where(accept[enough], values[lookup[enough]], np.nan).astype(result.dtype)
medians = np.nanmedian(samples, axis=1)
flat = selected[positions[enough]]
result.ravel()[flat] = medians
@@ -556,9 +532,7 @@ def windows(output_positions):
axis=1,
dtype=np.float64,
)
- result.ravel()[selected[positions[enough]]] = (
- totals[enough] / counts[enough]
- )
+ result.ravel()[selected[positions[enough]]] = totals[enough] / counts[enough]
return result
@@ -577,12 +551,24 @@ def snake_aligned_nanmedian(
vertical spacing. The trajectory is unwrapped modulo that spacing so its
row does not jump when an outer snake is absent from a column. Disconnected
column runs are kept separate. For each valid output pixel, this function
- gathers ``height * width`` samples translated by the local trajectory.
+ gathers height * width samples translated by the local trajectory.
Work is restricted to valid pixels and chunked to bound temporary memory.
- ``ref_r`` and ``ref_c`` must already be expressed in ``image`` coordinates;
+ ref_r and ref_c must already be expressed in image coordinates;
this helper does not apply motion correction itself.
The output is NaN at unrequested pixels and all-NaN footprints.
+
+ Returns
+ -------
+ np.ndarray
+ The local medians along the band trajectory, with the shape of image and at least
+ float32 precision; NaN at unrequested pixels and all-NaN footprints.
+
+ Raises
+ ------
+ ValueError
+ If height or width is not a positive odd integer, ref_r and ref_c are
+ empty or differ in size, or no reference center falls inside the image.
"""
if height < 1 or width < 1 or height % 2 == 0 or width % 2 == 0:
raise ValueError("height and width must be positive odd integers")
@@ -599,18 +585,10 @@ def snake_aligned_nanmedian(
raise ValueError("no reference centers fall inside the image")
rows_by_column = [np.sort(ref_r[ref_c == column]) for column in columns]
- spacing_samples = [
- np.diff(rows) for rows in rows_by_column if rows.size > 1
- ]
- row_spacings = (
- np.concatenate(spacing_samples)
- if spacing_samples
- else np.empty(0, dtype=float)
- )
+ spacing_samples = [np.diff(rows) for rows in rows_by_column if rows.size > 1]
+ row_spacings = np.concatenate(spacing_samples) if spacing_samples else np.empty(0, dtype=float)
snake_spacing = (
- float(np.median(row_spacings[row_spacings > 0]))
- if np.any(row_spacings > 0)
- else None
+ float(np.median(row_spacings[row_spacings > 0])) if np.any(row_spacings > 0) else None
)
run_starts = np.r_[0, np.flatnonzero(np.diff(columns) > 1) + 1]
@@ -620,32 +598,25 @@ def snake_aligned_nanmedian(
for segment, (start, stop) in enumerate(zip(run_starts, run_stops)):
segment_at_reference[start:stop] = segment
if snake_spacing is None:
- center_rows[start:stop] = [
- np.median(rows) for rows in rows_by_column[start:stop]
- ]
+ center_rows[start:stop] = [np.median(rows) for rows in rows_by_column[start:stop]]
continue
for index in range(start + 1, stop):
delta = center_rows[index] - center_rows[index - 1]
- center_rows[index] -= (
- np.rint(delta / snake_spacing) * snake_spacing
- )
+ center_rows[index] -= np.rint(delta / snake_spacing) * snake_spacing
all_columns = np.arange(n_cols)
insertions = np.searchsorted(columns, all_columns)
right = np.clip(insertions, 0, columns.size - 1)
left = np.clip(insertions - 1, 0, columns.size - 1)
nearest = np.where(
- np.abs(all_columns - columns[left])
- <= np.abs(columns[right] - all_columns),
+ np.abs(all_columns - columns[left]) <= np.abs(columns[right] - all_columns),
left,
right,
)
trajectory = center_rows[nearest]
trajectory_segment = segment_at_reference[nearest]
- result = np.full_like(
- image, np.nan, dtype=np.result_type(image, np.float32)
- )
+ result = np.full_like(image, np.nan, dtype=np.result_type(image, np.float32))
col_offsets = np.arange(-(width // 2), width // 2 + 1)
row_offsets = np.arange(-(height // 2), height // 2 + 1)
@@ -655,30 +626,16 @@ def snake_aligned_nanmedian(
sample_cols = cols[:, None] + col_offsets[None, :]
valid_cols = (sample_cols >= 0) & (sample_cols < n_cols)
clipped_cols = np.clip(sample_cols, 0, n_cols - 1)
- valid_cols &= (
- trajectory_segment[clipped_cols] == trajectory_segment[cols, None]
- )
- path_delta = np.rint(
- trajectory[clipped_cols] - trajectory[cols, None]
- ).astype(np.intp)
+ valid_cols &= trajectory_segment[clipped_cols] == trajectory_segment[cols, None]
+ path_delta = np.rint(trajectory[clipped_cols] - trajectory[cols, None]).astype(np.intp)
path_rows = rows[:, None] + path_delta
sample_rows = path_rows[:, :, None] + row_offsets[None, None, :]
- sample_cols = np.broadcast_to(
- clipped_cols[:, :, None], sample_rows.shape
- )
- sample_depths = np.broadcast_to(
- depths[:, None, None], sample_rows.shape
- )
- valid = (
- valid_cols[:, :, None]
- & (sample_rows >= 0)
- & (sample_rows < n_rows)
- )
+ sample_cols = np.broadcast_to(clipped_cols[:, :, None], sample_rows.shape)
+ sample_depths = np.broadcast_to(depths[:, None, None], sample_rows.shape)
+ valid = valid_cols[:, :, None] & (sample_rows >= 0) & (sample_rows < n_rows)
samples = np.full(sample_rows.shape, np.nan, dtype=result.dtype)
- samples[valid] = image[
- sample_depths[valid], sample_rows[valid], sample_cols[valid]
- ]
+ samples[valid] = image[sample_depths[valid], sample_rows[valid], sample_cols[valid]]
medians = np.nanmedian(samples, axis=(1, 2))
result.ravel()[flat] = medians
return result
diff --git a/src/giant_python/extraction/band/traces.py b/src/giant_python/extraction/band/traces.py
index a5830a26..559a83b1 100644
--- a/src/giant_python/extraction/band/traces.py
+++ b/src/giant_python/extraction/band/traces.py
@@ -1,15 +1,15 @@
"""High-resolution per-trial trace extraction.
-Ported from ``get_high_res_traces`` in
-``extractSLAP2IntegrationSources.py`` (ref 844-1011). For one trial this reads
+Ported from get_high_res_traces in
+extractSLAP2IntegrationSources.py (ref 844-1011). For one trial this reads
the high-res superpixel activity, interpolates the alignment motion/background
onto the trial's downsample grid, bins the frames by motion (matching the
low-res motion bins used during NMF), and — per motion bin — projects the fixed
-spatial profiles ``A_final`` into superpixel space and extracts per-source
-temporal traces (``phi``, stored as ``dF_ls``) via least squares or
-normalized profile-weighted averages. Background (``F0``) is the
+spatial profiles A_final into superpixel space and extracts per-source
+temporal traces (phi, stored as dF_ls) via least squares or
+normalized profile-weighted averages. Background (F0) is the
backprojection of each projected profile onto the background, and a
-backprojection of the fit residual (``data - background - x @ phi``) is kept
+backprojection of the fit residual (data - background - x @ phi) is kept
for the final F0 estimate. Transient fitting
adds separate denoised traces and events, jointly across the trial with fixed
spatial profiles; F0 is never fitted with events. The production workflow
@@ -19,14 +19,14 @@
The pure compute (:func:`compute_high_res_traces`) is factored out of the IO
wrapper (:func:`get_high_res_traces`, which reads the SLAP2 file lazily via
:mod:`giant_python.extraction.band.trial_data`) so the numerics can be used
-without ``slap2_utils``. The workflow owns per-trial scheduling. Results use
-``TrialTraceResult``, with denoised traces, events and the residual
+without slap2_utils. The workflow owns per-trial scheduling. Results use
+TrialTraceResult, with denoised traces, events and the residual
backprojection after the original fields.
"""
from __future__ import annotations
-from typing import List, Optional, Tuple, cast
+from typing import cast
import numpy as np
import torch
@@ -40,15 +40,13 @@
from .types import TrialTraceResult
-def _empty_trace_result(
- n_sources: int, num_channels: int, n_soma: int
-) -> TrialTraceResult:
+def _empty_trace_result(n_sources: int, num_channels: int, n_soma: int) -> TrialTraceResult:
"""Return the all-empty result tuple for a skipped trial.
Parameters
----------
n_sources : int
- Number of sources (column count of the empty ``phi``/``F0``).
+ Number of sources (column count of the empty phi/F0).
num_channels : int
Number of acquisition channels.
n_soma : int
@@ -81,11 +79,11 @@ def _empty_trace_result(
def _interp_trial_alignment(
frames: np.ndarray, a_data: dict, background_ds: np.ndarray
-):
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Interpolate alignment motion/background onto the trial's frame grid.
Motion and per-superpixel background are linearly interpolated from the
- alignment downsample grid to ``frames``; the online shifts use
+ alignment downsample grid to frames; the online shifts use
nearest-neighbor interpolation.
Parameters
@@ -93,27 +91,24 @@ def _interp_trial_alignment(
frames : ndarray
The trial's high-res downsample frame line positions.
a_data : dict
- Alignment data (``DSframes``, ``motionDSr/c/z``,
- ``onlineYshift/Xshift/Zshift``).
+ Alignment data (DSframes, motionDSr/c/z,
+ onlineYshift/Xshift/Zshift).
background_ds : ndarray of shape (n_superpixels, n_ds)
Per-superpixel low-res background for this trial.
Returns
-------
tuple
- ``(motion_r, motion_c, motion_z, background, online_y, online_x,
- online_z)``.
+ (motion_r, motion_c, motion_z, background, online_y, online_x,
+ online_z).
"""
ds = a_data["DSframes"]
motion_r = np.interp(frames, ds, a_data["motionDSr"])
motion_c = np.interp(frames, ds, a_data["motionDSc"])
motion_z = np.interp(frames, ds, a_data["motionDSz"])
- background = np.array(
- [
- np.interp(frames, ds, background_ds[i])
- for i in range(background_ds.shape[0])
- ]
- )
+ background = np.array([
+ np.interp(frames, ds, background_ds[i]) for i in range(background_ds.shape[0])
+ ])
online_y = nearest_interp(frames, ds, a_data["onlineYshift"])
online_x = nearest_interp(frames, ds, a_data["onlineXshift"])
online_z = nearest_interp(frames, ds, a_data["onlineZshift"])
@@ -136,10 +131,10 @@ def _bin_trial_motion(
unique_motion_ds: np.ndarray,
mot_inds_to_keep_ds: np.ndarray,
z_tol: float = 1.5,
-) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Bin trial frames by motion and match them to the low-res motion bins.
- Frames within ``z_tol`` um of the median z are rebinned into 2-D (row, col)
+ Frames within z_tol um of the median z are rebinned into 2-D (row, col)
motion bins; each retained low-res bin is matched to its trial bin so the
same PSF geometry is reused.
@@ -161,7 +156,7 @@ def _bin_trial_motion(
unique_motion : ndarray of shape (n_bins, 2)
Trial 2-D motion bins (over the z-kept frames).
mot_inds : ndarray of shape (n_frames,), int32
- Per-frame trial-bin index (``-1`` for dropped frames).
+ Per-frame trial-bin index (-1 for dropped frames).
mot_inds_to_keep : ndarray
Trial-bin indices matching a kept low-res bin.
frames_to_keep : ndarray of bool
@@ -179,9 +174,7 @@ def _bin_trial_motion(
)
mot_inds = -1 * np.ones((len(mot_inds),), dtype=np.int32)
- stacked = np.round(
- np.stack((motion_r, motion_c), axis=1)[frames_to_keep, :]
- )
+ stacked = np.round(np.stack((motion_r, motion_c), axis=1)[frames_to_keep, :])
unique_motion, inv = np.unique(stacked, axis=0, return_inverse=True)
mot_inds[frames_to_keep] = np.reshape(inv, -1)
@@ -201,16 +194,20 @@ def _bin_trial_motion(
return unique_motion, mot_inds, mot_inds_to_keep, frames_to_keep
-def _weighted_trace_average(
- x: torch.Tensor, data: torch.Tensor
-) -> torch.Tensor:
+def _weighted_trace_average(x: torch.Tensor, data: torch.Tensor) -> torch.Tensor:
"""Average superpixels using each projected source profile's intensities.
- ``x`` is (superpixels, sources), ``data`` is (superpixels, frames), and
+ x is (superpixels, sources), data is (superpixels, frames), and
the result is (frames, sources). Normalize in superpixel space for each
motion bin: projection through H need not preserve the profile's mass.
Sources with no observed profile support return NaN, not a zero signal.
Unlike least squares, overlapping sources are not de-mixed.
+
+ Returns
+ -------
+ torch.Tensor
+ Weighted-average trace of shape (frames, sources); NaN for sources
+ with no observed profile support.
"""
mass = x.sum(dim=0)
weights = x / mass.masked_fill(mass <= 0, float("nan"))
@@ -220,29 +217,40 @@ def _weighted_trace_average(
def _backproject(x: torch.Tensor, data: torch.Tensor) -> torch.Tensor:
"""Backproject each projected source profile onto a superpixel movie.
- Returns ``x_j^T data / x_j^T x_j`` as (frames, sources): the per-source
- coefficient in the same units as the least-squares/denoised ``phi``, but
+ Returns x_j^T data / x_j^T x_j as (frames, sources): the per-source
+ coefficient in the same units as the least-squares/denoised phi, but
without de-mixing overlapping sources. Zero profiles return zero, like
the basic least-squares solution; nonfinite samples propagate as NaN.
+
+ Returns
+ -------
+ torch.Tensor
+ Per-source backprojection coefficients of shape (frames, sources).
"""
norm = (x * x).sum(dim=0)
return (data.T @ x) / norm.masked_fill(norm <= 0, 1.0)
def _validate_transient_settings(
- transient_options, simple_trace_extraction, analyze_hz
-):
- """Validate mutually exclusive trace modes and the transient grid rate."""
+ transient_options: TransientOptions | None,
+ simple_trace_extraction: bool,
+ analyze_hz: float | None,
+) -> None:
+ """Validate mutually exclusive trace modes and the transient grid rate.
+
+ Raises
+ ------
+ ValueError
+ If transient options are combined with simple trace extraction, or if
+ `analyze_hz` is not a positive finite number.
+ TypeError
+ If `transient_options` is neither `TransientOptions` nor None.
+ """
if transient_options is not None:
if simple_trace_extraction:
- raise ValueError(
- "Simple and convolution trace extraction are mutually "
- "exclusive"
- )
+ raise ValueError("Simple and convolution trace extraction are mutually exclusive")
if not isinstance(transient_options, TransientOptions):
- raise TypeError(
- "transient_options must be TransientOptions or None"
- )
+ raise TypeError("transient_options must be TransientOptions or None")
from ...models.params import _positive
_positive("analyze_hz", analyze_hz)
@@ -262,17 +270,17 @@ def _solve_trial_phi_f0(
dmd_pixels_per_row: int,
simple_trace_extraction: bool = False,
*,
- transient_options: Optional[TransientOptions] = None,
- analyze_hz: Optional[float] = None,
+ transient_options: TransientOptions | None = None,
+ analyze_hz: float | None = None,
return_transient: bool = False,
) -> tuple:
"""Extract per-source traces, background and residual backprojections.
- For each kept motion bin, shifts ``H`` by the bin's motion, projects
- ``A_final`` into superpixel space, solves for the source temporal
+ For each kept motion bin, shifts H by the bin's motion, projects
+ A_final into superpixel space, solves for the source temporal
weights (from the background-subtracted residual), and backprojects the
- profiles onto the background (``F0``) and onto the fit residual
- ``data - background - x @ phi``.
+ profiles onto the background (F0) and onto the fit residual
+ data - background - x @ phi.
Parameters
----------
@@ -287,13 +295,13 @@ def _solve_trial_phi_f0(
mot_inds_to_keep : ndarray
Trial-bin indices to solve.
sparse_h_inds, sparse_h_vals : ndarray
- Base sparse ``H`` (from ``geometry.build_sparse_h``).
+ Base sparse H (from geometry.build_sparse_h).
sel_pix_idxs : ndarray of int
Sorted flat selected-pixel indices.
a_final : torch.Tensor of shape (n_pixels, n_sources)
Fixed source spatial profiles.
num_super_pixels : int
- Superpixel count (``H`` row count).
+ Superpixel count (H row count).
dmd_pixels_per_row : int
Grid geometry (column-shift stride).
simple_trace_extraction : bool, optional
@@ -320,20 +328,21 @@ def _solve_trial_phi_f0(
weighted averaging has no profile support). Outside simple
extraction, F0 is :func:`_backproject` of the background, not a
least-squares fit. The optional residual term is the backprojection
- of ``data - background - x @ phi`` (zero for simple extraction).
+ of data - background - x @ phi (zero for simple extraction).
+
+ Raises
+ ------
+ RuntimeError
+ If the transient fit does not converge.
"""
- _validate_transient_settings(
- transient_options, simple_trace_extraction, analyze_hz
- )
+ _validate_transient_settings(transient_options, simple_trace_extraction, analyze_hz)
n_sources = a_final.shape[1]
n_frames = data.shape[1]
phi = torch.full((n_frames, n_sources), float("nan"), dtype=torch.float32)
f0 = torch.full((n_frames, n_sources), float("nan"), dtype=torch.float32)
denoised = torch.full_like(phi, float("nan"))
events = torch.full_like(phi, float("nan"))
- f_residual = torch.full_like(
- phi, 0.0 if simple_trace_extraction else float("nan")
- )
+ f_residual = torch.full_like(phi, 0.0 if simple_trace_extraction else float("nan"))
residual = data - background
# One shifted superpixel<-pixel H per trial motion bin (same builder the
@@ -347,25 +356,17 @@ def _solve_trial_phi_f0(
dmd_pixels_per_row,
)
- extract = (
- _weighted_trace_average
- if simple_trace_extraction
- else solve_phi_motion
- )
+ extract = _weighted_trace_average if simple_trace_extraction else solve_phi_motion
designs = {}
for motion_idx in mot_inds_to_keep:
motion_frames = np.flatnonzero(mot_inds == motion_idx)
x = torch.sparse.mm(h_mots[motion_idx], a_final[sel_pix_idxs, :])
# F0 is never fitted with transient events.
- residual_frames = torch.from_numpy(
- residual[:, motion_frames].astype(np.float32)
- )
+ residual_frames = torch.from_numpy(residual[:, motion_frames].astype(np.float32))
phi[motion_frames, :] = extract(x, residual_frames)
if transient_options is not None:
designs[int(motion_idx)] = x.detach().cpu().numpy()
- background_frames = torch.from_numpy(
- background[:, motion_frames].astype(np.float32)
- )
+ background_frames = torch.from_numpy(background[:, motion_frames].astype(np.float32))
if simple_trace_extraction:
f0[motion_frames, :] = extract(x, background_frames)
else:
@@ -405,7 +406,7 @@ def _solve_trial_phi_f0(
def _compute_global_f(
data: np.ndarray,
- data2: Optional[np.ndarray],
+ data2: np.ndarray | None,
frames_to_keep: np.ndarray,
num_channels: int,
) -> np.ndarray:
@@ -416,7 +417,7 @@ def _compute_global_f(
data : ndarray of shape (n_superpixels, n_frames)
Channel-1 activity.
data2 : ndarray or None
- Channel-2 activity (used when ``num_channels >= 2``).
+ Channel-2 activity (used when num_channels >= 2).
frames_to_keep : ndarray of bool
Dropped frames are set to NaN.
num_channels : int
@@ -438,8 +439,8 @@ def _compute_global_f(
def _compute_f_soma(
data: np.ndarray,
- data2: Optional[np.ndarray],
- soma_sps: List[np.ndarray],
+ data2: np.ndarray | None,
+ soma_sps: list[np.ndarray],
frames_to_keep: np.ndarray,
num_channels: int,
) -> np.ndarray:
@@ -450,7 +451,7 @@ def _compute_f_soma(
data : ndarray of shape (n_superpixels, n_frames)
Channel-1 activity.
data2 : ndarray or None
- Channel-2 activity (used when ``num_channels >= 2``).
+ Channel-2 activity (used when num_channels >= 2).
soma_sps : list of ndarray
Per-ROI superpixel index arrays.
frames_to_keep : ndarray of bool
@@ -464,22 +465,18 @@ def _compute_f_soma(
Per-ROI fluorescence.
"""
n_frames = data.shape[1]
- f_soma = np.full(
- (n_frames, len(soma_sps), num_channels), np.nan, dtype=np.float32
- )
+ f_soma = np.full((n_frames, len(soma_sps), num_channels), np.nan, dtype=np.float32)
for i, roi_sps in enumerate(soma_sps):
f_soma[:, i, 0] = np.nansum(data[roi_sps, :], axis=0)
if num_channels >= 2:
- f_soma[:, i, 1] = np.nansum(
- cast(np.ndarray, data2)[roi_sps, :], axis=0
- )
+ f_soma[:, i, 1] = np.nansum(cast(np.ndarray, data2)[roi_sps, :], axis=0)
f_soma[~frames_to_keep, :, :] = np.nan
return f_soma
def compute_high_res_traces(
data: np.ndarray,
- data2: Optional[np.ndarray],
+ data2: np.ndarray | None,
background_ds: np.ndarray,
frames: np.ndarray,
a_data: dict,
@@ -496,12 +493,12 @@ def compute_high_res_traces(
dmd_pixels_per_column: int,
dmd_pixels_per_row: int,
num_channels: int,
- soma_sps: List[np.ndarray],
+ soma_sps: list[np.ndarray],
z_tol: float = 1.5,
simple_trace_extraction: bool = False,
*,
- transient_options: Optional[TransientOptions] = None,
- analyze_hz: Optional[float] = None,
+ transient_options: TransientOptions | None = None,
+ analyze_hz: float | None = None,
) -> TrialTraceResult:
"""Compute one trial's high-res source traces from loaded arrays.
@@ -518,9 +515,9 @@ def compute_high_res_traces(
a_data : dict
Alignment data for this trial.
subsample_matrix_inds : ndarray
- Superpixel reference-pixel map (from ``geometry``).
+ Superpixel reference-pixel map (from geometry).
sparse_h_inds, sparse_h_vals : ndarray
- Base sparse ``H``.
+ Base sparse H.
a_final : torch.Tensor of shape (n_pixels, n_sources)
Fixed source spatial profiles.
unique_motion_ds : ndarray
@@ -558,8 +555,14 @@ def compute_high_res_traces(
-------
TrialTraceResult
Named source traces and auxiliary data. Source trace arrays are
- ``(n_frames, n_sources)``; denoised traces/events are separate from
- d_f, and ``f_residual`` is the backprojected fit residual.
+ (n_frames, n_sources); denoised traces/events are separate from
+ d_f, and f_residual is the backprojected fit residual.
+
+ Raises
+ ------
+ ValueError
+ If transient fitting is requested and `frames` is not a finite
+ one-dimensional vector, or is not strictly increasing.
"""
if transient_options is not None:
frame_grid = np.asarray(frames)
@@ -569,9 +572,7 @@ def compute_high_res_traces(
# can have alternating line spacings. Use the explicit nominal rate.
steps = np.diff(frame_grid)
if np.any(steps <= 0):
- raise ValueError(
- "Convolution traces require chronological frames; retain gaps"
- )
+ raise ValueError("Convolution traces require chronological frames; retain gaps")
(
motion_r,
motion_c,
@@ -630,9 +631,7 @@ def compute_high_res_traces(
)
global_f = _compute_global_f(data, data2, frames_to_keep, num_channels)
- f_soma = _compute_f_soma(
- data, data2, soma_sps, frames_to_keep, num_channels
- )
+ f_soma = _compute_f_soma(data, data2, soma_sps, frames_to_keep, num_channels)
return TrialTraceResult(
phi.numpy(),
@@ -657,13 +656,13 @@ def _load_high_res_trial_data(
datadr: str,
trial_table: dict,
num_channels: int,
-):
+) -> tuple[np.ndarray, np.ndarray | None, dict, np.ndarray]:
"""Read one trial's high-res activity via the SLAP2 reader.
Returns
-------
tuple
- ``(data, data2, a_data, frames)`` with count-normalized activity.
+ (data, data2, a_data, frames) with count-normalized activity.
"""
# The reader returns None only for skipped trials; keep_trial is True.
result = cast(
@@ -697,7 +696,7 @@ def get_high_res_traces(
subsample_matrix_inds: np.ndarray,
sparse_h_inds: np.ndarray,
sparse_h_vals: np.ndarray,
- a_final,
+ a_final: np.ndarray | torch.Tensor,
unique_motion_ds: np.ndarray,
mot_inds_to_keep_ds: np.ndarray,
median_z: float,
@@ -707,22 +706,22 @@ def get_high_res_traces(
dmd_pixels_per_column: int,
dmd_pixels_per_row: int,
num_channels: int,
- soma_sps: List[np.ndarray],
+ soma_sps: list[np.ndarray],
z_tol: float = 1.5,
simple_trace_extraction: bool = False,
*,
- transient_options: Optional[TransientOptions] = None,
+ transient_options: TransientOptions | None = None,
) -> TrialTraceResult:
"""Read and extract one trial's high-res source traces.
- Skipped trials (``keep_trial`` False) return the empty result immediately;
- otherwise the trial is read (via ``slap2_utils``) and passed to
+ Skipped trials (keep_trial False) return the empty result immediately;
+ otherwise the trial is read (via slap2_utils) and passed to
:func:`compute_high_res_traces`.
Parameters
----------
trial_info : tuple
- ``(trial_ix, keep_trial, background_ds)`` for this trial.
+ (trial_ix, keep_trial, background_ds) for this trial.
dmd_ix : int
0-based DMD index.
samp_freq : float
@@ -734,9 +733,9 @@ def get_high_res_traces(
trial_table : dict
Normalized trial table.
subsample_matrix_inds, sparse_h_inds, sparse_h_vals : ndarray
- Geometry / sparse ``H``.
+ Geometry / sparse H.
a_final : ndarray or torch.Tensor
- Fixed source spatial profiles ``(n_pixels, n_sources)``.
+ Fixed source spatial profiles (n_pixels, n_sources).
unique_motion_ds, mot_inds_to_keep_ds : ndarray
Low-res motion bins / kept indices.
median_z : float
diff --git a/src/giant_python/extraction/band/transient.py b/src/giant_python/extraction/band/transient.py
index 4b9c9213..27ae515a 100644
--- a/src/giant_python/extraction/band/transient.py
+++ b/src/giant_python/extraction/band/transient.py
@@ -11,6 +11,7 @@
from dataclasses import dataclass
import numpy as np
+import numpy.typing as npt
from scipy.optimize import minimize
from scipy.signal import fftconvolve, lfilter
@@ -22,9 +23,9 @@ class TransientOptions:
"""Settings for trace-only fitting with fixed spatial profiles.
The workflow supplies tau_s from the shared BandSiloParams.decay_tau_s.
- ``beta`` overrides the trial-relative ``beta_fraction`` when supplied.
- ``debias`` optionally refits selected events without the L1 penalty.
- ``event_threshold`` is in absolute coefficient units, not scaled units.
+ beta overrides the trial-relative beta_fraction when supplied.
+ debias optionally refits selected events without the L1 penalty.
+ event_threshold is in absolute coefficient units, not scaled units.
"""
tau_s: float = 0.15
@@ -35,8 +36,14 @@ class TransientOptions:
debias: bool = False
event_threshold: float = 1e-6
- def __post_init__(self):
- """Reject invalid solver settings before fitting or reading data."""
+ def __post_init__(self) -> None:
+ """Reject invalid solver settings before fitting or reading data.
+
+ Raises
+ ------
+ ValueError
+ If a numeric setting is out of range or `debias` is not a bool.
+ """
_positive("tau_s", self.tau_s)
_positive("max_iter", self.max_iter, integer=True)
_positive("tolerance", self.tolerance)
@@ -62,14 +69,21 @@ class TransientResult:
class TransientOperator:
"""Causal convolution and exact adjoint without a dense temporal matrix."""
- def __init__(self, analyze_hz, tau_s, kernel=None):
- """Use a unit-peak exponential or a nonnegative causal kernel."""
+ def __init__(
+ self, analyze_hz: float, tau_s: float, kernel: npt.ArrayLike | None = None
+ ) -> None:
+ """Use a unit-peak exponential or a nonnegative causal kernel.
+
+ Raises
+ ------
+ ValueError
+ If `kernel` is not a finite, nonnegative, nonempty 1-D array with
+ a positive first element.
+ """
_positive("analyze_hz", analyze_hz)
_positive("tau_s", tau_s)
self.gamma = float(np.exp(-1 / (analyze_hz * tau_s)))
- self.kernel = (
- None if kernel is None else np.asarray(kernel, dtype=float)
- )
+ self.kernel = None if kernel is None else np.asarray(kernel, dtype=float)
if self.kernel is not None and (
self.kernel.ndim != 1
or not self.kernel.size
@@ -77,25 +91,45 @@ def __init__(self, analyze_hz, tau_s, kernel=None):
or np.any(self.kernel < 0)
or self.kernel[0] <= 0
):
- raise ValueError(
- "kernel must be finite, nonnegative, with kernel[0]>0"
- )
+ raise ValueError("kernel must be finite, nonnegative, with kernel[0]>0")
+
+ def forward(self, events: np.ndarray) -> np.ndarray:
+ """Convolve all sources in chronological order, including gaps.
- def forward(self, events):
- """Convolve all sources in chronological order, including gaps."""
+ Returns
+ -------
+ np.ndarray
+ Convolved traces with the same leading length as `events`, one column per source.
+ """
if self.kernel is None:
return lfilter([1.0], [1.0, -self.gamma], events, axis=0)
- return fftconvolve(events, self.kernel[:, None], mode="full", axes=0)[
- : len(events)
- ]
+ return fftconvolve(events, self.kernel[:, None], mode="full", axes=0)[: len(events)]
- def adjoint(self, traces):
- """Apply the exact transpose, including finite-trial boundaries."""
+ def adjoint(self, traces: np.ndarray) -> np.ndarray:
+ """Apply the exact transpose, including finite-trial boundaries.
+
+ Returns
+ -------
+ np.ndarray
+ Adjoint of `forward` applied to `traces`, with the same shape as `traces`.
+ """
return self.forward(traces[::-1])[::-1]
-def _temporal_quadratic(normal, groups, trace):
- """Half squared error minus its data constant, and the trace gradient."""
+def _temporal_quadratic(
+ normal: dict[int, tuple[np.ndarray, np.ndarray]],
+ groups: dict[int, np.ndarray],
+ trace: np.ndarray,
+) -> tuple[float, np.ndarray]:
+ """Half squared error minus its data constant, and the trace gradient.
+
+ Returns
+ -------
+ value : float
+ Half squared error minus its data constant, summed over motion groups.
+ gradient : np.ndarray
+ Gradient of `value` with respect to `trace`, same shape as `trace`.
+ """
gradient = np.zeros_like(trace)
value = 0.0
for motion, (gram, rhs) in normal.items():
@@ -107,8 +141,39 @@ def _temporal_quadratic(normal, groups, trace):
return float(value), gradient
-def _prepare_transient_system(residual, designs, motion_indices, valid):
- """Validate arrays and build motion-specific sufficient statistics."""
+def _prepare_transient_system(
+ residual: npt.ArrayLike,
+ designs: dict[int, np.ndarray],
+ motion_indices: npt.ArrayLike,
+ valid: npt.ArrayLike,
+) -> tuple[
+ tuple[int, int],
+ np.ndarray,
+ dict[int, np.ndarray],
+ dict[int, tuple[np.ndarray, np.ndarray]],
+]:
+ """Validate arrays and build motion-specific sufficient statistics.
+
+ Returns
+ -------
+ shape : tuple[int, int]
+ (n_frames, n_sources).
+ valid : np.ndarray
+ Boolean per-frame mask of usable frames: finite residual and a motion index present in
+ `designs`.
+ groups : dict[int, np.ndarray]
+ Valid frame indices for each motion index that has at least one valid frame.
+ normal : dict[int, tuple[np.ndarray, np.ndarray]]
+ Per-motion (gram, rhs) normal-equation terms, X.T @ X and X.T @ residual
+ on that motion's valid frames.
+
+ Raises
+ ------
+ ValueError
+ If the array shapes are inconsistent, `designs` is empty or contains
+ nonfinite or mismatched profiles, or no observed frames and sources
+ remain.
+ """
residual = np.asarray(residual)
motion_indices = np.asarray(motion_indices)
valid = np.asarray(valid, dtype=bool).copy()
@@ -116,9 +181,7 @@ def _prepare_transient_system(residual, designs, motion_indices, valid):
raise ValueError("residual must have shape (superpixels, frames)")
n_sp, n_frames = residual.shape
if valid.shape != (n_frames,) or motion_indices.shape != (n_frames,):
- raise ValueError(
- "motion_indices and valid must have one entry per frame"
- )
+ raise ValueError("motion_indices and valid must have one entry per frame")
if not designs:
raise ValueError("Transient fitting requires projected profiles")
arrays = {m: np.asarray(x) for m, x in designs.items()}
@@ -128,15 +191,11 @@ def _prepare_transient_system(residual, designs, motion_indices, valid):
n_sources = first.shape[1]
for x in arrays.values():
if x.shape != (n_sp, n_sources) or not np.all(np.isfinite(x)):
- raise ValueError(
- "Projected profiles must be finite with matching shapes"
- )
+ raise ValueError("Projected profiles must be finite with matching shapes")
valid &= np.all(np.isfinite(residual), axis=0)
valid &= np.isin(motion_indices, list(arrays))
if not np.any(valid) or n_sources == 0:
- raise ValueError(
- "Transient fitting requires observed frames and sources"
- )
+ raise ValueError("Transient fitting requires observed frames and sources")
groups, normal = {}, {}
for motion, x in arrays.items():
ix = np.flatnonzero(valid & (motion_indices == motion))
@@ -151,25 +210,38 @@ def _prepare_transient_system(residual, designs, motion_indices, valid):
def fit_transient_traces(
- residual,
- designs,
- motion_indices,
- valid,
- analyze_hz,
+ residual: npt.ArrayLike,
+ designs: dict[int, np.ndarray],
+ motion_indices: npt.ArrayLike,
+ valid: npt.ArrayLike,
+ analyze_hz: float,
*,
- options=None,
- kernel=None,
-):
+ options: TransientOptions | None = None,
+ kernel: npt.ArrayLike | None = None,
+) -> TransientResult:
"""Fit one trial using fixed motion-specific (superpixel, source) designs.
Residual is (superpixels, frames). The complete nominal output grid must
be retained, in chronological order: never compress out gaps or group
disjoint motion frames before convolution. Nonfinite observations reject
- the entire frame, as in QR. ``valid`` also excludes unmatched motion/z.
+ the entire frame, as in QR. valid also excludes unmatched motion/z.
Public dF is NaN there, while model_trace contains latent gap predictions.
Low-level nonconvergence returns diagnostics and warns. Production callers
- must check ``metadata['converged']`` before saving a result.
+ must check metadata['converged'] before saving a result.
+
+ Returns
+ -------
+ TransientResult
+ Public dF trace (NaN on invalid frames), fit metadata and convergence diagnostics,
+ non-negative events, initial state and the latent model trace.
+
+ Raises
+ ------
+ TypeError
+ If `options` is neither `TransientOptions` nor None.
+ ValueError
+ If the inputs are invalid or no profile has observable support.
"""
options = TransientOptions() if options is None else options
if not isinstance(options, TransientOptions):
@@ -184,9 +256,7 @@ def fit_transient_traces(
event_rhs = op.adjoint(rhs_trace)
beta_scale = float(max(0.0, np.max(event_rhs[1:], initial=0.0)))
penalty = float(
- options.beta
- if options.beta is not None
- else options.beta_fraction * beta_scale
+ options.beta if options.beta is not None else options.beta_fraction * beta_scale
)
diagonals = np.concatenate([np.diag(g) for g, _ in normal.values()])
positive = diagonals[diagonals > 0]
@@ -196,8 +266,16 @@ def fit_transient_traces(
amplitude_scale = max(float(np.max(np.abs(rhs_trace))) / gram_scale, 1e-12)
objective_scale = gram_scale * amplitude_scale**2
- def objective(flat, event_penalty=penalty):
- """Evaluate the scaled objective and its analytic event gradient."""
+ def objective(flat: np.ndarray, event_penalty: float = penalty) -> tuple[float, np.ndarray]:
+ """Evaluate the scaled objective and its analytic event gradient.
+
+ Returns
+ -------
+ value : float
+ Scaled objective value.
+ gradient : np.ndarray
+ Flattened gradient of the scaled objective with respect to `flat`.
+ """
coefficients = flat.reshape(shape) * amplitude_scale
trace = op.forward(coefficients)
value, trace_gradient = _temporal_quadratic(normal, groups, trace)
@@ -236,15 +314,21 @@ def objective(flat, event_penalty=penalty):
"event_threshold": float(options.event_threshold),
}
if options.debias and result.success:
- active = (
- result.x.reshape(shape) * amplitude_scale > options.event_threshold
- )
+ active = result.x.reshape(shape) * amplitude_scale > options.event_threshold
active[0] = True
free = np.flatnonzero(active.ravel())
debias_info["retained_events"] = int(active[1:].sum())
- def restricted_objective(reduced):
- """Refit selected events only; the initial state remains free."""
+ def restricted_objective(reduced: np.ndarray) -> tuple[float, np.ndarray]:
+ """Refit selected events only; the initial state remains free.
+
+ Returns
+ -------
+ value : float
+ Scaled objective with no event penalty.
+ gradient : np.ndarray
+ Gradient restricted to the free (selected) coefficients.
+ """
full = np.zeros(np.prod(shape))
full[free] = reduced
value, gradient = objective(full, event_penalty=0.0)
@@ -278,9 +362,7 @@ def restricted_objective(reduced):
initial = events[0].copy()
events[0] = 0
converged = bool(
- result.success
- and np.isfinite(result.fun)
- and np.all(np.isfinite(model_trace))
+ result.success and np.isfinite(result.fun) and np.all(np.isfinite(model_trace))
)
if not converged:
warnings.warn(
@@ -294,30 +376,17 @@ def restricted_objective(reduced):
"method": "transient",
"tau_s": options.tau_s,
"beta": penalty,
- "beta_fraction": (
- options.beta_fraction if options.beta is None else None
- ),
+ "beta_fraction": (options.beta_fraction if options.beta is None else None),
"beta_scale": beta_scale,
"converged": converged,
"iterations": int(result.nit),
"message": str(result.message),
- "kernel": (
- "exponential"
- if kernel is None
- else np.asarray(kernel).tolist()
- ),
- "sampling_model": (
- "nominal output grid; acquisition averaging not modeled "
- "exactly"
- ),
+ "kernel": ("exponential" if kernel is None else np.asarray(kernel).tolist()),
+ "sampling_model": ("nominal output grid; acquisition averaging not modeled exactly"),
"selection": selection,
"debias": debias_info,
- "final_event_penalty": (
- 0.0 if debias_info["performed"] else penalty
- ),
- "objective_without_data_constant": float(
- result.fun * objective_scale
- ),
+ "final_event_penalty": (0.0 if debias_info["performed"] else penalty),
+ "objective_without_data_constant": float(result.fun * objective_scale),
},
events,
initial,
diff --git a/src/giant_python/extraction/band/trial_data.py b/src/giant_python/extraction/band/trial_data.py
index 3fa0c639..7b589cea 100644
--- a/src/giant_python/extraction/band/trial_data.py
+++ b/src/giant_python/extraction/band/trial_data.py
@@ -1,6 +1,6 @@
"""Read low-resolution superpixel activity for band-scan trials.
-Ported from ``extractSLAP2IntegrationSources.py`` (``get_trial_data`` ref
+Ported from extractSLAP2IntegrationSources.py (get_trial_data ref
715-842 and the per-trial low-res caching block ref 1851-1892). Vendor file
construction belongs to shared SLAP2 IO; alignment inputs normalize motion
at the band boundary. The original reader lifetime and accumulation order are
@@ -11,11 +11,10 @@
from __future__ import annotations
import os
-from typing import Optional
import numpy as np
-from ...io.slap2 import open_slap2_file
+from ...io.slap2 import Slap2Reader, open_slap2_file
from .inputs import load_alignment_data_h5
__all__ = [
@@ -28,9 +27,7 @@
]
-def compute_ds_frames(
- first_line: float, last_line: float, dt: float
-) -> np.ndarray:
+def compute_ds_frames(first_line: float, last_line: float, dt: float) -> np.ndarray:
"""Return the downsampled-frame line grid for one trial.
Parameters
@@ -38,20 +35,30 @@ def compute_ds_frames(
first_line, last_line : float
First/last acquisition line (1-based, inclusive).
dt : float
- Downsample step, in lines (``1 / samp_freq / line_period_s``).
+ Downsample step, in lines (1 / samp_freq / line_period_s).
Returns
-------
ndarray
- ``ceil`` of the line positions of each downsampled frame.
+ ceil of the line positions of each downsampled frame.
"""
return np.ceil(np.arange(first_line, last_line + 1, dt))
def _build_time_windows(
ds_frames: np.ndarray, dt: float, lines_per_cycle: int, num_cycles: int
-):
- """Return per-frame time windows and their line/cycle index arrays."""
+) -> tuple[list[np.ndarray], list[np.ndarray], list[np.ndarray]]:
+ """Return per-frame time windows and their line/cycle index arrays.
+
+ Returns
+ -------
+ time_windows : list[np.ndarray]
+ The acquisition lines read for each downsampled frame.
+ line_indices : list[np.ndarray]
+ The within-cycle line index of each line in each window.
+ cycle_indices : list[np.ndarray]
+ The cycle index of each line in each window.
+ """
dt_read = max(3 * dt, lines_per_cycle)
max_line = num_cycles * lines_per_cycle
time_windows = [
@@ -62,24 +69,31 @@ def _build_time_windows(
for f in ds_frames
]
line_indices = [(tw - 1) % lines_per_cycle + 1 for tw in time_windows]
- cycle_indices = [
- np.floor((tw - 1) / lines_per_cycle) + 1 for tw in time_windows
- ]
+ cycle_indices = [np.floor((tw - 1) / lines_per_cycle) + 1 for tw in time_windows]
return time_windows, line_indices, cycle_indices
-def _build_line_cycle_cache(line_indices: list, cycle_indices: list):
- """Return unique (line, cycle) arrays and their ``(line, cycle)`` map."""
+def _build_line_cycle_cache(
+ line_indices: list, cycle_indices: list
+) -> tuple[np.ndarray, np.ndarray, dict[tuple[int, int], int]]:
+ """Return unique (line, cycle) arrays and their (line, cycle) map.
+
+ Returns
+ -------
+ all_lines : np.ndarray
+ Line index of each unique (line, cycle) pair.
+ all_cycles : np.ndarray
+ Cycle index of each unique (line, cycle) pair.
+ mapping : dict[tuple[int, int], int]
+ Position of each (line, cycle) pair in all_lines and all_cycles.
+ """
pairs = set()
for lines, cycles in zip(line_indices, cycle_indices):
for li, ci in zip(lines, cycles):
pairs.add((int(li), int(ci)))
all_lines = np.array([p[0] for p in pairs])
all_cycles = np.array([p[1] for p in pairs])
- mapping = {
- (int(li), int(ci)): i
- for i, (li, ci) in enumerate(zip(all_lines, all_cycles))
- }
+ mapping = {(int(li), int(ci)): i for i, (li, ci) in enumerate(zip(all_lines, all_cycles))}
return all_lines, all_cycles, mapping
@@ -92,18 +106,14 @@ def _accumulate_line(
weight: float,
ds_ix: int,
) -> None:
- """Accumulate one line's weighted superpixel data into ``acc`` in place."""
+ """Accumulate one line's weighted superpixel data into acc in place."""
lookup_values = positions * 100 + z_idx
matching_mask = np.isin(super_pixel_ids, lookup_values)
matching_indices = np.where(matching_mask)[0]
if len(matching_indices) == 0:
return
- value_to_pos = dict(
- zip(lookup_values.astype(np.uint32), range(len(lookup_values)))
- )
- matched = [
- value_to_pos[int(super_pixel_ids[idx])] for idx in matching_indices
- ]
+ value_to_pos = dict(zip(lookup_values.astype(np.uint32), range(len(lookup_values))))
+ matched = [value_to_pos[int(super_pixel_ids[idx])] for idx in matching_indices]
acc["data"][matching_indices, ds_ix] += line_data[matched, 0] * weight
acc["data_count"][matching_indices, ds_ix] += weight
if acc["data2"] is not None:
@@ -112,7 +122,7 @@ def _accumulate_line(
def accumulate_superpixel_data(
- data_file,
+ data_file: Slap2Reader,
ds_frames: np.ndarray,
dt: float,
super_pixel_ids: np.ndarray,
@@ -121,32 +131,32 @@ def accumulate_superpixel_data(
) -> dict:
"""Accumulate weighted per-superpixel activity over the DS-frame grid.
- Port of the core loop of ``get_trial_data``: for each downsampled frame,
+ Port of the core loop of get_trial_data: for each downsampled frame,
weight nearby acquisition lines by ``exp(-|dframe|/dt)`` and scatter their
- superpixel line data into the ``(n_superpixels, n_ds_frames)`` accumulator.
+ superpixel line data into the (n_superpixels, n_ds_frames) accumulator.
Parameters
----------
data_file : object
- SLAP2 data-file-like object exposing ``header['linesPerCycle']``,
- ``numCycles``, ``getLineData``, ``lineDataNumElements``,
- ``lineSuperPixelIDs``, and ``lineFastZIdxs``.
+ SLAP2 data-file-like object exposing header['linesPerCycle'],
+ numCycles, getLineData, lineDataNumElements,
+ lineSuperPixelIDs, and lineFastZIdxs.
ds_frames : ndarray
Downsampled-frame line grid from :func:`compute_ds_frames`.
dt : float
Downsample step, in lines.
super_pixel_ids : ndarray
- Superpixel id lookup for this DMD, shape ``(n_superpixels, 1)``.
+ Superpixel id lookup for this DMD, shape (n_superpixels, 1).
num_channels : int
Number of acquisition channels.
all_channels : bool
- Read all channels (``getLineData(..., None)``) vs channel 1 only.
+ Read all channels (getLineData(..., None)) vs channel 1 only.
Returns
-------
dict
- ``{"data", "data_count", "data2", "data_count2"}``. The second-channel
- entries are ``None`` unless ``all_channels`` and ``num_channels >= 2``.
+ {"data", "data_count", "data2", "data_count2"}. The second-channel
+ entries are None unless all_channels and num_channels >= 2.
"""
lines_per_cycle = data_file.header["linesPerCycle"]
n_ds = len(ds_frames)
@@ -157,22 +167,14 @@ def accumulate_superpixel_data(
time_windows, line_indices, cycle_indices = _build_time_windows(
ds_frames, dt, lines_per_cycle, data_file.numCycles
)
- all_lines, all_cycles, mapping = _build_line_cycle_cache(
- line_indices, cycle_indices
- )
- all_line_data = data_file.getLineData(
- all_lines, all_cycles, 1 if not all_channels else None
- )
+ all_lines, all_cycles, mapping = _build_line_cycle_cache(line_indices, cycle_indices)
+ all_line_data = data_file.getLineData(all_lines, all_cycles, 1 if not all_channels else None)
acc = {
"data": np.zeros((num_sp, n_ds), dtype=np.float32),
"data_count": np.zeros((num_sp, n_ds), dtype=np.float32),
- "data2": (
- np.zeros((num_sp, n_ds), dtype=np.float32) if read_second else None
- ),
- "data_count2": (
- np.zeros((num_sp, n_ds), dtype=np.float32) if read_second else None
- ),
+ "data2": (np.zeros((num_sp, n_ds), dtype=np.float32) if read_second else None),
+ "data_count2": (np.zeros((num_sp, n_ds), dtype=np.float32) if read_second else None),
}
for ds_ix in range(n_ds):
@@ -206,23 +208,23 @@ def read_band_trial_data(
trial_table: dict,
num_channels: int,
all_channels: bool = True,
-) -> Optional[dict]:
+) -> dict | None:
"""Read one band trial's low-res superpixel activity.
Opens the trial's SLAP2 file, builds the downsampled-frame grid,
accumulates weighted superpixel activity, and loads the matching alignment
data. Counts are returned unnormalized (the caller forms
- ``data / data_count``); activity is divided by 100 to undo the acquisition
+ data / data_count); activity is divided by 100 to undo the acquisition
scaling.
Parameters
----------
trial_ix : int
- Trial index into ``trial_table`` columns.
+ Trial index into trial_table columns.
keep_trial : bool
- When False, the trial is skipped and ``None`` is returned.
+ When False, the trial is skipped and None is returned.
dmd_ix : int
- 0-based DMD index into ``trial_table`` rows.
+ 0-based DMD index into trial_table rows.
samp_freq : float
Analysis/alignment sample rate, in Hz.
super_pixel_ids : ndarray
@@ -230,8 +232,8 @@ def read_band_trial_data(
datadr : str
Raw-data directory holding the SLAP2 files.
trial_table : dict
- Normalized trial table (``filename``, ``first_line``, ``last_line``,
- ``fn_adata``).
+ Normalized trial table (filename, first_line, last_line,
+ fn_adata).
num_channels : int
Number of acquisition channels.
all_channels : bool
@@ -240,8 +242,8 @@ def read_band_trial_data(
Returns
-------
dict or None
- ``{"data", "data_count", "alignment", "ds_frames", "data2",
- "data_count2"}`` for kept trials, else ``None``.
+ {"data", "data_count", "alignment", "ds_frames", "data2",
+ "data_count2"} for kept trials, else None.
"""
if not keep_trial:
return None
@@ -257,9 +259,7 @@ def read_band_trial_data(
acc = accumulate_superpixel_data(
data_file, ds_frames, dt, super_pixel_ids, num_channels, all_channels
)
- alignment = load_alignment_data_h5(
- trial_table["fn_adata"][dmd_ix, trial_ix]
- )
+ alignment = load_alignment_data_h5(trial_table["fn_adata"][dmd_ix, trial_ix])
data2 = acc["data2"]
return {
@@ -276,63 +276,51 @@ def assemble_lowres_data(results: list, num_channels: int) -> dict:
"""Concatenate per-trial reader results into low-res arrays.
Port of the concatenation block that stitches per-trial outputs into the
- per-DMD low-res dataset. ``None`` results (skipped trials) are dropped.
+ per-DMD low-res dataset. None results (skipped trials) are dropped.
Parameters
----------
results : list
- Per-trial dicts from :func:`read_band_trial_data` (or ``None``).
+ Per-trial dicts from :func:`read_band_trial_data` (or None).
num_channels : int
Number of acquisition channels (>= 2 adds second-channel arrays).
Returns
-------
dict
- ``lowResData``, ``lowResDataCt``, ``lowResMotionR/C/Z``,
- ``lowResTrialID`` (and ``lowResData2``/``lowResDataCt2`` when
- ``num_channels >= 2``).
+ lowResData, lowResDataCt, lowResMotionR/C/Z,
+ lowResTrialID (and lowResData2/lowResDataCt2 when
+ num_channels >= 2).
"""
kept = [(i, r) for i, r in enumerate(results) if r is not None]
arrays = {
"lowResData": np.concatenate([r["data"] for _, r in kept], axis=1),
- "lowResDataCt": np.concatenate(
- [r["data_count"] for _, r in kept], axis=1
- ),
- "lowResMotionR": np.concatenate(
- [r["alignment"]["motionDSr"] for _, r in kept], axis=0
- ),
- "lowResMotionC": np.concatenate(
- [r["alignment"]["motionDSc"] for _, r in kept], axis=0
- ),
- "lowResMotionZ": np.concatenate(
- [r["alignment"]["motionDSz"] for _, r in kept], axis=0
- ),
+ "lowResDataCt": np.concatenate([r["data_count"] for _, r in kept], axis=1),
+ "lowResMotionR": np.concatenate([r["alignment"]["motionDSr"] for _, r in kept], axis=0),
+ "lowResMotionC": np.concatenate([r["alignment"]["motionDSc"] for _, r in kept], axis=0),
+ "lowResMotionZ": np.concatenate([r["alignment"]["motionDSz"] for _, r in kept], axis=0),
"lowResTrialID": np.concatenate(
[np.ones_like(r["ds_frames"]) * i for i, r in kept], axis=0
),
}
if num_channels >= 2:
- arrays["lowResData2"] = np.concatenate(
- [r["data2"] for _, r in kept], axis=1
- )
- arrays["lowResDataCt2"] = np.concatenate(
- [r["data_count2"] for _, r in kept], axis=1
- )
+ arrays["lowResData2"] = np.concatenate([r["data2"] for _, r in kept], axis=1)
+ arrays["lowResDataCt2"] = np.concatenate([r["data_count2"] for _, r in kept], axis=1)
return arrays
def save_lowres_data(path: str, arrays: dict) -> None:
- """Save assembled low-res arrays to an ``.npz`` cache."""
+ """Save assembled low-res arrays to an .npz cache."""
np.savez(path, **arrays)
def load_lowres_data(path: str, num_channels: int) -> dict:
- """Load an ``.npz`` low-res cache into a dict of arrays.
+ """Load an .npz low-res cache into a dict of arrays.
Parameters
----------
path : str
- Path to the ``lowres_data_DMD{N}.npz`` cache.
+ Path to the lowres_data_DMD{N}.npz cache.
num_channels : int
Number of acquisition channels (>= 2 also loads the second channel).
diff --git a/src/giant_python/extraction/band/types.py b/src/giant_python/extraction/band/types.py
index 0fd5f07a..35137488 100644
--- a/src/giant_python/extraction/band/types.py
+++ b/src/giant_python/extraction/band/types.py
@@ -14,10 +14,10 @@ class TrialTraceResult(NamedTuple):
Reference offsets and online shifts are (row, column, z) arrays, each
with one value per frame. Only output assembly negates reference offsets
into saved MATLAB displacement. Skipped trials have zero frames.
- ``d_f`` is the LS result in production; ``d_f_denoised`` and ``events``
- contain separate convolution outputs. ``f_residual`` is the source
- backprojection of ``data - background - x @ d_f``, added with ``f0_ls`` to
- ``d_f`` before the final F0 estimate. Optional defaults permit legacy
+ d_f is the LS result in production; d_f_denoised and events
+ contain separate convolution outputs. f_residual is the source
+ backprojection of data - background - x @ d_f, added with f0_ls to
+ d_f before the final F0 estimate. Optional defaults permit legacy
eight-argument construction, but the record now has eleven fields.
"""
diff --git a/src/giant_python/extraction/band/workflow.py b/src/giant_python/extraction/band/workflow.py
index 1c0f8f03..6ca6317f 100644
--- a/src/giant_python/extraction/band/workflow.py
+++ b/src/giant_python/extraction/band/workflow.py
@@ -8,9 +8,9 @@
from __future__ import annotations
from pathlib import Path
-from typing import Optional, Union
import numpy as np
+from torch import Tensor
from ...io.experiment_summary import write_summary
from ...io.hdf5 import to_serializable
@@ -28,10 +28,9 @@
from ...numerics.peaks import get_act_im_peaks
from ...parallel import map_trials
from ...progress import log, progress
-from . import activity
+from . import activity, inputs, motion_binning, operators
from . import background as bg
from . import geometry as geo
-from . import inputs, motion_binning, operators
from . import summary_images as si
from . import trial_data as td
from .annotation import (
@@ -47,7 +46,7 @@
assemble_path_summary,
)
from .traces import get_high_res_traces
-from .types import ResolvedAcquisition
+from .types import ResolvedAcquisition, TrialTraceResult
def _resolve_session_user_rois(
@@ -55,8 +54,14 @@ def _resolve_session_user_rois(
trial_table: dict,
lookup: dict,
annotations: AnnotationOptions,
-) -> Optional[dict]:
- """Load session annotations or invoke the configured drawing fallback."""
+) -> dict | None:
+ """Load session annotations or invoke the configured drawing fallback.
+
+ Returns
+ -------
+ dict or None
+ The session's user ROIs, or None when annotations are disabled.
+ """
if not annotations.enabled:
return None
user_roi_geo, ref_files = build_user_roi_geometry(trial_table, lookup)
@@ -70,7 +75,7 @@ def _resolve_session_user_rois(
def extract_band_sources(
- input: Union[str, Path, TrialTable],
+ input: str | Path | TrialTable,
params: BandParamsInput = None,
*,
execution: ExecutionInput = None,
@@ -82,6 +87,18 @@ def extract_band_sources(
conventional filename. Channel inference is local; caller scientific and
policy objects remain unchanged. Results are persisted under the table's
savedr/source_extraction directory and returned with every path intact.
+
+ Returns
+ -------
+ ExperimentSummary
+ The extraction output, with one entry in paths per DMD path and the serialized
+ parameters in params.
+
+ Raises
+ ------
+ ValueError
+ If the number of channels cannot be determined from the alignment data (for example,
+ when no trials are kept).
"""
params, run, roi = resolve_band_options(params, execution, annotations)
log(f"Loading trial table {input}", run.verbose)
@@ -133,9 +150,7 @@ def extract_band_sources(
)
)
- params_serializable = to_serializable(
- _params_dict(params, acquisition, roi)
- )
+ params_serializable = to_serializable(_params_dict(params, acquisition, roi))
log(f"Writing {output_path}", run.verbose)
summary = ExperimentSummary(paths=paths, params=params_serializable)
write_summary(summary, output_path)
@@ -147,7 +162,13 @@ def _params_dict(
acquisition: ResolvedAcquisition,
annotations: AnnotationOptions,
) -> dict:
- """Historical persisted parameter names, with locally resolved metadata."""
+ """Historical persisted parameter names, with locally resolved metadata.
+
+ Returns
+ -------
+ dict
+ The parameters to persist under their historical names.
+ """
return {
"numChannels": acquisition.num_channels,
"analyzeHz": params.analyze_hz,
@@ -176,13 +197,19 @@ def _process_dmd(
params: BandSiloParams,
lookup: dict,
psf: dict,
- user_rois: Optional[dict] = None,
+ user_rois: dict | None = None,
*,
acquisition: ResolvedAcquisition,
execution: ExecutionOptions,
annotations: AnnotationOptions,
) -> PathResult:
- """Read, localize and extract one path without changing numerical order."""
+ """Read, localize and extract one path without changing numerical order.
+
+ Returns
+ -------
+ PathResult
+ The path's sources, images, trial trace results and geometry.
+ """
key = f"DMD{dmd_ix + 1}"
log(f"Processing {key}", execution.verbose)
soma_masks, soma_labels, soma_sps = _dmd_user_rois(user_rois, key)
@@ -195,9 +222,7 @@ def _process_dmd(
align_hz = acquisition.align_hz[key]
keep_trials = trial_table["keep_trials"]
- ref_stack, _, _ = inputs.load_reference_stack(
- datadr, trial_table["ref_stack"], dmd_ix
- )
+ ref_stack, _, _ = inputs.load_reference_stack(datadr, trial_table["ref_stack"], dmd_ix)
dmd_pixels_per_column = ref_stack.shape[2]
dmd_pixels_per_row = ref_stack.shape[3]
yx_shape = (dmd_pixels_per_column, dmd_pixels_per_row)
@@ -207,19 +232,21 @@ def _process_dmd(
num_super_pixels = all_sp_ids.shape[0]
n_pixels = num_fast_zs * dmd_pixels_per_column * dmd_pixels_per_row
- smi = geo.build_subsample_matrix_inds(
- all_sp_ids, lookup["sparseMaskInds"][key]
- )
+ smi = geo.build_subsample_matrix_inds(all_sp_ids, lookup["sparseMaskInds"][key])
psf2d = psf[key]
sparse_h_inds, sparse_h_vals = operators.build_sparse_h(
smi, psf2d, dmd_pixels_per_column, dmd_pixels_per_row
)
- ref_d, ref_c, ref_r = geo.ref_pixs_to_drc(
- smi[:, 0], dmd_pixels_per_column, dmd_pixels_per_row
- )
+ ref_d, ref_c, ref_r = geo.ref_pixs_to_drc(smi[:, 0], dmd_pixels_per_column, dmd_pixels_per_row)
- def _read(trial_ix):
- """Read one low-resolution trial in acquisition order."""
+ def _read(trial_ix: int) -> dict | None:
+ """Read one low-resolution trial in acquisition order.
+
+ Returns
+ -------
+ dict or None
+ The trial's low-resolution data.
+ """
return td.read_band_trial_data(
trial_ix,
bool(keep_trials[dmd_ix, trial_ix]),
@@ -242,11 +269,7 @@ def _read(trial_ix):
)
low_res_data_norm = low["lowResData"] / low["lowResDataCt"]
v_im = 1.0 / low["lowResDataCt"]
- low2 = (
- low["lowResData2"] / low["lowResDataCt2"]
- if num_channels >= 2
- else None
- )
+ low2 = low["lowResData2"] / low["lowResDataCt2"] if num_channels >= 2 else None
unique_motion, mot_inds = motion_binning.bin_motion(
low["lowResMotionR"], low["lowResMotionC"], low["lowResMotionZ"]
)
@@ -299,9 +322,7 @@ def _read(trial_ix):
params,
execution=execution,
)
- data_std, _, _ = bg.fit_noise_variance_model(
- low_res_data_norm, background, v_im, params.vif
- )
+ data_std, _, _ = bg.fit_noise_variance_model(low_res_data_norm, background, v_im, params.vif)
residual = bg.compute_residual(low_res_data_norm, background, data_std)
act_im, act_im_peaks, a, source_params, source_snr = _localize(
residual,
@@ -342,8 +363,14 @@ def _read(trial_ix):
event_threshold=params.trace_event_threshold,
)
- def _traces(trial_ix):
- """Extract high-res traces using this trial's background slice."""
+ def _traces(trial_ix: int) -> TrialTraceResult:
+ """Extract high-res traces using this trial's background slice.
+
+ Returns
+ -------
+ TrialTraceResult
+ The trial's extracted high-resolution traces.
+ """
return get_high_res_traces(
(
trial_ix,
@@ -393,12 +420,8 @@ def _traces(trial_ix):
dmd_pixels_per_column=dmd_pixels_per_column,
dmd_pixels_per_row=dmd_pixels_per_row,
num_channels=num_channels,
- denoise_window=int(
- np.ceil(params.denoise_window_s * params.analyze_hz)
- ),
- baseline_window=int(
- np.ceil(params.baseline_window_s * params.analyze_hz)
- ),
+ denoise_window=int(np.ceil(params.denoise_window_s * params.analyze_hz)),
+ baseline_window=int(np.ceil(params.baseline_window_s * params.analyze_hz)),
draw_user_rois=annotations.enabled,
soma_masks=soma_masks,
soma_labels=soma_labels,
@@ -407,22 +430,29 @@ def _traces(trial_ix):
def _estimate_background(
- low_res_data_norm,
- umyx,
- mot_inds_yx,
- sel_pix_idxs,
- ref_d,
- ref_r,
- ref_c,
- num_fast_zs,
- dmd_pixels_per_column,
- dmd_pixels_per_row,
- align_hz,
- params,
+ low_res_data_norm: np.ndarray,
+ umyx: np.ndarray,
+ mot_inds_yx: np.ndarray,
+ sel_pix_idxs: np.ndarray,
+ ref_d: np.ndarray,
+ ref_r: np.ndarray,
+ ref_c: np.ndarray,
+ num_fast_zs: int,
+ dmd_pixels_per_column: int,
+ dmd_pixels_per_row: int,
+ align_hz: float,
+ params: BandSiloParams,
*,
- execution=None,
-):
- """Compose interpolation and rolling baseline on the original grid."""
+ execution: ExecutionOptions | None = None,
+) -> np.ndarray:
+ """Compose interpolation and rolling baseline on the original grid.
+
+ Returns
+ -------
+ np.ndarray
+ The background estimate on the original grid, as assembled from the interpolated
+ rolling baseline.
+ """
execution = ExecutionOptions() if execution is None else execution
log("Estimating background", execution.verbose)
interp_data = np.full(
@@ -450,12 +480,8 @@ def _estimate_background(
mot_inds_yx,
method="cubic",
)
- baseline_window = bg.baseline_window_frames(
- align_hz, params.baseline_window_s
- )
- interp_background = bg.compute_rolling_baseline(
- interp_data, baseline_window
- )
+ baseline_window = bg.baseline_window_frames(align_hz, params.baseline_window_s)
+ interp_background = bg.compute_rolling_baseline(interp_data, baseline_window)
return bg.assemble_background(
interp_background,
umyx,
@@ -472,29 +498,43 @@ def _estimate_background(
def _localize(
- residual,
- umyx,
- mot_inds_yx,
- sel_pix_idxs,
- pixel_coords,
- n_pixels,
- ref_d,
- ref_r,
- ref_c,
- num_fast_zs,
- dmd_pixels_per_column,
- dmd_pixels_per_row,
- psf2d,
- num_super_pixels,
- sparse_h_inds,
- sparse_h_vals,
- align_hz,
- params,
+ residual: np.ndarray,
+ umyx: np.ndarray,
+ mot_inds_yx: np.ndarray,
+ sel_pix_idxs: np.ndarray,
+ pixel_coords: np.ndarray,
+ n_pixels: int,
+ ref_d: np.ndarray,
+ ref_r: np.ndarray,
+ ref_c: np.ndarray,
+ num_fast_zs: int,
+ dmd_pixels_per_column: int,
+ dmd_pixels_per_row: int,
+ psf2d: np.ndarray,
+ num_super_pixels: int,
+ sparse_h_inds: np.ndarray,
+ sparse_h_vals: np.ndarray,
+ align_hz: float,
+ params: BandSiloParams,
*,
- execution=None,
- exclusion_mask=None,
-):
- """Compose rho, activity and localization; preserve DoG and RNG order."""
+ execution: ExecutionOptions | None = None,
+ exclusion_mask: np.ndarray | None = None,
+) -> tuple[np.ndarray, np.ndarray, Tensor, Tensor, np.ndarray]:
+ """Compose rho, activity and localization; preserve DoG and RNG order.
+
+ Returns
+ -------
+ act_im : np.ndarray
+ The finalized activity image.
+ act_im_peaks : np.ndarray
+ The detected source seeds (peaks of the activity image).
+ a : Tensor
+ The fitted source footprints, (n_pixels, N).
+ source_params : Tensor
+ The fitted source parameters [z, y, x, sigma_y, sigma_x, tilt], (N, 6).
+ source_snr : np.ndarray
+ The signal-to-noise ratio of each source, (N,).
+ """
execution = ExecutionOptions() if execution is None else execution
log("Computing activity image and localizing sources", execution.verbose)
h_mots = operators.build_motion_h_matrices(
@@ -509,12 +549,8 @@ def _localize(
# determines its valid-column dilation/erosion mask, not the DoG widths.
dog_center_sd = 0.9
dog_surround_sd = 4.5
- center_kernel, center_kernel_ctr = operators.gaussian_kernel_2d(
- dog_center_sd
- )
- surround_kernel, surround_kernel_ctr = operators.gaussian_kernel_2d(
- dog_surround_sd
- )
+ center_kernel, center_kernel_ctr = operators.gaussian_kernel_2d(dog_center_sd)
+ surround_kernel, surround_kernel_ctr = operators.gaussian_kernel_2d(dog_surround_sd)
d_mats, d_mats_exp = [], []
for z in progress(
range(num_fast_zs),
@@ -524,15 +560,9 @@ def _localize(
_, sel_2d = geo.selected_pixels_2d_for_plane(
sel_pix_idxs, z, dmd_pixels_per_column, dmd_pixels_per_row
)
- d_mats.append(
- operators.build_convolution_matrix(
- sel_2d, center_kernel, center_kernel_ctr
- )
- )
+ d_mats.append(operators.build_convolution_matrix(sel_2d, center_kernel, center_kernel_ctr))
d_mats_exp.append(
- operators.build_convolution_matrix(
- sel_2d, surround_kernel, surround_kernel_ctr
- )
+ operators.build_convolution_matrix(sel_2d, surround_kernel, surround_kernel_ctr)
)
rho = activity.compute_rho(
residual,
diff --git a/src/giant_python/extraction/raster/__init__.py b/src/giant_python/extraction/raster/__init__.py
index c4509478..8b867184 100644
--- a/src/giant_python/extraction/raster/__init__.py
+++ b/src/giant_python/extraction/raster/__init__.py
@@ -1,3 +1,5 @@
-"""Multi-ROI (raster) SiLo localization: GIAnT-MATLAB's localizeSources_vIM
-and getActImPeaks, with optional detection changes (no DoG surround,
-bootstrap null per brightness, soft-threshold score)."""
+"""Multi-ROI (raster) SiLo localization.
+
+GIAnT-MATLAB's localizeSources_vIM and getActImPeaks, with optional detection
+changes (no DoG surround, bootstrap null per brightness, soft-threshold score).
+"""
diff --git a/src/giant_python/extraction/raster/alignment.py b/src/giant_python/extraction/raster/alignment.py
index b878fc28..0200785c 100644
--- a/src/giant_python/extraction/raster/alignment.py
+++ b/src/giant_python/extraction/raster/alignment.py
@@ -1,57 +1,58 @@
"""Across-trial alignment of one imaging path (SiLo's consensus frame).
-Port of the alignment part of GIAnT-MATLAB's ``SILo.m`` (main at 5a0673b)
-and its helpers ``makeConsensusTemplate``, ``dftregistration_clipped``
-(the whole-pixel branch SiLo uses), ``xcorr2_nans``, ``trialWarpCoords`` and
-``warpTrialImage`` / ``warpImageAffine``:
+Port of the alignment part of GIAnT-MATLAB's SILo.m (main at 5a0673b)
+and its helpers makeConsensusTemplate, dftregistration_clipped
+(the whole-pixel branch SiLo uses), xcorr2_nans, trialWarpCoords and
+warpTrialImage / warpImageAffine:
1. a consensus template from up to 20 trials' mean images: every pair is
registered, the trial that correlates best with the others is the
reference, and the trials that match it at least as well as the median
- are averaged around it on a canvas ``max_shift`` larger on every side;
+ are averaged around it on a canvas max_shift larger on every side;
2. each trial's mean image is registered to the template: a whole-pixel
estimate by FFT cross-correlation, refined by a normalized
- cross-correlation over ``+-max_shift`` pixels with a parabola fit;
+ cross-correlation over +-max_shift pixels with a parabola fit;
3. the shifts are the trials' maps from the consensus frame to their
registered images (:class:`TrialWarp`), which resample trial images into
the consensus frame (:func:`warp_trial_image`).
-The shifts can be refined groupwise (``interTrialAlignment``), as GIAnT-MATLAB
+The shifts can be refined groupwise (interTrialAlignment), as GIAnT-MATLAB
main does after the rigid fit:
-- ``'affine'`` (:func:`align_trials_affine`, port of
- ``alignTrialsAffine.m``): one affine map per trial;
-- ``'patchwise'`` (:func:`align_trials_patchwise`, port of
- ``alignTrialsPatchwise.m``, ``patchFieldMatrix.m``, ``patchFieldApply.m``):
+- 'affine' (:func:`align_trials_affine`, port of
+ alignTrialsAffine.m): one affine map per trial;
+- 'patchwise' (:func:`align_trials_patchwise`, port of
+ alignTrialsPatchwise.m, patchFieldMatrix.m, patchFieldApply.m):
a smooth displacement field per trial, set by its values at the centres of
patches of imaged pixels, on top of the field's plane (an affine map).
:class:`TrialWarp` holds any of the three maps; :meth:`TrialWarp.coords`
-(``trialWarpCoords.m``) and :meth:`TrialWarp.inverse`
-(``trialWarpInverse.m``) carry points between the consensus frame and a
+(trialWarpCoords.m) and :meth:`TrialWarp.inverse`
+(trialWarpInverse.m) carry points between the consensus frame and a
trial's registered image, and :func:`warp_trial_image`
-(``warpTrialImage.m``) resamples images.
+(warpTrialImage.m) resamples images.
-Images are ``(rows, cols)`` in MATLAB's orientation and coordinates are
-zero-based: a shift of ``(dr, dc)`` means that consensus pixel ``(r, c)`` is
-at ``(r + dr, c + dc)`` in the trial's registered image. Patch centres are
+Images are (rows, cols) in MATLAB's orientation and coordinates are
+zero-based: a shift of (dr, dc) means that consensus pixel (r, c) is
+at (r + dr, c + dc) in the trial's registered image. Patch centres are
zero-based too; displacements are the same in either base.
Against MATLAB: the k-means clustering that makes the patches
(:func:`make_patches`) draws from numpy's generator, not MATLAB's, so the
-patches differ; given MATLAB's patches (``patches=``) the fits follow
+patches differ; given MATLAB's patches (patches=) the fits follow
MATLAB's arithmetic, with numpy's least-squares and linear solvers.
"""
from __future__ import annotations
import warnings
+from collections.abc import Iterable, Iterator, Sequence
from contextlib import closing
from dataclasses import dataclass, field
import numpy as np
-import scipy.ndimage as ndimage
-import scipy.sparse as sparse
+import numpy.typing as npt
+from scipy import ndimage, sparse
from scipy.spatial import cKDTree
from ...parallel import (
@@ -66,16 +67,22 @@
_EPS = float(np.finfo(np.float64).eps)
-def matlab_round(x) -> np.ndarray:
- """MATLAB's ``round``: halves away from zero (numpy's go to even)."""
+def matlab_round(x: npt.ArrayLike) -> np.ndarray:
+ """Round as MATLAB's round: halves away from zero (numpy's go to even).
+
+ Returns
+ -------
+ np.ndarray
+ x rounded to whole numbers.
+ """
x = np.asarray(x, dtype=np.float64)
whole = np.trunc(x)
# x - whole is exact, unlike floor(|x| + 0.5) just below a half
return whole + np.sign(x) * (np.abs(x - whole) >= 0.5)
-def interp2_linear(im: np.ndarray, rows, cols) -> np.ndarray:
- """MATLAB ``interp2(im, cols, rows, 'linear')`` at zero-based points.
+def interp2_linear(im: np.ndarray, rows: npt.ArrayLike, cols: npt.ArrayLike) -> np.ndarray:
+ """Interpolate as MATLAB interp2(im, cols, rows, 'linear') at zero-based points.
Bilinear interpolation, NaN outside the image and wherever a pixel that
enters with a non-zero weight is NaN. As in MATLAB, a point exactly on a
@@ -92,7 +99,7 @@ def interp2_linear(im: np.ndarray, rows, cols) -> np.ndarray:
Returns
-------
ndarray
- The interpolated values, in the shape of ``rows``.
+ The interpolated values, in the shape of rows.
"""
im = np.asarray(im, dtype=np.float64)
rows = np.asarray(rows, dtype=np.float64)
@@ -122,8 +129,16 @@ def interp2_linear(im: np.ndarray, rows, cols) -> np.ndarray:
def _keys_weights(s: np.ndarray) -> tuple:
- """Weights of Keys' cubic convolution (a = -1/2) at offsets -1, 0, 1, 2
- from the grid point below a query, ``s`` its distance from it."""
+ """Return the weights of Keys' cubic convolution (a = -1/2).
+
+ The weights are at offsets -1, 0, 1, 2
+ from the grid point below a query, s its distance from it.
+
+ Returns
+ -------
+ tuple
+ The four weights, for offsets -1, 0, 1 and 2.
+ """
s2 = s * s
s3 = s2 * s
return (
@@ -135,11 +150,11 @@ def _keys_weights(s: np.ndarray) -> tuple:
class CubicInterpolant:
- """MATLAB's ``interp2(im, cols, rows, 'cubic')`` at zero-based points.
+ """MATLAB's interp2(im, cols, rows, 'cubic') at zero-based points.
Keys' cubic convolution on the pixel grid, with MATLAB's boundary
- condition (one row and column outside each edge, ``3 f(0) - 3 f(1) +
- f(2)``). NaN outside the image and wherever any of the 16 pixels around
+ condition (one row and column outside each edge, 3 f(0) - 3 f(1) +
+ f(2)). NaN outside the image and wherever any of the 16 pixels around
a point is NaN, also those with zero weight (as MATLAB; checked against
R2024b). The extended image is built once, for the many evaluations of
a Gauss-Newton fit.
@@ -151,13 +166,17 @@ class CubicInterpolant:
"""
def __init__(self, im: np.ndarray) -> None:
- """Extend the image by MATLAB's boundary rows and columns."""
+ """Extend the image by MATLAB's boundary rows and columns.
+
+ Raises
+ ------
+ ValueError
+ If the image is smaller than 3 x 3.
+ """
im = np.asarray(im, dtype=np.float64)
h, w = im.shape
if h < 3 or w < 3:
- raise ValueError(
- f"cubic interpolation needs 3 x 3, not {im.shape}"
- )
+ raise ValueError(f"cubic interpolation needs 3 x 3, not {im.shape}")
e = np.empty((h + 2, w))
e[1:-1] = im
e[0] = 3 * im[0] - 3 * im[1] + im[2]
@@ -170,8 +189,15 @@ def __init__(self, im: np.ndarray) -> None:
self._flat = ext.ravel()
self._w = w + 2
- def __call__(self, rows, cols) -> np.ndarray:
- """Values at zero-based ``rows``, ``cols`` (equal shapes)."""
+ def __call__(self, rows: npt.ArrayLike, cols: npt.ArrayLike) -> np.ndarray:
+ """Return the values at zero-based rows, cols (equal shapes).
+
+ Returns
+ -------
+ np.ndarray
+ The interpolated values, in the shape of rows; NaN where the
+ point is outside the image or a pixel around it is NaN.
+ """
h, w = self.shape
r = np.asarray(rows, dtype=np.float64)
c = np.asarray(cols, dtype=np.float64)
@@ -196,16 +222,30 @@ def __call__(self, rows, cols) -> np.ndarray:
return out
-def interp2_cubic(im: np.ndarray, rows, cols) -> np.ndarray:
- """MATLAB ``interp2(im, cols, rows, 'cubic')`` at zero-based points (see
- :class:`CubicInterpolant`)."""
+def interp2_cubic(im: np.ndarray, rows: npt.ArrayLike, cols: npt.ArrayLike) -> np.ndarray:
+ """Interpolate as MATLAB interp2(im, cols, rows, 'cubic') at zero-based points.
+
+ See :class:`CubicInterpolant`.
+
+ Returns
+ -------
+ np.ndarray
+ The interpolated values, in the shape of rows.
+ """
return CubicInterpolant(im)(rows, cols)
def _bilinear_bounds(
im: np.ndarray, rows: np.ndarray, cols: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
- """Per-point ``(min, max)`` of the 2 x 2 bilinear corner stencil."""
+ """Return the per-point (min, max) of the 2 x 2 bilinear corner stencil.
+
+ Returns
+ -------
+ lo, hi : np.ndarray
+ The smallest and largest corner value at each point (NaN where the
+ point is not finite).
+ """
h, w = im.shape
fin = np.isfinite(rows) & np.isfinite(cols)
r = np.clip(np.where(fin, rows, 0.0), 0.0, max(h - 1, 0))
@@ -214,20 +254,26 @@ def _bilinear_bounds(
c0 = np.floor(c).astype(np.intp)
r1 = np.minimum(r0 + 1, h - 1)
c1 = np.minimum(c0 + 1, w - 1)
- corners = np.stack(
- [im[r0, c0], im[r1, c0], im[r0, c1], im[r1, c1]], axis=0
- )
+ corners = np.stack([im[r0, c0], im[r1, c0], im[r0, c1], im[r1, c1]], axis=0)
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
lo, hi = np.nanmin(corners, axis=0), np.nanmax(corners, axis=0)
return np.where(fin, lo, np.nan), np.where(fin, hi, np.nan)
-def interp2_cubic_clamped(im: np.ndarray, rows, cols) -> np.ndarray:
- """Keys' bicubic interpolation with non-negativity preservation (clamped
- below at ``min(0, min_2x2)`` so non-negative images never ring negative
- while subpixel peaks above the 2 x 2 corners are reconstructed), falling
- back to :func:`interp2_linear` where cubic is NaN."""
+def interp2_cubic_clamped(im: np.ndarray, rows: npt.ArrayLike, cols: npt.ArrayLike) -> np.ndarray:
+ """Interpolate with Keys' bicubic interpolation, preserving non-negativity.
+
+ The result is clamped
+ below at min(0, min_2x2) so non-negative images never ring negative
+ while subpixel peaks above the 2 x 2 corners are reconstructed, falling
+ back to :func:`interp2_linear` where cubic is NaN.
+
+ Returns
+ -------
+ np.ndarray
+ The interpolated values, in the shape of the broadcast rows and cols.
+ """
im = np.asarray(im, dtype=np.float64)
r, c = np.broadcast_arrays(
np.asarray(rows, dtype=np.float64), np.asarray(cols, dtype=np.float64)
@@ -243,22 +289,45 @@ def interp2_cubic_clamped(im: np.ndarray, rows, cols) -> np.ndarray:
def matlab_gradient(im: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
- """MATLAB's ``[gc, gr] = gradient(im)`` as ``(gr, gc)``: central
- differences inside, one-sided at the edges, NaN carried."""
+ """Return MATLAB's [gc, gr] = gradient(im) as (gr, gc).
+
+ These are central
+ differences inside, one-sided at the edges, NaN carried.
+
+ Returns
+ -------
+ gr, gc : np.ndarray
+ The gradients along the rows and along the columns.
+ """
im = np.asarray(im, dtype=np.float64)
return np.gradient(im, axis=0), np.gradient(im, axis=1)
def _colmajor_nonzero(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
- """Rows and columns of a mask's pixels in MATLAB's ``find`` order
- (column by column)."""
+ """Return the rows and columns of a mask's pixels in MATLAB's find order.
+
+ That is column by column.
+
+ Returns
+ -------
+ rows, cols : np.ndarray
+ The rows and columns of the pixels.
+ """
cols, rows = np.nonzero(np.asarray(mask, dtype=bool).T)
return rows, cols
def _sqrt_nan(m: np.ndarray) -> np.ndarray:
- """``sqrt(max(M, 0))`` with NaN kept (roughly variance-stabilized for
- shot noise; unscanned pixels stay NaN, not sharp zero edges)."""
+ """Return sqrt(max(M, 0)) with NaN kept.
+
+ The result is roughly variance-stabilized for
+ shot noise; unscanned pixels stay NaN, not sharp zero edges.
+
+ Returns
+ -------
+ np.ndarray
+ The square root of m clipped at zero, NaN where m is NaN.
+ """
m = np.asarray(m, dtype=np.float64)
with np.errstate(invalid="ignore"):
s = np.sqrt(np.fmax(m, 0.0))
@@ -267,22 +336,32 @@ def _sqrt_nan(m: np.ndarray) -> np.ndarray:
def _first_nanmax(values: np.ndarray) -> int:
- """Index of MATLAB's ``max``: the first largest value, NaN ignored (the
- first element when all are NaN)."""
+ """Return the index of MATLAB's max: the first largest value, NaN ignored.
+
+ It is the
+ first element when all are NaN.
+
+ Returns
+ -------
+ int
+ The index of the first largest value.
+ """
if np.isnan(values).all():
return 0
return int(np.nanargmax(values))
def _parabola_offset(c: np.ndarray, rr: int, cc: int) -> tuple[float, float]:
- """xcorr2_nans' sub-pixel offset of the correlation maximum."""
+ """Return xcorr2_nans' sub-pixel offset of the correlation maximum.
+
+ Returns
+ -------
+ d_r, d_c : float
+ The offset along the rows and along the columns.
+ """
with np.errstate(divide="ignore", invalid="ignore"):
- ratio_r = np.fmin(
- 1e6, (c[rr, cc] - c[rr - 1, cc]) / (c[rr, cc] - c[rr + 1, cc])
- )
- ratio_c = np.fmin(
- 1e6, (c[rr, cc] - c[rr, cc - 1]) / (c[rr, cc] - c[rr, cc + 1])
- )
+ ratio_r = np.fmin(1e6, (c[rr, cc] - c[rr - 1, cc]) / (c[rr, cc] - c[rr + 1, cc]))
+ ratio_c = np.fmin(1e6, (c[rr, cc] - c[rr, cc - 1]) / (c[rr, cc] - c[rr, cc + 1]))
d_r = (1 - ratio_r) / (1 + ratio_r) / 2
d_c = (1 - ratio_c) / (1 + ratio_c) / 2
return float(d_r), float(d_c)
@@ -290,22 +369,24 @@ def _parabola_offset(c: np.ndarray, rr: int, cc: int) -> tuple[float, float]:
def _shifted_template_values(
template: np.ndarray, t_valid: np.ndarray, d: int
-):
- """The template at ``t_valid`` moved by every shift of ``[-d, d]^2``.
+) -> Iterator[tuple[int, int, np.ndarray]]:
+ """Generate the template at t_valid moved by every shift of [-d, d]^2.
- Yields ``(i, j, values)`` with the values in MATLAB's column-major order
- of ``template(circshift(tValid, -[dr dc]))``. While no shifted pixel
+ Yields (i, j, values) with the values in MATLAB's column-major order
+ of template(circshift(tValid, -[dr dc])). While no shifted pixel
leaves the image this is a lookup at shifted indices; otherwise the mask
is rolled as MATLAB does (pixels wrap around, and their order with them).
+
+ Yields
+ ------
+ tuple
+ (i, j, values): the shift's indices and the shifted template values.
"""
h, w = template.shape
cols, rows = np.nonzero(t_valid.T) # column-major order
shifts = range(-d, d + 1)
wraps = rows.size > 0 and (
- rows.min() - d < 0
- or rows.max() + d >= h
- or cols.min() - d < 0
- or cols.max() + d >= w
+ rows.min() - d < 0 or rows.max() + d >= h or cols.min() - d < 0 or cols.max() + d >= w
)
if not wraps:
flat = template.ravel()
@@ -321,14 +402,14 @@ def _shifted_template_values(
def xcorr2_nans(
- frame: np.ndarray, template: np.ndarray, shifts_center, d_shift: int
+ frame: np.ndarray, template: np.ndarray, shifts_center: npt.ArrayLike, d_shift: int
) -> tuple[np.ndarray, float]:
"""Local normalized cross-correlation of images with NaN.
- Port of ``xcorr2_nans.m``. The frame's pixels that are not NaN, and whose
+ Port of xcorr2_nans.m. The frame's pixels that are not NaN, and whose
template pixels are not NaN for any shift of the search, are correlated
- with the template at every whole shift within ``d_shift`` of
- ``shifts_center``; the maximum is refined by a parabola on each axis
+ with the template at every whole shift within d_shift of
+ shifts_center; the maximum is refined by a parabola on each axis
unless it lies on the edge of the search.
Parameters
@@ -336,15 +417,15 @@ def xcorr2_nans(
frame, template : ndarray of shape (rows, cols)
The image to align and the template (the same shape).
shifts_center : array_like of 2 int
- Centre of the search ``(rows, cols)``.
+ Centre of the search (rows, cols).
d_shift : int
Largest shift from the centre on each axis.
Returns
-------
motion : ndarray of shape (2,)
- The shift ``(rows, cols)``: frame pixel ``p`` matches template pixel
- ``p - motion``.
+ The shift (rows, cols): frame pixel p matches template pixel
+ p - motion.
r : float
The correlation at the best whole shift.
@@ -356,9 +437,7 @@ def xcorr2_nans(
frame = np.asarray(frame, dtype=np.float64)
template = np.asarray(template, dtype=np.float64)
if frame.shape != template.shape:
- raise ValueError(
- f"frame is {frame.shape}, the template {template.shape}"
- )
+ raise ValueError(f"frame is {frame.shape}, the template {template.shape}")
d = int(matlab_round(np.ravel(d_shift)[0]))
sc = np.asarray(shifts_center, dtype=np.float64).ravel().astype(int)
h, w = frame.shape
@@ -392,14 +471,14 @@ def xcorr2_nans(
def dftregistration_clipped(
- buf1ft: np.ndarray, buf2ft: np.ndarray, clip
+ buf1ft: np.ndarray, buf2ft: np.ndarray, clip: float | tuple[float, float]
) -> tuple[float, float, int, int]:
"""Whole-pixel registration by FFT cross-correlation, with a shift limit.
- Port of the ``usfac = 1`` branch of ``dftregistration_clipped.m`` (after
+ Port of the usfac = 1 branch of dftregistration_clipped.m (after
Guizar-Sicairos et al., Opt. Lett. 33, 156-158, 2008), the only one SiLo
uses. The cross-correlation is set to zero outside the window MATLAB
- keeps for ``clip`` (``fix(clip/2)`` pixels on either side of zero shift)
+ keeps for clip (fix(clip/2) pixels on either side of zero shift)
before its maximum is located.
Parameters
@@ -408,7 +487,7 @@ def dftregistration_clipped(
Fourier transforms of the reference and of the image to register
(zero frequency first).
clip : float or pair of float
- MATLAB's ``clip`` for rows and columns.
+ MATLAB's clip for rows and columns.
Returns
-------
@@ -447,9 +526,9 @@ def dftregistration_clipped(
def make_consensus_template(stack: np.ndarray, max_shift: int) -> np.ndarray:
- """A template that most of the given images agree with.
+ """Return a template that most of the given images agree with.
- Port of ``makeConsensusTemplate.m``. Every pair of images is registered
+ Port of makeConsensusTemplate.m. Every pair of images is registered
(:func:`xcorr2_nans`, twice: around zero, then around the rounded
result). The image with the highest median correlation to the others is
the reference; the images that correlate with it at least as well as
@@ -465,8 +544,8 @@ def make_consensus_template(stack: np.ndarray, max_shift: int) -> np.ndarray:
Returns
-------
ndarray of shape (rows + 2 * max_shift, cols + 2 * max_shift)
- The template; image pixel ``(r, c)`` of the reference is at
- ``(r + max_shift, c + max_shift)``.
+ The template; image pixel (r, c) of the reference is at
+ (r + max_shift, c + max_shift).
"""
y = np.asarray(stack, dtype=np.float64)
n, h, w = y.shape
@@ -492,9 +571,7 @@ def make_consensus_template(stack: np.ndarray, max_shift: int) -> np.ndarray:
total = np.zeros(template.shape)
count = np.zeros(template.shape)
for f in members:
- plane = interp2_linear(
- y[f], view_r - motion[0, f, ref], view_c - motion[1, f, ref]
- )
+ plane = interp2_linear(y[f], view_r - motion[0, f, ref], view_c - motion[1, f, ref])
ok = ~np.isnan(plane)
total[ok] += plane[ok]
count += ok
@@ -507,26 +584,26 @@ def make_consensus_template(stack: np.ndarray, max_shift: int) -> np.ndarray:
class TrialWarp:
"""Every trial's map from the consensus frame to its registered image.
- MATLAB's ``warp`` structure (``SILo.m``, ``trialWarpCoords.m``), with
+ MATLAB's warp structure (SILo.m, trialWarpCoords.m), with
zero-based coordinates.
Attributes
----------
affine : ndarray of shape (trials, 2, 3)
- ``[row_t, col_t] = affine[t] @ [row, col, 1]``; NaN for a trial that
- was not aligned. A rigid shift is ``[[1, 0, dr], [0, 1, dc]]``. For
+ [row_t, col_t] = affine[t] @ [row, col, 1]; NaN for a trial that
+ was not aligned. A rigid shift is [[1, 0, dr], [0, 1, dc]]. For
a patchwise field, the field's plane.
nodes : ndarray of shape (n_nodes, 2)
- Patch centres ``(row, col)`` of the patchwise field; empty for rigid
+ Patch centres (row, col) of the patchwise field; empty for rigid
and affine alignment.
sigma : float
SD of the patchwise field's Gaussian blend (NaN without one).
disp : ndarray of shape (trials, n_nodes, 2)
- Each trial's displacement ``(rows, cols)`` at the patch centres
- (MATLAB's ``warp.disp``, ``2 x nodes x trials``).
+ Each trial's displacement (rows, cols) at the patch centres
+ (MATLAB's warp.disp, 2 x nodes x trials).
patch : ndarray of int, shape (rows, cols), or None
The patch of each consensus pixel the field was fitted on (1 to
- ``n_nodes``, 0 outside; MATLAB's ``warp.patch``). Not needed to
+ n_nodes, 0 outside; MATLAB's warp.patch). Not needed to
apply the field.
"""
@@ -538,14 +615,10 @@ class TrialWarp:
def __post_init__(self) -> None:
"""Normalize the arrays' types and shapes."""
- self.affine = np.asarray(self.affine, dtype=np.float64).reshape(
- -1, 2, 3
- )
+ self.affine = np.asarray(self.affine, dtype=np.float64).reshape(-1, 2, 3)
self.nodes = np.asarray(self.nodes, dtype=np.float64).reshape(-1, 2)
if self.disp is None:
- self.disp = np.zeros(
- (self.affine.shape[0], self.nodes.shape[0], 2)
- )
+ self.disp = np.zeros((self.affine.shape[0], self.nodes.shape[0], 2))
self.disp = np.asarray(self.disp, dtype=np.float64).reshape(
self.affine.shape[0], self.nodes.shape[0], 2
)
@@ -554,9 +627,17 @@ def __post_init__(self) -> None:
self.patch = np.asarray(self.patch, dtype=np.int32)
@classmethod
- def from_shifts(cls, shifts: np.ndarray) -> "TrialWarp":
- """The rigid warp of per-trial shifts ``(trials, 2)`` (NaN rows for
- trials that were not aligned)."""
+ def from_shifts(cls, shifts: np.ndarray) -> TrialWarp:
+ """Return the rigid warp of per-trial shifts (trials, 2).
+
+ NaN rows are for
+ trials that were not aligned.
+
+ Returns
+ -------
+ TrialWarp
+ The warp whose maps are the rigid shifts.
+ """
shifts = np.asarray(shifts, dtype=np.float64).reshape(-1, 2)
affine = np.full((shifts.shape[0], 2, 3), np.nan)
ok = ~np.isnan(shifts[:, 0])
@@ -572,22 +653,27 @@ def from_matlab(
sigma: float = float("nan"),
disp: np.ndarray | None = None,
patch: np.ndarray | None = None,
- ) -> "TrialWarp":
- """From MATLAB's ``warp`` (one-based coordinates).
+ ) -> TrialWarp:
+ """Build a warp from MATLAB's warp (one-based coordinates).
Parameters
----------
affine : ndarray of shape (trials, 2, 3)
- ``warp.affine`` with the trials first
- (``permute(warp.affine, [3 1 2])``).
+ warp.affine with the trials first
+ (permute(warp.affine, [3 1 2])).
nodes : ndarray of shape (n_nodes, 2), optional
- ``warp.nodes``.
+ warp.nodes.
sigma : float
- ``warp.sigma``.
+ warp.sigma.
disp : ndarray of shape (trials, n_nodes, 2), optional
- ``warp.disp`` as ``permute(warp.disp, [3 2 1])``.
+ warp.disp as permute(warp.disp, [3 2 1]).
patch : ndarray of shape (rows, cols), optional
- ``warp.patch``.
+ warp.patch.
+
+ Returns
+ -------
+ TrialWarp
+ The warp in zero-based coordinates.
"""
a = np.array(affine, dtype=np.float64).reshape(-1, 2, 3)
a[:, :, 2] += a[:, :, 0] + a[:, :, 1] - 1
@@ -595,7 +681,13 @@ def from_matlab(
return cls(a, n, sigma, disp, patch)
def to_matlab(self) -> np.ndarray:
- """MATLAB's ``warp.affine`` as ``(trials, 2, 3)`` (one-based)."""
+ """Return MATLAB's warp.affine as (trials, 2, 3) (one-based).
+
+ Returns
+ -------
+ np.ndarray
+ The affine maps in MATLAB's one-based coordinates.
+ """
a = self.affine.copy()
a[:, :, 2] -= a[:, :, 0] + a[:, :, 1] - 1
return a
@@ -616,23 +708,44 @@ def aligned(self) -> np.ndarray:
return ~np.isnan(self.affine[:, 0, 2])
def is_shift(self, trial: int) -> bool:
- """Whether the trial's map is a shift (no affine or patchwise
- part), which extraction can add to the trial's motion."""
+ """Return whether the trial's map is a shift.
+
+ A shift has no affine or patchwise
+ part, which extraction can add to the trial's motion.
+
+ Returns
+ -------
+ bool
+ True if the trial's map is a shift.
+ """
return self.nodes.shape[0] == 0 and bool(
np.array_equal(self.affine[trial, :, :2], np.eye(2))
)
def shift(self, trial: int) -> np.ndarray:
- """The trial's shift ``(rows, cols)``; only for :meth:`is_shift`."""
+ """Return the trial's shift (rows, cols); only for :meth:`is_shift`.
+
+ Returns
+ -------
+ np.ndarray
+ The trial's shift (rows, cols).
+
+ Raises
+ ------
+ ValueError
+ If the trial's map is not a shift.
+ """
if not self.is_shift(trial):
raise ValueError(f"the map of trial {trial} is not a shift")
return self.affine[trial, :, 2].copy()
- def coords(self, trial: int, rows, cols) -> tuple[np.ndarray, np.ndarray]:
- """Positions in the trial's registered image of consensus points.
+ def coords(
+ self, trial: int, rows: npt.ArrayLike, cols: npt.ArrayLike
+ ) -> tuple[np.ndarray, np.ndarray]:
+ """Return the positions in the trial's registered image of consensus points.
- Port of ``trialWarpCoords.m`` (zero-based): through the patchwise
- field ``x + u_t(x)`` (evaluated in blocks of 50000 points), or the
+ Port of trialWarpCoords.m (zero-based): through the patchwise
+ field x + u_t(x) (evaluated in blocks of 50000 points), or the
affine map.
Parameters
@@ -672,12 +785,12 @@ def coords(self, trial: int, rows, cols) -> tuple[np.ndarray, np.ndarray]:
)
def inverse(
- self, trial: int, rows_t, cols_t
+ self, trial: int, rows_t: npt.ArrayLike, cols_t: npt.ArrayLike
) -> tuple[np.ndarray, np.ndarray]:
- """Consensus points that a trial's image points are read from.
+ """Return the consensus points that a trial's image points are read from.
- Port of ``trialWarpInverse.m`` (zero-based): the inverse of the
- affine part, then, for a patchwise field, ``x <- x + (y - map(x))``
+ Port of trialWarpInverse.m (zero-based): the inverse of the
+ affine part, then, for a patchwise field, x <- x + (y - map(x))
until the residual is below 1e-6 px (at most 20 times; it converges
because the field bends by far less than a pixel per pixel).
@@ -696,12 +809,10 @@ def inverse(
rt = np.asarray(rows_t, dtype=np.float64)
ct = np.asarray(cols_t, dtype=np.float64)
shape = np.broadcast_shapes(rt.shape, ct.shape)
- y = np.vstack(
- [
- np.broadcast_to(rt, shape).ravel(),
- np.broadcast_to(ct, shape).ravel(),
- ]
- )
+ y = np.vstack([
+ np.broadcast_to(rt, shape).ravel(),
+ np.broadcast_to(ct, shape).ravel(),
+ ])
a = self.affine[trial]
x = np.linalg.solve(a[:, :2], y - a[:, 2:3])
if self.nodes.shape[0]:
@@ -713,10 +824,15 @@ def inverse(
break
return x[0].reshape(shape), x[1].reshape(shape)
- def grid_coords(
- self, trial: int, shape: tuple[int, int]
- ) -> tuple[np.ndarray, np.ndarray]:
- """:meth:`coords` of every pixel of a ``(rows, cols)`` grid."""
+ def grid_coords(self, trial: int, shape: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]:
+ """Return :meth:`coords` of every pixel of a (rows, cols) grid.
+
+ Returns
+ -------
+ rows_t, cols_t : np.ndarray
+ The coordinates in the trial's registered image of every pixel of
+ the grid.
+ """
rr = np.arange(shape[0], dtype=np.float64)[:, None]
cc = np.arange(shape[1], dtype=np.float64)[None, :]
return self.coords(trial, *np.broadcast_arrays(rr, cc))
@@ -731,8 +847,8 @@ def warp_trial_image(
) -> np.ndarray:
"""Resample a trial image into the consensus frame.
- Port of ``warpTrialImage.m`` / ``warpImageAffine.m``:
- ``out[r, c] = im[warp.coords(trial, r, c)]`` on the grid of ``im``, NaN
+ Port of warpTrialImage.m / warpImageAffine.m:
+ out[r, c] = im[warp.coords(trial, r, c)] on the grid of im, NaN
outside the image or next to a NaN.
Parameters
@@ -744,29 +860,35 @@ def warp_trial_image(
trial : int
Zero-based trial.
method : str
- ``"linear"``, or ``"cubic"`` (falling back to linear where cubic
+ "linear", or "cubic" (falling back to linear where cubic
would reach a NaN, so it removes no more pixels than linear).
coords : (ndarray, ndarray), optional
- ``warp.grid_coords(trial, im.shape[:2])``, when already computed
+ warp.grid_coords(trial, im.shape[:2]), when already computed
(a patchwise field costs a blend over the patch centres per pixel).
Returns
-------
ndarray
- The resampled image, in the shape of ``im``.
+ The resampled image, in the shape of im.
+
+ Raises
+ ------
+ ValueError
+ If method is not "linear", "cubic" or "cubic_clamped".
"""
if method not in ("linear", "cubic", "cubic_clamped"):
- raise ValueError(
- f"interpolation {method!r} is not 'linear', 'cubic', or "
- "'cubic_clamped'"
- )
+ raise ValueError(f"interpolation {method!r} is not 'linear', 'cubic', or 'cubic_clamped'")
im = np.asarray(im, dtype=np.float64)
- r_t, c_t = (
- warp.grid_coords(trial, im.shape[:2]) if coords is None else coords
- )
+ r_t, c_t = warp.grid_coords(trial, im.shape[:2]) if coords is None else coords
+
+ def one(plane: np.ndarray) -> np.ndarray:
+ """Resample one channel.
- def one(plane):
- """One channel."""
+ Returns
+ -------
+ np.ndarray
+ The resampled channel.
+ """
if method == "cubic_clamped":
return interp2_cubic_clamped(plane, r_t, c_t)
lin = interp2_linear(plane, r_t, c_t)
@@ -780,11 +902,16 @@ def one(plane):
return np.stack([one(im[:, :, k]) for k in range(im.shape[2])], axis=2)
-def warp_image_affine(
- im: np.ndarray, a: np.ndarray, method: str = "linear"
-) -> np.ndarray:
- """Resample an image through one affine map (``warpImageAffine.m``):
- ``out[x] = im[a @ [x, 1]]``, zero-based, NaN outside or next to NaN."""
+def warp_image_affine(im: np.ndarray, a: np.ndarray, method: str = "linear") -> np.ndarray:
+ """Resample an image through one affine map (warpImageAffine.m).
+
+ That is out[x] = im[a @ [x, 1]], zero-based, NaN outside or next to NaN.
+
+ Returns
+ -------
+ np.ndarray
+ The resampled image, in the shape of im.
+ """
return warp_trial_image(im, TrialWarp(np.asarray(a)[None]), 0, method)
@@ -796,7 +923,7 @@ def mask_to_consensus(
) -> np.ndarray:
"""Move a mask drawn on a trial's image into the consensus frame.
- Port of what ``roisToConsensusFrame.m`` and ``shiftRoiData.m`` do to an
+ Port of what roisToConsensusFrame.m and shiftRoiData.m do to an
ROI's mask. For a shift the mask moves by minus the trial's shift,
rounded; for another map each consensus pixel takes the mask's value at
the nearest pixel of its position in the trial. Pixels that leave the
@@ -812,11 +939,12 @@ def mask_to_consensus(
trial : int or None
Zero-based trial the mask was drawn on.
shape : tuple of int
- ``(rows, cols)`` of the consensus frame.
+ (rows, cols) of the consensus frame.
Returns
-------
- ndarray of bool, shape ``shape``
+ ndarray of bool, shape shape
+ The mask in the consensus frame.
"""
mask = np.asarray(mask, dtype=bool)
out = np.zeros(shape, bool)
@@ -837,9 +965,7 @@ def mask_to_consensus(
# MATLAB rounds its one-based (positive) coordinates: halves go up
r_t = np.floor(r_t + 0.5).astype(np.int64)
c_t = np.floor(c_t + 0.5).astype(np.int64)
- ok = (
- (r_t >= 0) & (r_t < mask.shape[0]) & (c_t >= 0) & (c_t < mask.shape[1])
- )
+ ok = (r_t >= 0) & (r_t < mask.shape[0]) & (c_t >= 0) & (c_t < mask.shape[1])
out[ok] = mask[r_t[ok], c_t[ok]]
return out
@@ -855,7 +981,7 @@ class RigidAlignment:
samples : ndarray of int
Zero-based trials the template was made from.
shifts : ndarray of shape (trials, 2)
- Each trial's shift ``(rows, cols)`` (MATLAB's ``motOutput``); NaN
+ Each trial's shift (rows, cols) (MATLAB's motOutput); NaN
for trials that were not aligned.
corr : ndarray of shape (trials,)
Correlation of each trial's mean image with the template.
@@ -868,8 +994,16 @@ class RigidAlignment:
def template_samples(keep: np.ndarray, n_samples: int = 20) -> np.ndarray:
- """The kept trials the template is made from: up to ``n_samples``,
- evenly spaced (``round(linspace(1, n, n_samples))``, unique)."""
+ """Return the kept trials the template is made from.
+
+ These are up to n_samples,
+ evenly spaced (round(linspace(1, n, n_samples)), unique).
+
+ Returns
+ -------
+ np.ndarray
+ Zero-based indices of the trials sampled.
+ """
kept = np.flatnonzero(keep)
pick = matlab_round(np.linspace(1, kept.size, n_samples)).astype(int)
return kept[np.unique(pick) - 1]
@@ -883,7 +1017,7 @@ def align_trials(
clip: float = 80.0,
n_samples: int = 20,
) -> RigidAlignment:
- """Rigid alignment of the trials of one imaging path (as ``SILo.m``).
+ """Align rigidly the trials of one imaging path (as SILo.m).
Parameters
----------
@@ -898,7 +1032,7 @@ def align_trials(
max_shift : int
Search range of the refinement, and the template's margin.
clip : float
- ``clip`` of the whole-pixel estimate
+ clip of the whole-pixel estimate
(:func:`dftregistration_clipped`).
n_samples : int
Largest number of trials the template is made from. Kept trials
@@ -908,6 +1042,7 @@ def align_trials(
Returns
-------
RigidAlignment
+ The template, the sampled trials, the shifts and the correlations.
Raises
------
@@ -931,9 +1066,7 @@ def align_trials(
shifts = np.full((n_trials, 2), np.nan)
corr = np.full(n_trials, np.nan)
with np.errstate(invalid="ignore"):
- fill = (
- np.nanmin(template) - 1 if not np.isnan(template).all() else np.nan
- )
+ fill = np.nanmin(template) - 1 if not np.isnan(template).all() else np.nan
t_fft = np.fft.fft2(np.fmax(template, fill))
padded = np.full(template.shape, np.nan)
for t in range(n_trials):
@@ -941,12 +1074,8 @@ def align_trials(
continue
padded[:] = np.nan
padded[s : s + h, s : s + w] = m[t]
- out = dftregistration_clipped(
- t_fft, np.fft.fft2(np.fmax(padded, fill)), clip
- )
- shifts[t], corr[t] = xcorr2_nans(
- padded, template, (-out[2], -out[3]), s
- )
+ out = dftregistration_clipped(t_fft, np.fft.fft2(np.fmax(padded, fill)), clip)
+ shifts[t], corr[t] = xcorr2_nans(padded, template, (-out[2], -out[3]), s)
return RigidAlignment(template, samples, shifts, corr)
@@ -955,8 +1084,7 @@ def align_trials(
@dataclass
class AlignmentInfo:
- """Diagnostics of :func:`align_trials_affine` and
- :func:`align_trials_patchwise`.
+ """Diagnostics of :func:`align_trials_affine` and :func:`align_trials_patchwise`.
Attributes
----------
@@ -981,12 +1109,24 @@ class AlignmentInfo:
def _fitted_trials(tforms: np.ndarray) -> np.ndarray:
- """Trials whose starting map has no NaN."""
+ """Return the trials whose starting map has no NaN.
+
+ Returns
+ -------
+ np.ndarray
+ Zero-based indices of the trials whose map has no NaN.
+ """
return np.flatnonzero(~np.isnan(tforms).any(axis=(1, 2)))
def _nanmean0(stack: np.ndarray) -> np.ndarray:
- """Mean over axis 0 with NaN ignored (NaN where nothing is left)."""
+ """Return the mean over axis 0 with NaN ignored (NaN where nothing is left).
+
+ Returns
+ -------
+ np.ndarray
+ The mean over axis 0.
+ """
ok = ~np.isnan(stack)
count = ok.sum(axis=0)
total = np.where(ok, stack, 0.0).sum(axis=0)
@@ -994,28 +1134,48 @@ def _nanmean0(stack: np.ndarray) -> np.ndarray:
return np.where(count > 0, total / count, np.nan)
-def _affine_template(s, tforms, trials):
- """Mean of the trials warped into the common frame (linear); NaN where
- fewer than half of the trials are seen."""
- stack = np.stack(
- [warp_image_affine(s[t], tforms[t], "linear") for t in trials]
- )
+def _affine_template(s: np.ndarray, tforms: np.ndarray, trials: np.ndarray) -> np.ndarray:
+ """Return the mean of the trials warped into the common frame (linear).
+
+ It is NaN where
+ fewer than half of the trials are seen.
+
+ Returns
+ -------
+ np.ndarray
+ The template.
+ """
+ stack = np.stack([warp_image_affine(s[t], tforms[t], "linear") for t in trials])
template = _nanmean0(stack)
template[(~np.isnan(stack)).sum(axis=0) < len(trials) / 2] = np.nan
return template
def _corr(a: np.ndarray, b: np.ndarray) -> float:
- """Pearson correlation (NaN for fewer than two points)."""
+ """Return the Pearson correlation (NaN for fewer than two points).
+
+ Returns
+ -------
+ float
+ The correlation of a and b.
+ """
if a.size < 2:
return float("nan")
return float(np.corrcoef(a, b)[0, 1])
-def _refine_affine(s, template, a):
- """Forward-additive Gauss-Newton: minimize, over the template's pixels,
- ``sum (S(A x) - g T(x) - b)^2`` over the map ``A``, gain ``g`` and offset
- ``b`` (``refineAffine`` in ``alignTrialsAffine.m``)."""
+def _refine_affine(s: np.ndarray, template: np.ndarray, a: np.ndarray) -> np.ndarray:
+ """Refine an affine map by forward-additive Gauss-Newton.
+
+ It minimizes, over the template's pixels,
+ sum (S(A x) - g T(x) - b)^2 over the map A, gain g and offset
+ b (refineAffine in alignTrialsAffine.m).
+
+ Returns
+ -------
+ np.ndarray
+ The refined map, shape (2, 3).
+ """
max_iter, tol = 50, 1e-3 # tol: pixels, largest displacement change
r, c = _colmajor_nonzero(~np.isnan(template))
if r.size < 500:
@@ -1025,12 +1185,10 @@ def _refine_affine(s, template, a):
c = c.astype(np.float64)
r0, c0, sc = r.mean(), c.mean(), 100.0 # centred, scaled coordinates
u, v = (r - r0) / sc, (c - c0) / sc
- corners = np.array(
- [
- [r.min(), r.max(), r.min(), r.max()],
- [c.min(), c.min(), c.max(), c.max()],
- ]
- )
+ corners = np.array([
+ [r.min(), r.max(), r.min(), r.max()],
+ [c.min(), c.min(), c.max(), c.max()],
+ ])
g_r, g_c = matlab_gradient(s)
cubic = CubicInterpolant(s)
a = a.copy()
@@ -1051,9 +1209,7 @@ def _refine_affine(s, template, a):
d_lin = np.array([[dp[0], dp[1]], [dp[3], dp[4]]]) / sc
d_t = np.array([dp[2], dp[5]]) - d_lin @ np.array([r0, c0])
# limit the step to 1 px anywhere on the template
- step = np.max(
- np.sqrt(((d_lin @ corners + d_t[:, None]) ** 2).sum(axis=0))
- )
+ step = np.max(np.sqrt(((d_lin @ corners + d_t[:, None]) ** 2).sum(axis=0)))
if step > 1:
d_lin, d_t = d_lin / step, d_t / step
a[:, :2] += d_lin
@@ -1063,9 +1219,16 @@ def _refine_affine(s, template, a):
return a
-def _recentre(tforms, trials, x0):
- """Right-multiply every map so that the trials' mean linear part is the
- identity and the mean mapping of ``x0`` is unchanged."""
+def _recentre(tforms: np.ndarray, trials: np.ndarray, x0: np.ndarray) -> np.ndarray:
+ """Right-multiply every map so that the trials' mean linear part is the identity.
+
+ The mean mapping of x0 is unchanged.
+
+ Returns
+ -------
+ np.ndarray
+ The recentred maps, shape (trials, 2, 3).
+ """
a_bar = tforms[trials].mean(axis=0)
l_inv = np.linalg.inv(a_bar[:, :2])
b = np.eye(3)
@@ -1082,10 +1245,10 @@ def align_trials_affine(
) -> tuple[np.ndarray, AlignmentInfo]:
"""Refine the trials' maps to affine maps, groupwise.
- Port of ``alignTrialsAffine.m``. The template is the mean of the trials
+ Port of alignTrialsAffine.m. The template is the mean of the trials
warped into the common frame; each trial's affine map is refit to it by
Gauss-Newton (with a gain and offset, on square-root images, NaN
- ignored) and the template is rebuilt, for ``n_rounds`` rounds. Each
+ ignored) and the template is rebuilt, for n_rounds rounds. Each
round the trials' mean linear part is removed, so the common frame keeps
the trials' average geometry, with the image centre where it was.
@@ -1104,6 +1267,7 @@ def align_trials_affine(
tforms : ndarray of shape (trials, 2, 3)
The refined maps.
info : AlignmentInfo
+ Diagnostics of the alignment.
"""
m = np.asarray(mean_sum, dtype=np.float64)
n_trials, h, w = m.shape
@@ -1137,17 +1301,24 @@ def align_trials_affine(
# --------------------------------------------------------- patchwise field
-def _plane_basis(nodes: np.ndarray, rows: np.ndarray, cols: np.ndarray):
- """The plane's design at the centres and at the points (centred, scaled
- coordinates; the mean with fewer than 3 centres)."""
+def _plane_basis(
+ nodes: np.ndarray, rows: np.ndarray, cols: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """Return the plane's design at the centres and at the points.
+
+ The coordinates are centred and scaled; the plane is the mean with fewer than 3 centres.
+
+ Returns
+ -------
+ p, pq : np.ndarray
+ The design at the centres and at the points.
+ """
k = nodes.shape[0]
if k >= 3:
mu = nodes.mean(axis=0)
sc = np.max(np.std(nodes, axis=0, ddof=1)) + _EPS
p = np.column_stack([(nodes - mu) / sc, np.ones(k)])
- pq = np.column_stack(
- [(rows - mu[0]) / sc, (cols - mu[1]) / sc, np.ones(rows.size)]
- )
+ pq = np.column_stack([(rows - mu[0]) / sc, (cols - mu[1]) / sc, np.ones(rows.size)])
else:
p = np.ones((k, 1))
pq = np.ones((rows.size, 1))
@@ -1155,30 +1326,44 @@ def _plane_basis(nodes: np.ndarray, rows: np.ndarray, cols: np.ndarray):
def _pinv(a: np.ndarray) -> np.ndarray:
- """MATLAB's ``pinv`` (singular values below ``max(size) * eps(norm)``
- dropped)."""
+ """Return MATLAB's pinv.
+
+ Singular values below max(size) * eps(norm)
+ are dropped.
+
+ Returns
+ -------
+ np.ndarray
+ The pseudo-inverse of a.
+ """
return np.linalg.pinv(a, rcond=max(a.shape) * _EPS)
-def _blend(nodes, sigma, rows, cols) -> np.ndarray:
- """Gaussian weights of the centres at the points, relative to the
- nearest centre (so far points do not underflow), summing to 1."""
- d2 = (rows[:, None] - nodes[None, :, 0]) ** 2 + (
- cols[:, None] - nodes[None, :, 1]
- ) ** 2
+def _blend(nodes: np.ndarray, sigma: float, rows: np.ndarray, cols: np.ndarray) -> np.ndarray:
+ """Return the Gaussian weights of the centres at the points.
+
+ They are relative to the
+ nearest centre (so far points do not underflow), summing to 1.
+
+ Returns
+ -------
+ np.ndarray
+ The weights, shape (points, n_nodes).
+ """
+ d2 = (rows[:, None] - nodes[None, :, 0]) ** 2 + (cols[:, None] - nodes[None, :, 1]) ** 2
phi = np.exp(-(d2 - d2.min(axis=1, keepdims=True)) / (2 * sigma**2))
return phi / phi.sum(axis=1, keepdims=True)
def patch_field_matrix(
- nodes: np.ndarray, sigma: float, rows, cols
+ nodes: np.ndarray, sigma: float, rows: npt.ArrayLike, cols: npt.ArrayLike
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- """Displacements at points from displacements at patch centres.
+ """Return the displacements at points from displacements at patch centres.
- Port of ``patchFieldMatrix.m``: ``u(rows, cols) = L @ d`` for the values
- ``d`` (``(n_nodes,)`` or ``(n_nodes, 2)``) at the centres: the plane
+ Port of patchFieldMatrix.m: u(rows, cols) = L @ d for the values
+ d ((n_nodes,) or (n_nodes, 2)) at the centres: the plane
fitted by least squares through the centre values, plus a blend of each
- centre's departure from it with Gaussian weights of SD ``sigma``,
+ centre's departure from it with Gaussian weights of SD sigma,
normalized to sum to 1. With fewer than 3 centres the plane is their
mean.
@@ -1186,7 +1371,7 @@ def patch_field_matrix(
-------
L : ndarray of shape (points, n_nodes)
E : ndarray of shape (n_nodes, n_nodes)
- The departures from the plane, ``E @ d``.
+ The departures from the plane, E @ d.
L_plane : ndarray of shape (points, n_nodes)
The plane alone.
"""
@@ -1201,11 +1386,18 @@ def patch_field_matrix(
def patch_field_apply(
- nodes: np.ndarray, sigma: float, rows, cols, d: np.ndarray
+ nodes: np.ndarray, sigma: float, rows: npt.ArrayLike, cols: npt.ArrayLike, d: np.ndarray
) -> np.ndarray:
- """``patch_field_matrix(nodes, sigma, rows, cols)[0] @ d`` without the
- matrix (``patchFieldApply.m``): the plane's coefficients and the
- centres' departures are computed from ``d`` once."""
+ """Apply patch_field_matrix(nodes, sigma, rows, cols)[0] @ d without the matrix.
+
+ This is patchFieldApply.m: the plane's coefficients and the
+ centres' departures are computed from d once.
+
+ Returns
+ -------
+ np.ndarray
+ The displacements at the points.
+ """
nodes = np.asarray(nodes, dtype=np.float64).reshape(-1, 2)
r = np.asarray(rows, dtype=np.float64).ravel()
c = np.asarray(cols, dtype=np.float64).ravel()
@@ -1224,9 +1416,11 @@ def kmeans(
start: np.ndarray | None = None,
max_iter: int = 500,
) -> tuple[np.ndarray, np.ndarray]:
- """k-means with MATLAB ``kmeans``'s defaults (squared Euclidean,
- k-means++ starts, batch updates until no point moves, an empty cluster
- restarted at the point farthest from its centroid).
+ """Cluster points with k-means, with MATLAB kmeans's defaults.
+
+ These are squared Euclidean distance,
+ k-means++ starts, batch updates until no point moves, and an empty cluster
+ restarted at the point farthest from its centroid.
Parameters
----------
@@ -1234,7 +1428,7 @@ def kmeans(
k : int
Clusters.
rng : numpy Generator, optional
- For the k-means++ starts (needed without ``start``).
+ For the k-means++ starts (needed without start).
replicates : int
Runs from new starts; the one with the smallest total distance is
kept.
@@ -1276,18 +1470,21 @@ def kmeans(
labels = new
counts = np.bincount(labels, minlength=k).astype(np.float64)
for dim in range(x.shape[1]):
- cen[:, dim] = (
- np.bincount(labels, weights=x[:, dim], minlength=k)
- / counts
- )
+ cen[:, dim] = np.bincount(labels, weights=x[:, dim], minlength=k) / counts
total = float(((x - cen[labels]) ** 2).sum())
if best is None or total < best[0]:
best = (total, labels.copy(), cen.copy())
return best[1], best[2]
-def _kmeans_plus_plus(x, k, rng) -> np.ndarray:
- """k-means++ starting centroids."""
+def _kmeans_plus_plus(x: np.ndarray, k: int, rng: np.random.Generator) -> np.ndarray:
+ """Return the k-means++ starting centroids.
+
+ Returns
+ -------
+ np.ndarray
+ The k starting centroids, shape (k, dims).
+ """
n = x.shape[0]
cen = np.empty((k, x.shape[1]))
cen[0] = x[rng.integers(n)]
@@ -1303,11 +1500,13 @@ def _kmeans_plus_plus(x, k, rng) -> np.ndarray:
def make_patches(
valid: np.ndarray, patch_px: float, seed: int = 0
) -> tuple[np.ndarray, np.ndarray]:
- """Patches of about ``patch_px`` valid pixels (``makePatches`` in
- ``alignTrialsPatchwise.m``).
+ """Make patches of about patch_px valid pixels.
+
+ This is makePatches in
+ alignTrialsPatchwise.m.
k-means on the valid pixels' coordinates (3 replicates); while a cluster
- has fewer than ``patch_px / 2`` pixels, the smallest is dropped and
+ has fewer than patch_px / 2 pixels, the smallest is dropped and
k-means rerun from the remaining centroids.
Returns
@@ -1315,7 +1514,12 @@ def make_patches(
patch : ndarray of int32, shape valid.shape
1 to K on the valid pixels, 0 elsewhere.
nodes : ndarray of shape (K, 2)
- The patches' centroids ``(row, col)``, zero-based.
+ The patches' centroids (row, col), zero-based.
+
+ Raises
+ ------
+ ValueError
+ If patch_px is less than 1.
"""
rows, cols = _colmajor_nonzero(valid)
x = np.column_stack([rows, cols]).astype(np.float64)
@@ -1338,12 +1542,12 @@ def make_patches(
@dataclass
class PatchwiseFit:
- """Result of :func:`align_trials_patchwise` (MATLAB's ``warp``).
+ """Result of :func:`align_trials_patchwise` (MATLAB's warp).
Attributes
----------
nodes : ndarray of shape (K, 2)
- Patch centres, zero-based ``(row, col)``.
+ Patch centres, zero-based (row, col).
sigma : float
SD of the blend (half the median distance to the nearest centre).
disp : ndarray of shape (trials, K, 2)
@@ -1361,9 +1565,23 @@ class PatchwiseFit:
affine: np.ndarray
-def _patch_template(s, d, lmat, r, c, trials):
- """The trials warped into the common frame at the fit pixels, averaged;
- NaN where fewer than half are seen."""
+def _patch_template(
+ s: np.ndarray,
+ d: np.ndarray,
+ lmat: np.ndarray,
+ r: np.ndarray,
+ c: np.ndarray,
+ trials: np.ndarray,
+) -> np.ndarray:
+ """Return the trials warped into the common frame at the fit pixels, averaged.
+
+ It is NaN where fewer than half are seen.
+
+ Returns
+ -------
+ np.ndarray
+ The template at the fit pixels, shape (pixels,).
+ """
v = np.empty((r.size, len(trials)))
for k, t in enumerate(trials):
u = lmat @ d[t].T
@@ -1376,9 +1594,17 @@ def _patch_template(s, d, lmat, r, c, trials):
return template
-def _group_median(values, groups, k) -> np.ndarray:
- """Median of ``values`` per group 0..k-1 (0 for an empty group, as
- MATLAB's ``accumarray`` with ``@median``)."""
+def _group_median(values: np.ndarray, groups: np.ndarray, k: int) -> np.ndarray:
+ """Return the median of values per group 0..k-1.
+
+ It is 0 for an empty group, as
+ MATLAB's accumarray with @median.
+
+ Returns
+ -------
+ np.ndarray
+ The median of each group, shape (k,).
+ """
out = np.zeros(k)
if values.size == 0:
return out
@@ -1393,9 +1619,19 @@ def _group_median(values, groups, k) -> np.ndarray:
return out
-def _interp2_linear_pair(ims, rows, cols):
- """:func:`interp2_linear` of two images at the same points (the weights
- and indices computed once)."""
+def _interp2_linear_pair(
+ ims: Sequence[np.ndarray], rows: npt.ArrayLike, cols: npt.ArrayLike
+) -> list[np.ndarray]:
+ """Interpolate two images at the same points with :func:`interp2_linear`.
+
+ The weights
+ and indices are computed once.
+
+ Returns
+ -------
+ list of np.ndarray
+ The interpolated values of each image, in the shape of rows.
+ """
h, w = ims[0].shape
rows = np.asarray(rows, dtype=np.float64)
cols = np.asarray(cols, dtype=np.float64)
@@ -1424,17 +1660,34 @@ def _interp2_linear_pair(ims, rows, cols):
return outs
-def _refine_field(s, template, d, lmat, r, c, pix, e_mat, lambda_rel):
- """Robust Gauss-Newton for all centre displacements of one trial
- (``refineField`` in ``alignTrialsPatchwise.m``): minimize the bisquare
- loss of ``S(x + u(x)) - g_k T(x) - b_k`` over the fit pixels (``k`` their
- patch), ``u = L @ d``, plus ``lambda |E d|^2``.
+def _refine_field(
+ s: np.ndarray,
+ template: np.ndarray,
+ d: np.ndarray,
+ lmat: np.ndarray,
+ r: np.ndarray,
+ c: np.ndarray,
+ pix: np.ndarray,
+ e_mat: np.ndarray,
+ lambda_rel: float,
+) -> np.ndarray:
+ """Run a robust Gauss-Newton for all centre displacements of one trial.
+
+ This is
+ (refineField in alignTrialsPatchwise.m): minimize the bisquare
+ loss of S(x + u(x)) - g_k T(x) - b_k over the fit pixels (k their
+ patch), u = L @ d, plus ``lambda |E d|^2``.
- ``d`` is ``(2, K)`` (MATLAB's layout); returns the refined ``d``. The
- normal equations are MATLAB's, of the design ``[Xs, Xd]`` (a gain and
+ d is (2, K) (MATLAB's layout); returns the refined d. The
+ normal equations are MATLAB's, of the design [Xs, Xd] (a gain and
offset per patch, then the centres' row and column updates), with
- ``sqrt(W) Xd = -sqrt(W) [GR .* L, GC .* L]`` formed once per iteration
- (its Gram matrix as a symmetric product) and ``Xs`` sparse.
+ sqrt(W) Xd = -sqrt(W) [GR .* L, GC .* L] formed once per iteration
+ (its Gram matrix as a symmetric product) and Xs sparse.
+
+ Returns
+ -------
+ np.ndarray
+ The refined d, shape (2, K).
"""
max_iter, tol = 30, 1e-3 # tol: pixels, largest centre update
k = lmat.shape[1]
@@ -1480,9 +1733,7 @@ def _refine_field(s, template, d, lmat, r, c, pix, e_mat, lambda_rel):
shape=(2 * k, n),
)
a12 = -(xs @ grad)
- b1 = np.concatenate(
- [np.bincount(pix, wk * tz * y, k), np.bincount(pix, wk * y, k)]
- )
+ b1 = np.concatenate([np.bincount(pix, wk * tz * y, k), np.bincount(pix, wk * y, k)])
b2 = -(grad.T @ (sw * y))
lam = lambda_rel * np.median(np.diag(a22))
a22 = a22 + lam * penalty
@@ -1492,12 +1743,7 @@ def _refine_field(s, template, d, lmat, r, c, pix, e_mat, lambda_rel):
a = a + (1e-10 * np.mean(np.diag(a)) + _EPS) * np.eye(4 * k)
beta = np.linalg.solve(a, np.concatenate([b1, b2]))
lb = lmat @ np.column_stack([beta[2 * k : 3 * k], beta[3 * k :]])
- err = (
- y
- - (tz * beta[pix] + beta[k + pix])
- + gr * lb[:, 0]
- + gc * lb[:, 1]
- )
+ err = y - (tz * beta[pix] + beta[k + pix]) + gr * lb[:, 0] + gc * lb[:, 1]
sc = 1.4826 * _group_median(np.abs(err[ok]), pix[ok], k) + _EPS
uu = err[ok] / (4.685 * sc[pix[ok]])
w[ok] = (1 - uu**2) ** 2 * (np.abs(uu) < 1)
@@ -1522,17 +1768,17 @@ def align_trials_patchwise(
) -> tuple[PatchwiseFit, AlignmentInfo]:
"""Align the trials with patchwise displacement fields, groupwise.
- Port of ``alignTrialsPatchwise.m``. A common-frame pixel ``x`` is read
- from trial ``t`` at ``x + u_t(x)``, with ``u_t`` set by its values at the
+ Port of alignTrialsPatchwise.m. A common-frame pixel x is read
+ from trial t at x + u_t(x), with u_t set by its values at the
centres of patches of imaged pixels (:func:`patch_field_matrix`). The
patches are k-means clusters of the pixels imaged in at least half of
the trials (:func:`make_patches`). The fit is groupwise, as
:func:`align_trials_affine`, with a gain and offset per patch, robust
bisquare weights and a weak penalty on departures from the plane; the
mean field across trials is held at that of the starting maps. With
- ``halves``, each trial is refit on both halves, and each centre's
- departure from the plane is scaled by ``max(0, 1 - noise variance /
- variance across trials)``, so a bend that is not above its noise
+ halves, each trial is refit on both halves, and each centre's
+ departure from the plane is scaled by max(0, 1 - noise variance /
+ variance across trials), so a bend that is not above its noise
follows the plane.
Parameters
@@ -1546,12 +1792,12 @@ def align_trials_patchwise(
Mean images of two halves of equal size of each trial's frames.
Without, the departures are kept as fitted.
patch_px : float
- Pixels per patch (``alignPatchPx``).
+ Pixels per patch (alignPatchPx).
n_rounds : int
Rounds of template and refit.
patches : (ndarray, ndarray), optional
- ``(patch, nodes)`` to use instead of :func:`make_patches` (MATLAB's
- ``warp.patch`` and zero-based ``warp.nodes``, for parity tests).
+ (patch, nodes) to use instead of :func:`make_patches` (MATLAB's
+ warp.patch and zero-based warp.nodes, for parity tests).
workers : int
Worker processes that refit the trials of a round (each trial's
refit is independent of the others'; :class:`_TrialRefiner`), at
@@ -1563,8 +1809,9 @@ def align_trials_patchwise(
-------
fit : PatchwiseFit
Without patches (too few imaged pixels, or fewer than 2 trials):
- no centres, and ``affine`` the starting maps.
+ no centres, and affine the starting maps.
info : AlignmentInfo
+ Diagnostics of the alignment.
"""
workers = check_workers(workers)
m = np.asarray(mean_sum, dtype=np.float64)
@@ -1603,9 +1850,7 @@ def align_trials_patchwise(
template = lay.template(s, disp, trials)
disp[trials] = refiner.refine(s, template, disp, trials)
disp[trials] = disp[trials] - disp[trials].mean(axis=0) + mean0
- bend, bend_var, noise_var, weight = _bends(
- lay, s, halves, disp, trials, mean0, refiner
- )
+ bend, bend_var, noise_var, weight = _bends(lay, s, halves, disp, trials, mean0, refiner)
for t in trials:
disp[t] = disp[t] - (1 - weight) * bend[t]
@@ -1620,11 +1865,33 @@ def align_trials_patchwise(
return fit, info
-def _bends(lay, s, halves, disp, trials, mean0, refiner):
- """Each trial's departures from the plane, per centre their variance
+def _bends(
+ lay: _FieldLayout,
+ s: np.ndarray,
+ halves: np.ndarray | None,
+ disp: np.ndarray,
+ trials: np.ndarray,
+ mean0: np.ndarray,
+ refiner: _TrialRefiner,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Return each trial's departures from the plane and their statistics.
+
+ Per centre, their variance
across the trials and their noise variance (from the halves; NaN
- without), and the weight that keeps them (``align_trials_patchwise``'s
- reliability step)."""
+ without), and the weight that keeps them (align_trials_patchwise's
+ reliability step).
+
+ Returns
+ -------
+ bend : np.ndarray
+ Each trial's departures from the plane, shape (trials, 2, K).
+ bend_var : np.ndarray
+ Their variance across the trials, per centre.
+ noise_var : np.ndarray
+ Their noise variance per centre (NaN without halves).
+ weight : np.ndarray
+ The weight that keeps the departures, per centre.
+ """
n_trials = disp.shape[0]
# reliability: refit each half against the final template
@@ -1646,17 +1913,25 @@ def _bends(lay, s, halves, disp, trials, mean0, refiner):
_REFINE_LAYOUT = None # a refitting worker's field layout (_TrialRefiner)
-def _refiner_init(lay) -> None:
+def _refiner_init(lay: _FieldLayout) -> None:
"""Give a refitting worker the field layout."""
global _REFINE_LAYOUT
_REFINE_LAYOUT = lay
-def _refine_task(args) -> tuple:
- """One trial's refit in a worker, ``(image, template, d, errors)``,
- under the caller's numpy error handling ``errors`` (``np.geterr()``):
- the refit displacements, the warnings it gave, and the exception it
- ended with (None: none), which the caller raises after the warnings."""
+def _refine_task(args: tuple) -> tuple:
+ """Refit one trial in a worker, from (image, template, d, errors).
+
+ This is done
+ under the caller's numpy error handling errors (np.geterr()).
+
+ Returns
+ -------
+ tuple
+ (out, warnings, error): the refit displacements, the warnings it
+ gave, and the exception it ended with (None: none), which the caller
+ raises after the warnings.
+ """
s_t, template, d, errors = args
out = error = None
with warnings.catch_warnings(record=True) as caught:
@@ -1669,19 +1944,17 @@ def _refine_task(args) -> tuple:
return out, [(w.message, w.filename, w.lineno) for w in caught], error
-def _reissue(caught) -> None:
- """Issue warnings given in a worker in this process, at the place they
- were given, through this process's filters (shown once per place under
- the default action, as when they are given here)."""
+def _reissue(caught: Iterable[tuple[Warning, str, int]]) -> None:
+ """Issue warnings given in a worker in this process, at the place they were given.
+
+ They go through this process's filters (shown once per place under
+ the default action, as when they are given here).
+ """
import sys
for message, filename, lineno in caught:
module = next(
- (
- m
- for m in list(sys.modules.values())
- if getattr(m, "__file__", None) == filename
- ),
+ (m for m in list(sys.modules.values()) if getattr(m, "__file__", None) == filename),
None,
)
warnings.warn_explicit(
@@ -1691,9 +1964,7 @@ def _reissue(caught) -> None:
lineno,
module=None if module is None else module.__name__,
registry=(
- None
- if module is None
- else vars(module).setdefault("__warningregistry__", {})
+ None if module is None else vars(module).setdefault("__warningregistry__", {})
),
)
@@ -1714,7 +1985,7 @@ class _TrialRefiner:
libraries use different numbers, a worker's differs, this process is
daemonic, or the workers cannot be started (then with a warning), the
workers are stopped and the trials are refit here. Each refit runs
- under this process's numpy error handling (``np.geterr()``; here, and
+ under this process's numpy error handling (np.geterr(); here, and
without starting workers, when that calls a function, writes to a log
object or prints), and the warnings it gives are issued here, before
the exception it ends with, if any. The workers' idle BLAS threads
@@ -1728,8 +1999,8 @@ class _TrialRefiner:
at its end, at once if it ends with an exception.
"""
- def __init__(self, lay, workers: int = 1) -> None:
- """The layout and the number of workers (1: no workers)."""
+ def __init__(self, lay: _FieldLayout, workers: int = 1) -> None:
+ """Set the layout and the number of workers (1: no workers)."""
self.lay = lay
self.workers = workers
self.pool = None
@@ -1737,13 +2008,21 @@ def __init__(self, lay, workers: int = 1) -> None:
self.in_workers = 0 # trials refit in the workers
self._tried = workers <= 1
- def __enter__(self):
- """The refiner (its workers start at the first refit)."""
+ def __enter__(self) -> _TrialRefiner:
+ """Return the refiner (its workers start at the first refit).
+
+ Returns
+ -------
+ _TrialRefiner
+ This refiner.
+ """
return self
- def __exit__(self, exc_type, *_) -> None:
- """Stop the workers (without waiting for them after an
- exception: the refits they are at end by themselves)."""
+ def __exit__(self, exc_type: type[BaseException] | None, *_: object) -> None:
+ """Stop the workers (without waiting for them after an exception).
+
+ The refits they are at end by themselves.
+ """
if self.pool is not None:
if exc_type is None:
self.pool.shutdown()
@@ -1752,16 +2031,28 @@ def __exit__(self, exc_type, *_) -> None:
self.pool = None
def _start(self) -> None:
- """Start the workers if they can compute as this process; if
+ """Start the workers if they can compute as this process.
+
+ If
they cannot be started (a caller whose main module the workers
cannot import, such as a script read from standard input, or no
more processes), warn, and the trials are refit here. A daemonic
- process (a ``multiprocessing.Pool`` worker) may not have
+ process (a multiprocessing.Pool worker) may not have
children: none are started there. In a spawned process that is
still importing its main module (the worker of a script that
- starts processes outside ``if __name__ == "__main__":``) the
+ starts processes outside if __name__ == "__main__":) the
standard library's error is raised as it is, so that such a
- worker ends instead of running the caller's script again."""
+ worker ends instead of running the caller's script again.
+
+ Raises
+ ------
+ OSError
+ If the workers cannot be started, in a spawned process that is
+ still importing its main module.
+ RuntimeError
+ If the workers cannot be started, in a spawned process that is
+ still importing its main module.
+ """
import multiprocessing
self._tried = True
@@ -1778,9 +2069,7 @@ def _start(self) -> None:
env = dict.fromkeys(THREAD_VARS, str(n))
env[BLAS_IDLE[0]] = BLAS_IDLE[1]
try:
- pool, started = spawn_pool(
- self.workers, env, _refiner_init, (self.lay,)
- )
+ pool, started = spawn_pool(self.workers, env, _refiner_init, (self.lay,))
except (OSError, RuntimeError) as exc:
if getattr(multiprocessing.current_process(), "_inheriting", 0):
raise
@@ -1797,9 +2086,19 @@ def _start(self) -> None:
else:
pool.shutdown()
- def refine(self, s, template, disp, trials) -> np.ndarray:
- """The refit displacements ``(len(trials), 2, K)`` of ``trials``,
- from their images ``s[t]`` and displacements ``disp[t]``."""
+ def refine(
+ self, s: np.ndarray, template: np.ndarray, disp: np.ndarray, trials: np.ndarray
+ ) -> np.ndarray:
+ """Return the refit displacements (len(trials), 2, K) of trials.
+
+ They are refit
+ from their images s[t] and displacements disp[t].
+
+ Returns
+ -------
+ np.ndarray
+ The refit displacements, shape (len(trials), 2, K).
+ """
errors = np.geterr()
# what numpy calls or prints on an error is called and printed
# here, in the order of the trials
@@ -1822,9 +2121,17 @@ def refine(self, s, template, disp, trials) -> np.ndarray:
return np.array(out).reshape((len(trials),) + disp.shape[1:])
-def _field_planes(lay, disp: np.ndarray) -> np.ndarray:
- """Each field's plane as a map ``(trials, 2, 3)``: the plane at the
- origin and one pixel along each axis."""
+def _field_planes(lay: _FieldLayout, disp: np.ndarray) -> np.ndarray:
+ """Return each field's plane as a map (trials, 2, 3).
+
+ That is the plane at the
+ origin and one pixel along each axis.
+
+ Returns
+ -------
+ np.ndarray
+ The planes as maps, shape (trials, 2, 3).
+ """
_, _, l_p = patch_field_matrix(
lay.nodes,
lay.sigma,
@@ -1839,9 +2146,18 @@ def _field_planes(lay, disp: np.ndarray) -> np.ndarray:
return out
-def _fit_quality(info, lay, s, disp, disp0, trials) -> None:
- """Each trial's correlation with the final template over the patches
- and the RMS change of its field from the start (into ``info``)."""
+def _fit_quality(
+ info: AlignmentInfo,
+ lay: _FieldLayout,
+ s: np.ndarray,
+ disp: np.ndarray,
+ disp0: np.ndarray,
+ trials: np.ndarray,
+) -> None:
+ """Record each trial's correlation with the final template over the patches.
+
+ The RMS change of its field from the start is recorded too (into info).
+ """
template = lay.template(s, disp, trials)
for t in trials:
u = lay.lmat @ disp[t].T
@@ -1852,9 +2168,20 @@ def _fit_quality(info, lay, s, disp, disp0, trials) -> None:
info.rms_disp[t] = np.sqrt(np.mean((du**2).sum(axis=1)))
-def _imaged_patches(s, tforms, trials, patch_px):
- """Patches on the pixels imaged in at least half of the trials under
- the starting maps; None if fewer than 500 are."""
+def _imaged_patches(
+ s: np.ndarray, tforms: np.ndarray, trials: np.ndarray, patch_px: float
+) -> tuple[np.ndarray, np.ndarray] | None:
+ """Return patches on the pixels imaged in at least half of the trials.
+
+ The pixels are those imaged under
+ the starting maps; None if fewer than 500 are.
+
+ Returns
+ -------
+ tuple of np.ndarray or None
+ (patch, nodes) from :func:`make_patches`, or None if fewer than
+ 500 pixels are imaged in at least half of the trials.
+ """
seen = np.zeros(s.shape[1:])
for t in trials:
seen += ~np.isnan(warp_image_affine(s[t], tforms[t], "linear"))
@@ -1877,15 +2204,13 @@ class _FieldLayout:
lambda_rel = 1e-2 # departures' penalty, relative to a centre's data
- def __init__(self, patch, nodes) -> None:
- """The pixels in MATLAB's order, sigma and the field matrix."""
+ def __init__(self, patch: np.ndarray, nodes: np.ndarray) -> None:
+ """Set the pixels in MATLAB's order, sigma and the field matrix."""
self.patch = np.asarray(patch, dtype=np.int32)
self.nodes = np.asarray(nodes, dtype=np.float64).reshape(-1, 2)
self.k = self.nodes.shape[0]
if self.k > 1:
- dd = np.sqrt(
- ((self.nodes[:, None] - self.nodes[None]) ** 2).sum(axis=2)
- )
+ dd = np.sqrt(((self.nodes[:, None] - self.nodes[None]) ** 2).sum(axis=2))
np.fill_diagonal(dd, np.inf)
self.sigma = float(np.median(dd.min(axis=1)) / 2)
else:
@@ -1894,16 +2219,26 @@ def __init__(self, patch, nodes) -> None:
self.pix = self.patch[rows, cols].astype(np.intp) - 1
self.r = rows.astype(np.float64)
self.c = cols.astype(np.float64)
- self.lmat, self.e_mat, _ = patch_field_matrix(
- self.nodes, self.sigma, self.r, self.c
- )
+ self.lmat, self.e_mat, _ = patch_field_matrix(self.nodes, self.sigma, self.r, self.c)
+
+ def template(self, s: np.ndarray, disp: np.ndarray, trials: np.ndarray) -> np.ndarray:
+ """Return the trials warped into the common frame at the fit pixels.
- def template(self, s, disp, trials):
- """The trials warped into the common frame at the fit pixels."""
+ Returns
+ -------
+ np.ndarray
+ The template at the fit pixels.
+ """
return _patch_template(s, disp, self.lmat, self.r, self.c, trials)
- def refine(self, s, template, d):
- """:func:`_refine_field` of one trial's image."""
+ def refine(self, s: np.ndarray, template: np.ndarray, d: np.ndarray) -> np.ndarray:
+ """Refit one trial's image with :func:`_refine_field`.
+
+ Returns
+ -------
+ np.ndarray
+ The refit displacements d, shape (2, K).
+ """
return _refine_field(
s,
template,
@@ -1918,12 +2253,25 @@ def refine(self, s, template, d):
def _halves_noise(
- lay, s, halves, disp, trials, mean0, refiner=None
+ lay: _FieldLayout,
+ s: np.ndarray,
+ halves: np.ndarray,
+ disp: np.ndarray,
+ trials: np.ndarray,
+ mean0: np.ndarray,
+ refiner: _TrialRefiner | None = None,
) -> np.ndarray:
- """Each centre's noise variance of its departure from the plane: the
- trials refit on each half against the final template; a quarter of the
+ """Return each centre's noise variance of its departure from the plane.
+
+ The trials are refit on each half against the final template; the variance is a quarter of the
variance of the halves' difference (halves of equal size each have
- twice the noise variance of the full data)."""
+ twice the noise variance of the full data).
+
+ Returns
+ -------
+ np.ndarray
+ The noise variance of each centre, shape (K,).
+ """
hv = np.asarray(halves, dtype=np.float64)
template = lay.template(s, disp, trials)
n_trials = disp.shape[0]
diff --git a/src/giant_python/extraction/raster/annotations.py b/src/giant_python/extraction/raster/annotations.py
index 0e304d82..4aad671f 100644
--- a/src/giant_python/extraction/raster/annotations.py
+++ b/src/giant_python/extraction/raster/annotations.py
@@ -1,31 +1,32 @@
-"""Users' ROIs of a raster session: ``annotations.h5`` read, and moved into
-the consensus frame.
-
-Port of the non-GUI path of GIAnT-MATLAB's ``loadOrCreateAnnotations.m``
-(main 5a0673b): an existing ``/annotations/annotations.h5`` is read
-(``loadAnnotationsH5.m``) and each path's ROIs are moved from the trial they
-were drawn on into SILo's consensus frame (``roisToConsensusFrame.m``,
-``shiftRoiData.m``). ROIs whose label contains ``SOMA`` mask seeding; every
+"""Users' ROIs of a raster session.
+
+annotations.h5 is read, and its ROIs moved into the consensus frame.
+
+Port of the non-GUI path of GIAnT-MATLAB's loadOrCreateAnnotations.m
+(main 5a0673b): an existing /annotations/annotations.h5 is read
+(loadAnnotationsH5.m) and each path's ROIs are moved from the trial they
+were drawn on into SILo's consensus frame (roisToConsensusFrame.m,
+shiftRoiData.m). ROIs whose label contains SOMA mask seeding; every
ROI gets a trace. The GUI that draws ROIs, and the import of
post-acquisition annotations, are not ported: without a file a session has
no user ROIs, as MATLAB's SILo when the GUI is not available.
-The file's layout (written by ``saveAnnotationsH5.m``): ``/Path`` with
-``dr`` and ``fn`` (the annotation trial's registered file stem), ``n_rois``
-and ``roi_###`` groups holding ``type``, ``label``, ``mask`` and optional
-``position``, ``center``, ``semi_axes``, ``rotation_angle``, ``radius``.
+The file's layout (written by saveAnnotationsH5.m): /Path with
+dr and fn (the annotation trial's registered file stem), n_rois
+and roi_### groups holding type, label, mask and optional
+position, center, semi_axes, rotation_angle, radius.
Strings are stored as UTF-16 code units, arrays column-major (MATLAB's
-``h5write``); ``/coords_zero_indexed`` (1 in current files) says whether
-``position`` and ``center`` are zero-based ``[row, col]``.
+h5write); /coords_zero_indexed (1 in current files) says whether
+position and center are zero-based [row, col].
"""
from __future__ import annotations
import re
import warnings
+from collections.abc import Sequence
from dataclasses import dataclass, field, replace
from pathlib import Path, PurePath
-from typing import Optional, Sequence
import h5py
import numpy as np
@@ -40,13 +41,13 @@ class UserRoi:
Attributes
----------
label : str
- The ROI's label (``Label``); ``SOMA`` in it marks a soma.
+ The ROI's label (Label); SOMA in it marks a soma.
type : str
- ``'polygon'``, ``'circle'``, ``'ellipse'`` or as stored.
+ 'polygon', 'circle', 'ellipse' or as stored.
mask : ndarray of bool, shape (rows, cols)
Pixels of the ROI (MATLAB's orientation).
center, position : ndarray or None
- Geometry in MATLAB's ``images.roi`` convention: ``[x, y]`` (column,
+ Geometry in MATLAB's images.roi convention: [x, y] (column,
row), one-based. Moved with the mask into the consensus frame.
radius, rotation_angle : float or None
semi_axes : ndarray or None
@@ -55,11 +56,11 @@ class UserRoi:
label: str
type: str
mask: np.ndarray
- center: Optional[np.ndarray] = None
- position: Optional[np.ndarray] = None
- radius: Optional[float] = None
- semi_axes: Optional[np.ndarray] = None
- rotation_angle: Optional[float] = None
+ center: np.ndarray | None = None
+ position: np.ndarray | None = None
+ radius: float | None = None
+ semi_axes: np.ndarray | None = None
+ rotation_angle: float | None = None
@property
def is_soma(self) -> bool:
@@ -69,7 +70,7 @@ def is_soma(self) -> bool:
@dataclass
class PathAnnotations:
- """One imaging path's ROIs (an entry of MATLAB's ``ROIs``).
+ """One imaging path's ROIs (an entry of MATLAB's ROIs).
Attributes
----------
@@ -80,7 +81,7 @@ class PathAnnotations:
The folder of that file when it was annotated.
rois : list of UserRoi
path : int
- The path's number in the file (``Path`` or ``DMD``; 0 if not
+ The path's number in the file (Path or DMD; 0 if not
read from a file).
"""
@@ -91,7 +92,13 @@ class PathAnnotations:
def _text(f: h5py.File, path: str, default: str = "") -> str:
- """A string stored as MATLAB character codes (``uint16``)."""
+ """Read a string stored as MATLAB character codes (uint16).
+
+ Returns
+ -------
+ str
+ The decoded text, or default when path is not in the file.
+ """
if path not in f:
return default
raw = np.asarray(f[path][()])
@@ -103,16 +110,30 @@ def _text(f: h5py.File, path: str, default: str = "") -> str:
return codes.tobytes().decode("utf-16-le", errors="replace")
-def _array(f: h5py.File, path: str) -> Optional[np.ndarray]:
- """A numeric array in MATLAB's orientation, or None."""
+def _array(f: h5py.File, path: str) -> np.ndarray | None:
+ """Read a numeric array in MATLAB's orientation, or None.
+
+ Returns
+ -------
+ np.ndarray or None
+ The array (transposed when it has two or more dimensions), or None
+ when path is not in the file.
+ """
if path not in f:
return None
a = np.asarray(f[path][()])
return a.T if a.ndim >= 2 else a
-def _coords(a: Optional[np.ndarray], zero_indexed: bool):
- """H5 coordinates as ``images.roi`` ``[x, y]`` (one-based)."""
+def _coords(a: np.ndarray | None, zero_indexed: bool) -> np.ndarray | None:
+ """H5 coordinates as images.roi [x, y] (one-based).
+
+ Returns
+ -------
+ np.ndarray or None
+ The [x, y] coordinates, one row per point (a single point is
+ returned as a 1-D [x, y] array), or None when a is None.
+ """
if a is None:
return None
a = np.asarray(a, dtype=np.float64).reshape(-1, 2)
@@ -120,19 +141,31 @@ def _coords(a: Optional[np.ndarray], zero_indexed: bool):
return xy[0] if xy.shape[0] == 1 else xy
-def _scalar(a: Optional[np.ndarray]) -> Optional[float]:
- """First element of an array as a float, or None."""
+def _scalar(a: np.ndarray | None) -> float | None:
+ """First element of an array as a float, or None.
+
+ Returns
+ -------
+ float or None
+ The first element, or None when a is None or empty.
+ """
return None if a is None or a.size == 0 else float(a.ravel()[0])
def _type(raw: str) -> str:
- """The ROI type without MATLAB's ``images.roi.`` prefix."""
+ """Return the ROI type without MATLAB's images.roi. prefix.
+
+ Returns
+ -------
+ str
+ The stripped, lower-case type name.
+ """
t = raw.strip().lower()
- return t[len("images.roi.") :] if t.startswith("images.roi.") else t
+ return t.removeprefix("images.roi.")
-def read_annotations(path) -> list:
- """Read a SILo ``annotations.h5`` (``loadAnnotationsH5.m``).
+def read_annotations(path: str | Path) -> list:
+ """Read a SILo annotations.h5 (loadAnnotationsH5.m).
Parameters
----------
@@ -142,8 +175,8 @@ def read_annotations(path) -> list:
Returns
-------
list of PathAnnotations
- One entry per ``Path`` (or ``DMD``) group, in the order of
- their numbers (``PathAnnotations.path``).
+ One entry per Path (or DMD) group, in the order of
+ their numbers (PathAnnotations.path).
"""
with h5py.File(path, "r") as f:
zero = True
@@ -167,18 +200,12 @@ def read_annotations(path) -> list:
UserRoi(
label=_text(f, f"{r}/label"),
type=_type(_text(f, f"{r}/type")),
- mask=(
- np.zeros((0, 0), bool)
- if mask is None
- else mask.astype(bool)
- ),
+ mask=(np.zeros((0, 0), bool) if mask is None else mask.astype(bool)),
center=_coords(_array(f, f"{r}/center"), zero),
position=_coords(_array(f, f"{r}/position"), zero),
radius=_scalar(_array(f, f"{r}/radius")),
semi_axes=_array(f, f"{r}/semi_axes"),
- rotation_angle=_scalar(
- _array(f, f"{r}/rotation_angle")
- ),
+ rotation_angle=_scalar(_array(f, f"{r}/rotation_angle")),
)
)
out.append(
@@ -192,18 +219,18 @@ def read_annotations(path) -> list:
return out
-def annotation_trial(fn: str, fn_reg_ds: Sequence[str]) -> Optional[int]:
- """The zero-based trial an annotation was drawn on, if it is known.
+def annotation_trial(fn: str, fn_reg_ds: Sequence[str]) -> int | None:
+ """Find the zero-based trial an annotation was drawn on, if it is known.
- As ``roisToConsensusFrame.m``: ``fn`` is matched whole against the
+ As roisToConsensusFrame.m: fn is matched whole against the
stems of the registered files, then without its extension.
Parameters
----------
fn : str
- The annotation's file name (``PathAnnotations.fn``).
+ The annotation's file name (PathAnnotations.fn).
fn_reg_ds : sequence of str
- The path's registered files (trial table ``fn_reg_ds``), in trial
+ The path's registered files (trial table fn_reg_ds), in trial
order.
Returns
@@ -213,20 +240,24 @@ def annotation_trial(fn: str, fn_reg_ds: Sequence[str]) -> Optional[int]:
name = PurePath(str(fn).replace("\\", "/")).name
if not name:
return None
- stems = [
- PurePath(str(f).replace("\\", "/")).stem if f else ""
- for f in fn_reg_ds
- ]
+ stems = [PurePath(str(f).replace("\\", "/")).stem if f else "" for f in fn_reg_ds]
for candidate in (name, PurePath(name).stem):
if candidate in stems:
return stems.index(candidate)
return None
-def _geometry_to_consensus(xy: np.ndarray, warp: TrialWarp, trial: int):
- """``images.roi`` points (``[x, y]``, one-based) of a trial's image in
- the consensus frame, through the inverse of the trial's map (MATLAB's
- ``trialWarpInverse`` in ``roisToConsensusFrame``)."""
+def _geometry_to_consensus(xy: np.ndarray, warp: TrialWarp, trial: int) -> np.ndarray:
+ """images.roi points of a trial's image in the consensus frame.
+
+ The points ([x, y], one-based) are moved through the inverse of the
+ trial's map (MATLAB's trialWarpInverse in roisToConsensusFrame).
+
+ Returns
+ -------
+ np.ndarray
+ The points in the consensus frame, with the shape of xy.
+ """
pts = xy.reshape(-1, 2)
rows, cols = warp.inverse(trial, pts[:, 1] - 1, pts[:, 0] - 1)
moved = np.column_stack([cols + 1, rows + 1])
@@ -239,14 +270,14 @@ def rois_to_consensus(
warp: TrialWarp,
shape: tuple,
) -> list:
- """Move a path's ROIs into the consensus frame (``roisToConsensusFrame``).
+ """Move a path's ROIs into the consensus frame (roisToConsensusFrame).
Each mask is moved by minus its trial's shift, rounded, and cropped or
- padded to ``shape``; geometry (``center``, ``position``) is moved by
+ padded to shape; geometry (center, position) is moved by
the exact shift. Through an affine map or a patchwise field, each
consensus pixel takes the mask's value at the nearest pixel of its
position in the trial, and geometry goes through the map's inverse
- (MATLAB's ``warpRoiData``). If the annotation trial is not in the table
+ (MATLAB's warpRoiData). If the annotation trial is not in the table
or was not aligned, the ROIs are only cropped or padded, with a
warning, as in MATLAB.
@@ -259,7 +290,7 @@ def rois_to_consensus(
warp : TrialWarp
The plan's across-trial alignment.
shape : tuple of int
- ``(rows, cols)`` of the consensus frame.
+ (rows, cols) of the consensus frame.
Returns
-------
@@ -304,7 +335,13 @@ def rois_to_consensus(
def soma_mask(rois: Sequence[UserRoi], shape: tuple) -> np.ndarray:
- """Pixels of the ROIs labelled as somata (SILo's ``somaMask``)."""
+ """Pixels of the ROIs labelled as somata (SILo's somaMask).
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask of shape that is True inside any soma ROI.
+ """
out = np.zeros(tuple(shape), bool)
for roi in rois:
if roi.is_soma and roi.mask.size:
@@ -314,25 +351,23 @@ def soma_mask(rois: Sequence[UserRoi], shape: tuple) -> np.ndarray:
return out
-def session_annotations(
- path: Optional[Path], n_paths: int
-) -> list[Optional[PathAnnotations]]:
+def session_annotations(path: Path | None, n_paths: int) -> list[PathAnnotations | None]:
"""Each path's annotations from a session's file, if there is one.
Parameters
----------
path : Path or None
- ``annotations.h5``; None or a missing file gives no ROIs.
+ annotations.h5; None or a missing file gives no ROIs.
n_paths : int
Imaging paths of the session.
Returns
-------
list of (PathAnnotations or None)
- Index ``d`` holds the annotations of the file's ``Path``;
+ Index d holds the annotations of the file's Path;
None where the file has none for that path. (MATLAB's
- ``loadAnnotationsH5`` numbers the groups it finds in order, which
- is the same for the files its ``saveAnnotationsH5`` writes, with
+ loadAnnotationsH5 numbers the groups it finds in order, which
+ is the same for the files its saveAnnotationsH5 writes, with
every path.)
"""
out: list = [None] * n_paths
diff --git a/src/giant_python/extraction/raster/baseline_map.py b/src/giant_python/extraction/raster/baseline_map.py
index a3b49c8c..d6bb5f4e 100644
--- a/src/giant_python/extraction/raster/baseline_map.py
+++ b/src/giant_python/extraction/raster/baseline_map.py
@@ -1,45 +1,45 @@
"""The F0 network's baseline on the data of source extraction.
-``slap2-f0 predict-registered`` writes one ``_BASELINE-80Hz.h5`` per
+slap2-f0 predict-registered writes one _BASELINE-80Hz.h5 per
trial-path: the baseline of the trial's registered 80 Hz movie, in movie
counts, on the trial's registered frame. Source extraction works at 200 Hz,
at the selected pixels of the path's consensus frame, in counts /
-``photon_scale``
+photon_scale
(:class:`~giant_python.extraction.raster.trial_data.TrialData`).
:func:`map_baseline` carries the one to the other:
1. **Space.** Each selected pixel is sampled at its position in the trial's
- registered frame (``TrialData.trial_rc``: the across-trial map that the
+ registered frame (TrialData.trial_rc: the across-trial map that the
data were read through), bilinearly on the registered frame's pixel
grid (pixel centres at whole numbers, zero-based).
2. **Time.** Linear interpolation in line number, from the lines of the
- registered frames (``DSframes`` of the alignment file) to the lines of
- the extraction's frames (``TrialData.frame_lines``). Extraction frames
+ registered frames (DSframes of the alignment file) to the lines of
+ the extraction's frames (TrialData.frame_lines). Extraction frames
before the first or after the last registered frame take that frame's
value.
-3. **Units.** Division by ``photon_scale``.
+3. **Units.** Division by photon_scale.
Where the network gives no value:
- **Pixels.** The network's baseline is NaN outside the trial's valid
- pixels (those imaged in at least ``1 - nanThresh`` of the frames). A
+ pixels (those imaged in at least 1 - nanThresh of the frames). A
selected pixel is sampled from those of its four neighbours that have a
value, the bilinear weights renormalized, if they carry at least
- ``min_weight`` of the weight (a neighbour outside the registered frame
+ min_weight of the weight (a neighbour outside the registered frame
has none). Otherwise the pixel has no network baseline: it is flagged in
:attr:`MappedBaseline.missing`, and gets the data's own starting baseline
- (``splitFreq``, as MATLAB's solver starts from) when the data are given,
+ (splitFreq, as MATLAB's solver starts from) when the data are given,
or NaN.
- **Frames.** The network gives a value at every registered frame,
including those that SiLo discards for motion (its input is NaN there,
so the value comes from the neighbouring frames). Those values are kept
- unless ``drop_frames`` names the frames. A registered frame at which a
+ unless drop_frames names the frames. A registered frame at which a
pixel has no value (NaN, or dropped) is left out of that pixel's time
interpolation. The extraction's discarded frames hold filled-in data
with a large variance multiplier, so their baseline barely enters the
fits.
-The pipeline (``prepare`` and the streaming run of ``giant silo``) does the
+The pipeline (prepare and the streaming run of giant silo) does the
same in two steps: :func:`read_trial_baseline` (space and units, stored in
the container at the registration's frames) and :func:`subproblem_baseline`
(time and the fallback, per subproblem).
@@ -54,6 +54,7 @@
from dataclasses import dataclass
from pathlib import Path
+from typing import TYPE_CHECKING
import h5py
import numpy as np
@@ -61,32 +62,40 @@
from .solver_baseline import initial_baseline
from .solver_setup import SolverParams
+if TYPE_CHECKING:
+ from .trial_data import TrialData
+
BASELINE_SUFFIX = "_BASELINE-80Hz.h5"
_REGISTERED = "_REGISTERED"
-def baseline_file(baseline_dir, movie_or_stem: str) -> Path:
- """The network baseline file of a trial.
+def baseline_file(baseline_dir: str | Path, movie_or_stem: str) -> Path:
+ """Return the network baseline file of a trial.
Parameters
----------
baseline_dir : str or Path
- Folder of ``slap2-f0 predict-registered``'s outputs.
+ Folder of slap2-f0 predict-registered's outputs.
movie_or_stem : str
The registered movie's file name
- (``_REGISTERED_DOWNSAMPLED-80Hz.h5``) or the trial's stem
- (``E1T1DMD1``).
+ (_REGISTERED_DOWNSAMPLED-80Hz.h5) or the trial's stem
+ (E1T1DMD1).
+
+ Returns
+ -------
+ Path
+ /_BASELINE-80Hz.h5.
"""
name = Path(movie_or_stem).name
stem = name[: name.index(_REGISTERED)] if _REGISTERED in name else name
return Path(baseline_dir) / f"{stem}{BASELINE_SUFFIX}"
-def read_network_baseline(path) -> tuple[np.ndarray, dict]:
- """A network baseline file as ``(frames, rows, cols)`` float32 counts.
+def read_network_baseline(path: str | Path) -> tuple[np.ndarray, dict]:
+ """Read a network baseline file as (frames, rows, cols) float32 counts.
- ``slap2-f0`` writes ``/baseline`` as (frame, MATLAB column, MATLAB
- row), so that MATLAB's ``h5read`` gives SiLo's rows x cols x frames;
+ slap2-f0 writes /baseline as (frame, MATLAB column, MATLAB
+ row), so that MATLAB's h5read gives SiLo's rows x cols x frames;
here it is transposed to (frame, row, col), the orientation of
:func:`~giant_python.extraction.raster.trial.load_registered_trial`'s
movie. NaN outside the trial's valid pixels.
@@ -96,21 +105,25 @@ def read_network_baseline(path) -> tuple[np.ndarray, dict]:
values : ndarray of float32, shape (frames, rows, cols)
attrs : dict
The file's attributes (checkpoint, gain, ...).
+
+ Raises
+ ------
+ ValueError
+ If /baseline is not three-dimensional.
"""
with h5py.File(path, "r") as f:
values = np.asarray(f["baseline"][()], dtype=np.float32)
attrs = {k: f.attrs[k] for k in f.attrs}
if values.ndim != 3:
- raise ValueError(
- f"{path}: /baseline must be (frame, col, row), not "
- f"{values.shape}"
- )
+ raise ValueError(f"{path}: /baseline must be (frame, col, row), not {values.shape}")
return np.ascontiguousarray(values.transpose(0, 2, 1)), attrs
-def read_network_sd(path) -> np.ndarray | None:
- """Optional ``/sd`` dataset of a network baseline file as
- ``(frames, rows, cols)`` float32 counts, or None when absent.
+def read_network_sd(path: str | Path) -> np.ndarray | None:
+ """Read the optional /sd dataset of a network baseline file.
+
+ The dataset is returned as (frames, rows, cols) float32 counts, or
+ None when absent.
Parameters
----------
@@ -120,15 +133,18 @@ def read_network_sd(path) -> np.ndarray | None:
Returns
-------
ndarray of float32, shape (frames, rows, cols), or None
+
+ Raises
+ ------
+ ValueError
+ If /sd is not three-dimensional.
"""
with h5py.File(path, "r") as f:
if "sd" not in f:
return None
values = np.asarray(f["sd"][()], dtype=np.float32)
if values.ndim != 3:
- raise ValueError(
- f"{path}: /sd must be (frame, col, row), not {values.shape}"
- )
+ raise ValueError(f"{path}: /sd must be (frame, col, row), not {values.shape}")
return np.ascontiguousarray(values.transpose(0, 2, 1))
@@ -139,7 +155,7 @@ class MappedBaseline:
Attributes
----------
values : ndarray of float64, shape (pixels, frames)
- Baseline in counts / ``photon_scale`` (the data's units), at the
+ Baseline in counts / photon_scale (the data's units), at the
extraction's frames. Pixels without a network baseline hold the
fallback (or NaN without one).
missing : ndarray of bool, shape (pixels,)
@@ -160,12 +176,12 @@ def sample_bilinear(
min_weight: float = 0.5,
block: int = 2048,
) -> tuple[np.ndarray, np.ndarray]:
- """Sample a ``(frames, rows, cols)`` stack at sub-pixel positions.
+ """Sample a (frames, rows, cols) stack at sub-pixel positions.
Bilinear on the stack's pixel grid; per frame, the neighbours without
a value (NaN, or outside the stack) are left out and the others'
weights renormalized. A sample whose neighbours with a value carry
- less than ``min_weight`` of the weight is NaN.
+ less than min_weight of the weight is NaN.
Parameters
----------
@@ -182,6 +198,12 @@ def sample_bilinear(
values : ndarray of float64, shape (n, frames)
weight : ndarray of float64, shape (n,)
Share of the weight with a value, smallest over frames.
+
+ Raises
+ ------
+ ValueError
+ If min_weight is outside (0, 1], stack is not
+ (frames, rows, cols), or the positions are not finite.
"""
if not 0 < min_weight <= 1:
raise ValueError("min_weight must lie in (0, 1]")
@@ -234,18 +256,43 @@ def sample_spatial(
block: int = 2048,
method: str = "linear",
) -> tuple[np.ndarray, np.ndarray]:
- """Sample a ``(frames, rows, cols)`` stack at sub-pixel positions using
- ``'linear'``, ``'cubic'``, or monotonicity-clamped ``'cubic_clamped'``
- Keys' bicubic interpolation (falling back to :func:`sample_bilinear`
- where any of the 16 bicubic neighbours is NaN or outside the frame)."""
+ """Sample a (frames, rows, cols) stack at sub-pixel positions.
+
+ The interpolation is 'linear', 'cubic', or monotonicity-clamped
+ 'cubic_clamped' Keys' bicubic interpolation (falling back to
+ :func:`sample_bilinear` where any of the 16 bicubic neighbours is NaN
+ or outside the frame).
+
+ Parameters
+ ----------
+ stack : np.ndarray
+ Stack of shape (frames, rows, cols).
+ rc : np.ndarray
+ Zero-based (row, col) positions, shape (n, 2).
+ min_weight : float
+ See :func:`sample_bilinear`.
+ block : int
+ Positions sampled at a time (memory).
+ method : str
+ 'linear', 'cubic', or 'cubic_clamped'.
+
+ Returns
+ -------
+ values : np.ndarray
+ Samples, shape (n, frames).
+ weight : np.ndarray
+ Share of the bilinear weight with a value, smallest over frames,
+ shape (n,).
+
+ Raises
+ ------
+ ValueError
+ If method is not one of the three, or from
+ :func:`sample_bilinear`.
+ """
if method not in ("linear", "cubic", "cubic_clamped"):
- raise ValueError(
- "method must be 'linear', 'cubic', or 'cubic_clamped', not "
- f"{method!r}"
- )
- lin, weight = sample_bilinear(
- stack, rc, min_weight=min_weight, block=block
- )
+ raise ValueError(f"method must be 'linear', 'cubic', or 'cubic_clamped', not {method!r}")
+ lin, weight = sample_bilinear(stack, rc, min_weight=min_weight, block=block)
if method == "linear":
return lin, weight
stack = np.asarray(stack)
@@ -294,7 +341,7 @@ def interp_frames(
dst_lines: np.ndarray,
block: int = 512,
) -> np.ndarray:
- """Linear interpolation in line number, per row of ``values``.
+ """Interpolate linearly in line number, per row of values.
NaN samples are left out of their row's interpolation; destinations
beyond the first or last source line with a value take that value. A
@@ -312,15 +359,18 @@ def interp_frames(
Returns
-------
ndarray of float64, shape (n, frames)
+
+ Raises
+ ------
+ ValueError
+ If values is not (n, sources), or the source lines are not
+ increasing and not empty.
"""
values = np.asarray(values, dtype=np.float64)
src = np.asarray(src_lines, dtype=np.float64).ravel()
dst = np.asarray(dst_lines, dtype=np.float64).ravel()
if values.ndim != 2 or values.shape[1] != src.size:
- raise ValueError(
- f"values are {values.shape}; {src.size} source lines need "
- "(n, sources)"
- )
+ raise ValueError(f"values are {values.shape}; {src.size} source lines need (n, sources)")
if src.size == 0 or np.any(np.diff(src) <= 0):
raise ValueError("source lines must be increasing and not empty")
out = np.full((values.shape[0], dst.size), np.nan)
@@ -353,10 +403,10 @@ def map_baseline(
min_weight: float = 0.5,
drop_frames: np.ndarray | None = None,
fallback_data: np.ndarray | None = None,
- solver_params=None,
+ solver_params: SolverParams | None = None,
spatial_interp: str = "linear",
) -> MappedBaseline:
- """The network's baseline at a trial's selected pixels and frames.
+ """Map the network's baseline to a trial's selected pixels and frames.
Parameters
----------
@@ -365,14 +415,14 @@ def map_baseline(
(:func:`read_network_baseline`).
trial_rc : ndarray of shape (pixels, 2)
Zero-based positions of the selected pixels in the trial's
- registered frame (``TrialData.trial_rc``).
+ registered frame (TrialData.trial_rc).
ds_lines : ndarray of shape (registered frames,)
- One-based line of each registered frame (``DSframes``,
- ``TrialAlignment.ds_frames``).
+ One-based line of each registered frame (DSframes,
+ TrialAlignment.ds_frames).
frame_lines : ndarray of shape (frames,)
- One-based line of each extraction frame (``TrialData.frame_lines``).
+ One-based line of each extraction frame (TrialData.frame_lines).
photon_scale : float
- Counts per unit of the data (``TrialData.photon_scale``).
+ Counts per unit of the data (TrialData.photon_scale).
min_weight : float
Least share of a pixel's bilinear weight that must fall on pixels
with a network value (see :func:`sample_bilinear`).
@@ -380,7 +430,7 @@ def map_baseline(
Registered frames whose network values are not used (they are
interpolated over instead).
fallback_data : ndarray of shape (pixels, frames), optional
- The activity channel's data (``TrialData.y[0]``). Pixels without a
+ The activity channel's data (TrialData.y[0]). Pixels without a
network baseline get its starting baseline
(:func:`~giant_python.extraction.raster.solver_baseline.initial_baseline`).
solver_params : SolverParams, optional
@@ -389,13 +439,22 @@ def map_baseline(
Returns
-------
MappedBaseline
+ The baseline at the selected pixels and extraction frames, the
+ pixels without a network baseline, and the weight of each pixel.
+
+ Raises
+ ------
+ ValueError
+ If the baseline does not match the registration's frames,
+ photon_scale is not positive and finite, drop_frames does
+ not match or drops every registered frame, or fallback_data
+ does not match the baseline.
"""
baseline = np.asarray(baseline)
ds_lines = np.asarray(ds_lines, dtype=np.float64).ravel()
if baseline.ndim != 3 or baseline.shape[0] != ds_lines.size:
raise ValueError(
- f"the baseline is {baseline.shape}; the registration has "
- f"{ds_lines.size} frames"
+ f"the baseline is {baseline.shape}; the registration has {ds_lines.size} frames"
)
if not (photon_scale > 0 and np.isfinite(photon_scale)):
raise ValueError("photon_scale must be positive and finite")
@@ -406,16 +465,13 @@ def map_baseline(
drop = np.asarray(drop_frames, dtype=bool).ravel()
if drop.size != ds_lines.size:
raise ValueError(
- f"drop_frames has {drop.size} frames; the registration has "
- f"{ds_lines.size}"
+ f"drop_frames has {drop.size} frames; the registration has {ds_lines.size}"
)
keep = ~drop
if not keep.any():
raise ValueError("every registered frame is dropped")
if keep.all(): # no copy of the whole movie
- sampled, weight = sample_spatial(
- baseline, trial_rc, min_weight, method=spatial_interp
- )
+ sampled, weight = sample_spatial(baseline, trial_rc, min_weight, method=spatial_interp)
else:
sampled, weight = sample_spatial(
baseline[keep], trial_rc, min_weight, method=spatial_interp
@@ -426,10 +482,7 @@ def map_baseline(
if fallback_data is not None and missing.any():
data = np.asarray(fallback_data, dtype=np.float64)
if data.shape != values.shape:
- raise ValueError(
- f"fallback_data is {data.shape}; the baseline is "
- f"{values.shape}"
- )
+ raise ValueError(f"fallback_data is {data.shape}; the baseline is {values.shape}")
params = solver_params or SolverParams()
values[missing] = initial_baseline(data[missing], params)
return MappedBaseline(values=values, missing=missing, weight=weight)
@@ -453,16 +506,17 @@ def map_baseline(
@dataclass
class TrialBaseline:
- """The network's baseline at a trial's selected pixels, at the
- registration's frames: what a container stores in ``/baseline``.
+ """The network's baseline at a trial's selected pixels, at the registration's frames.
+
+ This is what a container stores in /baseline.
Attributes
----------
values : ndarray of float32, shape (pixels, registered frames)
- Space and units mapped (bilinear at ``TrialData.trial_rc``, divided
- by ``photon_scale``); NaN where a pixel has no network value.
+ Space and units mapped (bilinear at TrialData.trial_rc, divided
+ by photon_scale); NaN where a pixel has no network value.
lines : ndarray of float64, shape (registered frames,)
- One-based line of each registered frame (``DSframes``).
+ One-based line of each registered frame (DSframes).
weight : ndarray of float64, shape (pixels,)
Share of each pixel's bilinear weight on pixels with a value.
identity : dict
@@ -476,8 +530,15 @@ class TrialBaseline:
identity: dict
-def _attr_value(v):
- """An HDF5 attribute as a JSON type."""
+def _attr_value(v: object) -> object:
+ """Convert an HDF5 attribute to a JSON type.
+
+ Returns
+ -------
+ object
+ A str for bytes, a list for an array, a Python scalar for a NumPy
+ scalar; anything else unchanged.
+ """
if isinstance(v, bytes):
return v.decode("utf-8", "replace")
if isinstance(v, np.ndarray):
@@ -488,7 +549,7 @@ def _attr_value(v):
def read_trial_baseline(
- path,
+ path: str | Path,
trial_rc: np.ndarray,
ds_lines: np.ndarray,
photon_scale: float,
@@ -496,7 +557,7 @@ def read_trial_baseline(
min_weight: float = MIN_WEIGHT,
spatial_interp: str = "linear",
) -> TrialBaseline:
- """Space and units of :func:`map_baseline`, from a baseline file.
+ """Read the space and units of :func:`map_baseline` from a baseline file.
Only the part of the file around the pixels is read (every pixel's
four neighbours), so a trial's baseline is not held whole.
@@ -507,9 +568,9 @@ def read_trial_baseline(
The trial's ``*_BASELINE-80Hz.h5``.
trial_rc : ndarray of shape (pixels, 2)
Zero-based positions of the selected pixels in the trial's
- registered frame (``TrialData.trial_rc``).
+ registered frame (TrialData.trial_rc).
ds_lines : ndarray of shape (registered frames,)
- One-based line of each registered frame (``DSframes``).
+ One-based line of each registered frame (DSframes).
photon_scale : float
Counts per unit of the data.
min_weight : float
@@ -518,6 +579,13 @@ def read_trial_baseline(
Returns
-------
TrialBaseline
+
+ Raises
+ ------
+ ValueError
+ If photon_scale is not positive and finite, the registered
+ frames' lines do not increase, the baseline does not match the
+ registration's frames, or the positions are not finite.
"""
path = Path(path)
trial_rc = np.asarray(trial_rc, dtype=np.float64).reshape(-1, 2)
@@ -531,12 +599,9 @@ def read_trial_baseline(
ds = f["baseline"] # (frame, col, row), see read_network_baseline
if ds.ndim != 3 or ds.shape[0] != ds_lines.size:
raise ValueError(
- f"{path}: the baseline is {ds.shape}; the registration has "
- f"{ds_lines.size} frames"
+ f"{path}: the baseline is {ds.shape}; the registration has {ds_lines.size} frames"
)
- attrs = {
- k: _attr_value(f.attrs[k]) for k in _IDENTITY_ATTRS if k in f.attrs
- }
+ attrs = {k: _attr_value(f.attrs[k]) for k in _IDENTITY_ATTRS if k in f.attrs}
n_t, n_c, n_r = ds.shape
if trial_rc.shape[0] == 0:
values = np.zeros((0, n_t), dtype=np.float32)
@@ -577,7 +642,7 @@ def subproblem_baseline(
lines: np.ndarray,
frame_lines: np.ndarray,
data: np.ndarray,
- solver_params=None,
+ solver_params: SolverParams | None = None,
) -> np.ndarray:
"""Time and the fallback of :func:`map_baseline`, for some pixels.
@@ -599,19 +664,20 @@ def subproblem_baseline(
Returns
-------
ndarray of float32, shape (pixels, frames)
- The baseline in the data's units (``Subproblem.baseline``).
+ The baseline in the data's units (Subproblem.baseline).
+
+ Raises
+ ------
+ ValueError
+ If data does not match the baseline.
"""
out = interp_frames(values, lines, frame_lines)
missing = ~np.isfinite(out).any(1)
if missing.any():
data = np.asarray(data, dtype=np.float64)
if data.shape != out.shape:
- raise ValueError(
- f"the data are {data.shape}; the baseline is {out.shape}"
- )
- out[missing] = initial_baseline(
- data[missing], solver_params or SolverParams()
- )
+ raise ValueError(f"the data are {data.shape}; the baseline is {out.shape}")
+ out[missing] = initial_baseline(data[missing], solver_params or SolverParams())
return out.astype(np.float32)
@@ -624,9 +690,25 @@ def _alignment_pooling_stats(
n_t: int,
motion_thresh: float = 2.0,
discard_initial_s: float = 0.0,
-):
- """Retained-frame mask ``keep80``, 80 Hz spatial attenuation ``q80``,
- ``kappa80``, and cropped mean ``varFacDS`` from ``alignment_path``."""
+) -> tuple[np.ndarray, float, float, np.ndarray | None]:
+ """Read the pooling statistics of an alignment file.
+
+ These are the retained-frame mask keep80, 80 Hz spatial attenuation
+ q80, kappa80, and cropped mean varFacDS from
+ alignment_path.
+
+ Returns
+ -------
+ keep80 : np.ndarray
+ Boolean mask of the retained 80 Hz frames, shape (n_t,).
+ q80 : float
+ The 80 Hz spatial attenuation (at least 0.25).
+ kappa80 : float
+ The 80 Hz kappa.
+ vf_box : np.ndarray or None
+ Mean varFacDS over the retained frames, cropped to the box;
+ None if the alignment file has no three-dimensional varFacDS.
+ """
from .trial import discard_frames
q80 = 4.0 / 9.0
@@ -647,9 +729,7 @@ def _alignment_pooling_stats(
if ok_m.any():
fr = np.mod(mr[ok_m], 1.0)
fc = np.mod(mc[ok_m], 1.0)
- q80 = float(
- np.mean(((1 - fr) ** 2 + fr**2) * ((1 - fc) ** 2 + fc**2))
- )
+ q80 = float(np.mean(((1 - fr) ** 2 + fr**2) * ((1 - fc) ** 2 + fc**2)))
if "slap2" in af and "varFacDS" in af["slap2"]:
ds_vf = af["slap2/varFacDS"]
if ds_vf.ndim == 3:
@@ -661,9 +741,9 @@ def _alignment_pooling_stats(
km = keep80[t0:t1]
if not km.any():
continue
- blk = np.asarray(
- ds_vf[t0:t1, c0 : c1 + 1, r0 : r1 + 1], np.float64
- ).transpose(0, 2, 1)[km]
+ blk = np.asarray(ds_vf[t0:t1, c0 : c1 + 1, r0 : r1 + 1], np.float64).transpose(
+ 0, 2, 1
+ )[km]
fin = np.isfinite(blk)
tot_vf += np.where(fin, blk, 0.0).sum(0)
cnt_vf += fin.sum(0)
@@ -673,9 +753,9 @@ def _alignment_pooling_stats(
def apply_trial_sd_finv(
- trial,
- base_path,
- alignment_path,
+ trial: TrialData,
+ base_path: str | Path,
+ alignment_path: str | Path,
tb: TrialBaseline,
*,
min_weight: float = MIN_WEIGHT,
@@ -683,8 +763,17 @@ def apply_trial_sd_finv(
motion_thresh: float = 2.0,
discard_initial_s: float = 0.0,
) -> bool:
- """Scale ``trial.finv`` in place by pooling-deattenuated network ``/sd``
- relative to ``(b + 1) * varFacDS * kappa80`` when ``/sd`` is present."""
+ """Scale trial.finv in place by the network's /sd when it is present.
+
+ The /sd is pooling-deattenuated and taken relative to
+ (b + 1) * varFacDS * kappa80.
+
+ Returns
+ -------
+ bool
+ True if trial.finv was scaled; False if there are no selected
+ pixels, no /sd, or no usable scale.
+ """
base_path = Path(base_path)
n_px = trial.trial_rc.shape[0]
if n_px == 0:
@@ -719,9 +808,7 @@ def apply_trial_sd_finv(
if not km.any():
continue
blk = ds_sd[t0:t1, c0 : c1 + 1, r0 : r1 + 1].transpose(0, 2, 1)[km]
- sd_b, _ = sample_spatial(
- blk, rel_rc, min_weight=min_weight, method=spatial_interp
- )
+ sd_b, _ = sample_spatial(blk, rel_rc, min_weight=min_weight, method=spatial_interp)
fin = np.isfinite(sd_b)
tot_sd2 += np.where(fin, (sd_b**2) * inv_ps2, 0.0).sum(1)
cnt_sd2 += fin.sum(1)
@@ -730,9 +817,7 @@ def apply_trial_sd_finv(
var_pool = np.where(cnt_sd2 > 0, tot_sd2 / cnt_sd2, np.nan) / q80
b_mean = np.nanmean(np.maximum(0.0, b_keep), 1)
if vf_box is not None:
- vf_px, _ = sample_bilinear(
- vf_box[None], rel_rc, min_weight=min_weight
- )
+ vf_px, _ = sample_bilinear(vf_box[None], rel_rc, min_weight=min_weight)
vf_m = vf_px[:, 0]
else:
vf_m = np.nanmedian(trial.finv, axis=1)
diff --git a/src/giant_python/extraction/raster/container.py b/src/giant_python/extraction/raster/container.py
index 47787226..b96aded1 100644
--- a/src/giant_python/extraction/raster/container.py
+++ b/src/giant_python/extraction/raster/container.py
@@ -41,8 +41,8 @@
NaN where a pixel has no network value
/baseline/frame_lines (registered frames,), resizable: their lines
-``/baseline`` has the attributes ``filled`` (0 while empty) and, when
-filled, ``identity`` (JSON: the baseline file and the network's record,
+/baseline has the attributes filled (0 while empty) and, when
+filled, identity (JSON: the baseline file and the network's record,
:class:`~giant_python.extraction.raster.baseline_map.TrialBaseline`). A
subproblem's baseline is interpolated from it to the extraction's frames
(:func:`~giant_python.extraction.raster.baseline_map.subproblem_baseline`)
@@ -53,18 +53,21 @@
import dataclasses
import hashlib
+import itertools
import json
import os
+from collections.abc import Sequence
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Optional, Sequence, Union
+from typing import Any
import h5py
import numpy as np
+from numpy.typing import ArrayLike
from ... import __version__
from .baseline_map import TrialBaseline, subproblem_baseline
-from .solver_setup import Subproblem
+from .solver_setup import SolverParams, Subproblem
from .trial_data import TrialData
__all__ = [
@@ -87,8 +90,14 @@
"""Pixels per chunk of the data (a chunk holds all frames)."""
-def _jsonable(value):
- """A value as JSON types: NumPy to Python, dataclasses to dicts."""
+def _jsonable(value: object) -> object:
+ """Convert a value to JSON types: NumPy to Python, dataclasses to dicts.
+
+ Returns
+ -------
+ object
+ The value made of JSON types (dicts with string keys, lists, Python scalars and strings).
+ """
if dataclasses.is_dataclass(value) and not isinstance(value, type):
value = dataclasses.asdict(value)
if isinstance(value, dict):
@@ -104,7 +113,7 @@ def _jsonable(value):
return value
-def settings_hash(params) -> str:
+def settings_hash(params: object) -> str:
"""SHA-256 of settings, independent of the order of their keys.
Parameters
@@ -138,29 +147,29 @@ class Container:
motion_r, motion_c : ndarray
Motion applied at each frame.
pixel_rc : ndarray of int
- ``(pixels, 2)`` consensus row and column of each pixel.
+ (pixels, 2) consensus row and column of each pixel.
trial_rc : ndarray
- ``(pixels, 2)`` position of each pixel in the registered frame.
+ (pixels, 2) position of each pixel in the registered frame.
sources_rc : ndarray
- ``(sources, 2)`` consensus row and column of the path's sources.
+ (sources, 2) consensus row and column of the path's sources.
subproblem_pixels, subproblem_sources : list of ndarray
Each subproblem's pixels and sources, as indices into the lists.
crops : ndarray of int
- ``(subproblems, 4)`` row0, col0, rows, cols of each crop.
+ (subproblems, 4) row0, col0, rows, cols of each crop.
consensus_shape : tuple
- ``(rows, cols)`` of the consensus frame.
+ (rows, cols) of the consensus frame.
global_f, roi_f, roi_fsvd : ndarray
- The trial's global and user-ROI traces (see ``TrialData``).
+ The trial's global and user-ROI traces (see TrialData).
photon_scale : float
- Counts per unit of ``y``.
+ Counts per unit of y.
params, source : dict
The settings and the caller's record of where the data came from.
code_version, settings_hash : str
- Version of the package that wrote the file; hash of ``params``.
+ Version of the package that wrote the file; hash of params.
baseline_filled : bool
Whether the network's baseline has been written.
baseline_values : ndarray or None
- ``(pixels, registered frames)`` float32: the network's baseline
+ (pixels, registered frames) float32: the network's baseline
(read with the data, when filled).
baseline_lines : ndarray or None
Lines of the registered frames (when filled).
@@ -168,8 +177,8 @@ class Container:
The baseline file and the network's record (when filled).
"""
- y: Optional[np.ndarray]
- finv: Optional[np.ndarray]
+ y: np.ndarray | None
+ finv: np.ndarray | None
frame_lines: np.ndarray
discard: np.ndarray
motion_r: np.ndarray
@@ -190,8 +199,8 @@ class Container:
code_version: str = ""
settings_hash: str = ""
baseline_filled: bool = False
- baseline_values: Optional[np.ndarray] = None
- baseline_lines: Optional[np.ndarray] = None
+ baseline_values: np.ndarray | None = None
+ baseline_lines: np.ndarray | None = None
baseline_identity: dict = field(default_factory=dict)
@property
@@ -199,25 +208,28 @@ def n_subproblems(self) -> int:
"""Number of subproblems."""
return len(self.subproblem_pixels)
- def subproblem(self, k: int, solver_params=None) -> Subproblem:
- """Subproblem ``k`` (zero-based) of a container read with its data.
+ def subproblem(self, k: int, solver_params: SolverParams | None = None) -> Subproblem:
+ """Subproblem k (zero-based) of a container read with its data.
Parameters
----------
k : int
solver_params : SolverParams, optional
- The solver's parameters. When their ``baseline_mode`` uses an
+ The solver's parameters. When their baseline_mode uses an
external baseline, the subproblem gets the network's
(:func:`~.baseline_map.subproblem_baseline`).
+ Returns
+ -------
+ Subproblem
+ The subproblem's data, pixels and sources, with the network's baseline when the solver
+ parameters need one.
+
Raises
------
ValueError
If the container was read without its data, or has no network
baseline for a mode that needs one.
- IndexError
- If ``k`` is not one of the subproblems (negative indices are
- not accepted, as when reading from the file).
"""
if self.y is None:
raise ValueError("the container was read without its data")
@@ -252,22 +264,37 @@ def subproblem(self, k: int, solver_params=None) -> Subproblem:
)
-def _uses_baseline(solver_params) -> bool:
- """Whether a solver's baseline mode reads ``Subproblem.baseline``."""
- return (
- solver_params is not None
- and getattr(solver_params, "baseline_mode", "fit") != "fit"
- )
+def _uses_baseline(solver_params: SolverParams | None) -> bool:
+ """Whether a solver's baseline mode reads Subproblem.baseline.
+
+ Returns
+ -------
+ bool
+ True when solver_params is given and its baseline_mode is not "fit".
+ """
+ return solver_params is not None and getattr(solver_params, "baseline_mode", "fit") != "fit"
def _check_index(k: int, n: int) -> None:
- """Reject an index that is not one of ``n`` subproblems."""
+ """Reject an index that is not one of n subproblems.
+
+ Raises
+ ------
+ IndexError
+ If k is not in 0..n - 1.
+ """
if not 0 <= k < n:
raise IndexError(f"subproblem {k} is not one of {n}")
def crop_of(pixel_rc: np.ndarray) -> np.ndarray:
- """Bounding box ``[row0, col0, rows, cols]`` of pixels."""
+ """Bounding box [row0, col0, rows, cols] of pixels.
+
+ Returns
+ -------
+ np.ndarray
+ The four values [row0, col0, rows, cols]; zeros for no pixels.
+ """
if pixel_rc.shape[0] == 0:
return np.zeros(4, dtype=np.int64)
lo, hi = pixel_rc.min(0), pixel_rc.max(0)
@@ -275,9 +302,23 @@ def crop_of(pixel_rc: np.ndarray) -> np.ndarray:
def _subproblem(
- y, finv, pixel_rc, sources_rc, pixels, sources, crop, baseline=None
-):
- """Assemble a :class:`Subproblem` from its rows and index lists."""
+ y: np.ndarray,
+ finv: np.ndarray,
+ pixel_rc: np.ndarray,
+ sources_rc: np.ndarray,
+ pixels: np.ndarray,
+ sources: np.ndarray,
+ crop: np.ndarray,
+ baseline: np.ndarray | None = None,
+) -> Subproblem:
+ """Assemble a :class:`Subproblem` from its rows and index lists.
+
+ Returns
+ -------
+ Subproblem
+ The subproblem, with sel the mask of its pixels in the crop and the sources' positions
+ relative to the crop's corner.
+ """
row0, col0, rows, cols = (int(v) for v in crop)
sel = np.zeros((rows, cols), dtype=bool)
sel[pixel_rc[:, 0] - row0, pixel_rc[:, 1] - col0] = True
@@ -294,8 +335,19 @@ def _subproblem(
)
-def _index_list(values, k: int, what: str) -> np.ndarray:
- """One subproblem's indices as integers; whole numbers only."""
+def _index_list(values: ArrayLike, k: int, what: str) -> np.ndarray:
+ """One subproblem's indices as integers; whole numbers only.
+
+ Returns
+ -------
+ np.ndarray
+ The indices as a flat int64 array.
+
+ Raises
+ ------
+ ValueError
+ If the values are not whole numbers.
+ """
a = np.asarray(values).ravel()
if a.size == 0:
return np.zeros(0, dtype=np.int64)
@@ -307,8 +359,21 @@ def _index_list(values, k: int, what: str) -> np.ndarray:
return a.astype(np.int64)
-def _ragged(lists, n_max: int, what: str):
- """Concatenated index lists and their offsets, checked."""
+def _ragged(lists: Sequence[ArrayLike], n_max: int, what: str) -> tuple[np.ndarray, np.ndarray]:
+ """Concatenated index lists and their offsets, checked.
+
+ Returns
+ -------
+ flat : np.ndarray
+ The index lists concatenated (int32).
+ offsets : np.ndarray
+ Where each list starts in flat, and the total length (int64, one more than lists).
+
+ Raises
+ ------
+ ValueError
+ If a list has an index outside 0..n_max - 1 or does not strictly increase.
+ """
lists = [_index_list(v, k, what) for k, v in enumerate(lists)]
for k, v in enumerate(lists):
if v.size and (v.min() < 0 or v.max() >= n_max):
@@ -320,15 +385,23 @@ def _ragged(lists, n_max: int, what: str):
return flat.astype(np.int32), offsets.astype(np.int64)
-def _data_kwargs(shape, chunk_pixels, compression, compression_opts):
- """Chunking and filter of a ``(..., pixels, frames)`` dataset."""
+def _data_kwargs(
+ shape: tuple[int, ...],
+ chunk_pixels: int,
+ compression: str | None,
+ compression_opts: int | None,
+) -> dict[str, Any]:
+ """Chunking and filter of a (..., pixels, frames) dataset.
+
+ Returns
+ -------
+ dict
+ The h5py dataset keywords (chunks and, with a filter, compression,
+ compression_opts and shuffle); empty for a dataset without pixels or frames.
+ """
if shape[-2] == 0 or shape[-1] == 0:
return {}
- chunks = (
- (1,) * (len(shape) - 2)
- + (min(chunk_pixels, shape[-2]),)
- + (shape[-1],)
- )
+ chunks = (1,) * (len(shape) - 2) + (min(chunk_pixels, shape[-2]),) + (shape[-1],)
kwargs = {"chunks": chunks}
if compression:
kwargs.update(
@@ -340,18 +413,18 @@ def _data_kwargs(shape, chunk_pixels, compression, compression_opts):
def write_container(
- path,
+ path: str | Path,
trial: TrialData,
- sources_rc,
+ sources_rc: ArrayLike,
subproblem_pixels: Sequence,
subproblem_sources: Sequence,
- consensus_shape,
- params=None,
- source: Optional[dict] = None,
- compression: Optional[str] = COMPRESSION,
- compression_opts=None,
+ consensus_shape: Sequence[int],
+ params: object | None = None,
+ source: dict | None = None,
+ compression: str | None = COMPRESSION,
+ compression_opts: int | None = None,
chunk_pixels: int = CHUNK_PIXELS,
- baseline: Optional[TrialBaseline] = None,
+ baseline: TrialBaseline | None = None,
) -> Path:
"""Write one trial-path's container.
@@ -366,11 +439,11 @@ def write_container(
trial : TrialData
The trial's data from :func:`~.trial_data.load_trial`.
sources_rc : array_like
- ``(sources, 2)`` zero-based consensus row and column of the path's
+ (sources, 2) zero-based consensus row and column of the path's
sources.
subproblem_pixels, subproblem_sources : sequence of array_like
Each subproblem's pixels (increasing indices into the trial's
- selected-pixel list) and sources (indices into ``sources_rc``).
+ selected-pixel list) and sources (indices into sources_rc).
consensus_shape : (int, int)
Rows and columns of the consensus frame.
params : dict or dataclass, optional
@@ -381,10 +454,10 @@ def write_container(
compression : {"lzf", "gzip", None}
Filter of the data (with byte shuffling). On a 780125 trial-path
(13909 pixels, 5633 frames, 897 MB in memory) the default, LZF,
- gives 597 MB in 4 s; ``"gzip"`` (level ``compression_opts`` 1 to 4)
+ gives 597 MB in 4 s; "gzip" (level compression_opts 1 to 4)
544 to 528 MB in 17 to 23 s; None 901 MB in 1 s.
compression_opts : int, optional
- Level for ``"gzip"``.
+ Level for "gzip".
chunk_pixels : int
Pixels per chunk; a chunk holds all frames of its pixels, so a
subproblem is read as the few chunks around its pixels (small
@@ -392,7 +465,7 @@ def write_container(
baseline : TrialBaseline, optional
The network's baseline at the trial's pixels
(:func:`~.baseline_map.read_trial_baseline`), written to
- ``/baseline``.
+ /baseline.
Returns
-------
@@ -412,18 +485,12 @@ def write_container(
raise ValueError("one source list is needed per subproblem")
if baseline is not None and baseline.values.shape[0] != n_px:
raise ValueError(
- f"the baseline has {baseline.values.shape[0]} pixels; the trial "
- f"has {n_px}"
+ f"the baseline has {baseline.values.shape[0]} pixels; the trial has {n_px}"
)
pix_flat, pix_off = _ragged(subproblem_pixels, n_px, "pixels")
- src_flat, src_off = _ragged(
- subproblem_sources, sources_rc.shape[0], "sources"
- )
+ src_flat, src_off = _ragged(subproblem_sources, sources_rc.shape[0], "sources")
crops = np.array(
- [
- crop_of(trial.pixel_rc[pix_flat[a:b]])
- for a, b in zip(pix_off[:-1], pix_off[1:])
- ],
+ [crop_of(trial.pixel_rc[pix_flat[a:b]]) for a, b in itertools.pairwise(pix_off)],
dtype=np.int32,
).reshape(-1, 4)
params = _jsonable(params or {})
@@ -435,18 +502,14 @@ def write_container(
f.attrs["code_version"] = __version__
f.attrs["settings_hash"] = settings_hash(params)
f.attrs["params"] = json.dumps(params, sort_keys=True)
- f.attrs["source"] = json.dumps(
- _jsonable(source or {}), sort_keys=True
- )
+ f.attrs["source"] = json.dumps(_jsonable(source or {}), sort_keys=True)
f.attrs["photon_scale"] = float(trial.photon_scale)
f.attrs["consensus_shape"] = np.asarray(consensus_shape, np.int64)
for name, a in (("y", trial.y), ("finv", trial.finv)):
f.create_dataset(
f"data/{name}",
data=np.asarray(a, dtype=np.float32),
- **_data_kwargs(
- a.shape, chunk_pixels, compression, compression_opts
- ),
+ **_data_kwargs(a.shape, chunk_pixels, compression, compression_opts),
)
f["frames/lines"] = np.asarray(trial.frame_lines, np.int64)
f["frames/discard"] = np.asarray(trial.discard, np.uint8)
@@ -463,9 +526,7 @@ def write_container(
f["traces/global_f"] = trial.global_f
f["traces/roi_f"] = trial.roi_f
f["traces/roi_fsvd"] = trial.roi_fsvd
- _reserve_baseline(
- f, n_px, chunk_pixels, compression, compression_opts
- )
+ _reserve_baseline(f, n_px, chunk_pixels, compression, compression_opts)
if baseline is not None:
_write_baseline(f["baseline"], baseline)
os.replace(tmp, path)
@@ -476,7 +537,13 @@ def write_container(
return path
-def _reserve_baseline(f, n_px, chunk_pixels, compression, compression_opts):
+def _reserve_baseline(
+ f: h5py.File,
+ n_px: int,
+ chunk_pixels: int,
+ compression: str | None,
+ compression_opts: int | None,
+) -> None:
"""Create the empty, resizable datasets of the network's baseline."""
g = f.create_group("baseline")
kwargs = {}
@@ -497,52 +564,60 @@ def _reserve_baseline(f, n_px, chunk_pixels, compression, compression_opts):
fillvalue=np.nan,
**kwargs,
)
- g.create_dataset(
- "frame_lines", shape=(0,), maxshape=(None,), dtype=np.float64
- )
+ g.create_dataset("frame_lines", shape=(0,), maxshape=(None,), dtype=np.float64)
g.attrs["filled"] = 0
g.attrs["units"] = "counts / photon_scale"
-def _write_baseline(g, baseline: TrialBaseline) -> None:
- """Fill the reserved datasets with the network's baseline."""
+def _write_baseline(g: h5py.Group, baseline: TrialBaseline) -> None:
+ """Fill the reserved datasets with the network's baseline.
+
+ Raises
+ ------
+ ValueError
+ If the baseline's frame count differs from its number of lines.
+ """
values = np.asarray(baseline.values, dtype=np.float32)
lines = np.asarray(baseline.lines, dtype=np.float64).ravel()
if values.shape[1] != lines.size:
- raise ValueError(
- f"the baseline has {values.shape[1]} frames and {lines.size} "
- "lines"
- )
+ raise ValueError(f"the baseline has {values.shape[1]} frames and {lines.size} lines")
g["values"].resize(values.shape)
g["values"][...] = values
g["frame_lines"].resize(lines.shape)
g["frame_lines"][...] = lines
g.attrs["filled"] = 1
- g.attrs["identity"] = json.dumps(
- _jsonable(baseline.identity), sort_keys=True
- )
+ g.attrs["identity"] = json.dumps(_jsonable(baseline.identity), sort_keys=True)
+
+def _check_format(f: h5py.File) -> None:
+ """Reject files that are not containers of a version this code reads.
-def _check_format(f) -> None:
- """Reject files that are not containers of a version this code reads."""
+ Raises
+ ------
+ ValueError
+ If the file is not a SILo container or its format version is newer than this code reads.
+ """
if f.attrs.get("format") != FORMAT:
raise ValueError(f"{f.filename} is not a SILo container")
version = int(f.attrs["format_version"])
if version > FORMAT_VERSION:
raise ValueError(
- f"{f.filename} has container format {version}; this code reads "
- f"up to {FORMAT_VERSION}"
+ f"{f.filename} has container format {version}; this code reads up to {FORMAT_VERSION}"
)
def _split(flat: np.ndarray, offsets: np.ndarray) -> list:
- """The index lists of concatenated lists and their offsets."""
- return [
- flat[a:b].astype(np.int64) for a, b in zip(offsets[:-1], offsets[1:])
- ]
+ """Split concatenated lists into index lists by their offsets.
+
+ Returns
+ -------
+ list
+ One int64 index array per list.
+ """
+ return [flat[a:b].astype(np.int64) for a, b in itertools.pairwise(offsets)]
-def read_container(path, data: bool = True) -> Container:
+def read_container(path: str | Path, data: bool = True) -> Container:
"""Read a container.
Parameters
@@ -550,7 +625,7 @@ def read_container(path, data: bool = True) -> Container:
path : str or Path
The container.
data : bool
- Read ``y`` and ``finv`` too (they are most of the file). Without
+ Read y and finv too (they are most of the file). Without
them, :func:`read_subproblem` reads single subproblems from the
file.
@@ -573,12 +648,8 @@ def read_container(path, data: bool = True) -> Container:
pixel_rc=f["pixels/consensus_rc"][()].astype(np.int64),
trial_rc=f["pixels/trial_rc"][()],
sources_rc=f["sources/rc"][()],
- subproblem_pixels=_split(
- sub["pixel_index"][()], sub["pixel_offset"][()]
- ),
- subproblem_sources=_split(
- sub["source_index"][()], sub["source_offset"][()]
- ),
+ subproblem_pixels=_split(sub["pixel_index"][()], sub["pixel_offset"][()]),
+ subproblem_sources=_split(sub["source_index"][()], sub["source_offset"][()]),
crops=sub["crop"][()].astype(np.int64),
consensus_shape=tuple(int(v) for v in f.attrs["consensus_shape"]),
global_f=f["traces/global_f"][()],
@@ -593,19 +664,22 @@ def read_container(path, data: bool = True) -> Container:
baseline_values=g["values"][()] if filled and data else None,
baseline_lines=g["frame_lines"][()] if filled else None,
baseline_identity=(
- json.loads(g.attrs["identity"])
- if filled and "identity" in g.attrs
- else {}
+ json.loads(g.attrs["identity"]) if filled and "identity" in g.attrs else {}
),
)
-def _read_rows(ds, rows: np.ndarray) -> np.ndarray:
+def _read_rows(ds: h5py.Dataset, rows: np.ndarray) -> np.ndarray:
"""Rows of the pixel axis (second to last) of a dataset.
The span of the rows is read in one piece and indexed in memory: a
subproblem's pixels lie close together in the list, and HDF5 reads a
contiguous span much faster than a list of rows.
+
+ Returns
+ -------
+ np.ndarray
+ The dataset's data at rows of the pixel axis.
"""
if rows.size == 0:
return ds[..., :0, :]
@@ -614,11 +688,11 @@ def _read_rows(ds, rows: np.ndarray) -> np.ndarray:
def read_subproblem(
- container: Union[Container, str, Path, h5py.File],
+ container: Container | str | Path | h5py.File,
k: int,
- solver_params=None,
+ solver_params: SolverParams | None = None,
) -> Subproblem:
- """Subproblem ``k`` of a container, in the shared convention.
+ """Subproblem k of a container, in the shared convention.
Parameters
----------
@@ -633,6 +707,11 @@ def read_subproblem(
Returns
-------
Subproblem
+
+ Raises
+ ------
+ ValueError
+ If the solver's baseline mode needs a network baseline that the container does not have.
"""
if isinstance(container, Container):
return container.subproblem(k, solver_params)
diff --git a/src/giant_python/extraction/raster/kinetics.py b/src/giant_python/extraction/raster/kinetics.py
index 4249bff2..1582fe93 100644
--- a/src/giant_python/extraction/raster/kinetics.py
+++ b/src/giant_python/extraction/raster/kinetics.py
@@ -1,11 +1,11 @@
"""SILo's kinetics test: sources whose transients are faster than the sensor.
-Port of GIAnT-MATLAB's ``sourceKinetics.m`` and ``rejectFastSources.m``
+Port of GIAnT-MATLAB's sourceKinetics.m and rejectFastSources.m
(main 5a0673b). Each source's strongest transients in its least-squares
trace (activity channel, pooled over trials) are averaged, and the average
one decay time constant after the peak, relative to the peak, is divided by
-the sensor's ``exp(-1)``: about 1 for the sensor's kinetics, about 0 for
-one- or two-frame transients. Sources scoring below ``min_kinetic_score``
+the sensor's exp(-1): about 1 for the sensor's kinetics, about 0 for
+one- or two-frame transients. Sources scoring below min_kinetic_score
are removed after extraction.
An evidence test can remove, with them, sources whose extracted activity is
@@ -14,14 +14,14 @@
the kinetics test cannot judge, since a source with fewer than
:data:`MIN_EVENTS` events gets no score and is kept.
-Traces are ``(sources, frames)`` per trial, NaN at discarded frames, as
-SILo's ``E{t}.dF.ls(:, :, 1)``.
+Traces are (sources, frames) per trial, NaN at discarded frames, as
+SILo's E{t}.dF.ls(:, :, 1).
"""
from __future__ import annotations
+from collections.abc import Sequence
from dataclasses import dataclass
-from typing import Optional, Sequence
import numpy as np
from scipy.signal import lfilter, peak_prominences
@@ -34,12 +34,17 @@
def movmean_omitnan(x: np.ndarray, window: int) -> np.ndarray:
- """MATLAB ``movmean(x, window, 2, 'omitnan')`` along the last axis.
+ """MATLAB movmean(x, window, 2, 'omitnan') along the last axis.
- The window holds ``floor(window / 2)`` samples before and
- ``ceil(window / 2) - 1`` after each sample (centred for odd windows),
+ The window holds floor(window / 2) samples before and
+ ceil(window / 2) - 1 after each sample (centred for odd windows),
shrunk at the ends; NaN are left out, and a window with no number gives
NaN.
+
+ Returns
+ -------
+ np.ndarray
+ The moving mean, the shape of x.
"""
x = np.asarray(x, dtype=np.float64)
n = x.shape[-1]
@@ -58,15 +63,25 @@ def movmean_omitnan(x: np.ndarray, window: int) -> np.ndarray:
def _plateaus(y: np.ndarray) -> list:
- """Local maxima of one row as MATLAB's ``islocalmax`` finds them.
+ """Local maxima of one row as MATLAB's islocalmax finds them.
A run of equal values is a maximum if both its neighbours are lower.
- The first and last samples are never maxima. Returns ``(first, last,
- mark)`` of each maximum's run, where ``mark`` is its centre (the left
+ The first and last samples are never maxima. Returns (first, last,
+ mark) of each maximum's run, where mark is its centre (the left
one of the two centres of a run of even length).
- ``y`` must be one row (:func:`islocalmax` passes each row); anything
+ y must be one row (:func:`islocalmax` passes each row); anything
else is a ValueError.
+
+ Returns
+ -------
+ list
+ (first, last, mark) of each maximum's run, as described above.
+
+ Raises
+ ------
+ ValueError
+ If y is not one row.
"""
if np.ndim(y) != 1:
raise ValueError(f"one row is needed; got shape {np.shape(y)}")
@@ -84,10 +99,10 @@ def _plateaus(y: np.ndarray) -> list:
def islocalmax(y: np.ndarray, min_separation: float = 0) -> np.ndarray:
- """MATLAB ``islocalmax(y, 2, 'MinSeparation', s)`` for each row.
+ """MATLAB islocalmax(y, 2, 'MinSeparation', s) for each row.
With a minimum separation, maxima are taken from left to right; one
- closer than ``min_separation`` samples to the last maximum kept (from
+ closer than min_separation samples to the last maximum kept (from
the end of that maximum's run of equal values to the start of its
own) replaces it if it is more prominent and is dropped otherwise.
This reproduces MATLAB R2024b on rows with and without runs of equal
@@ -105,7 +120,7 @@ def islocalmax(y: np.ndarray, min_separation: float = 0) -> np.ndarray:
Returns
-------
- ndarray of bool, the shape of ``y``
+ ndarray of bool, the shape of y
"""
y = np.asarray(y, dtype=np.float64)
rows = np.atleast_2d(y)
@@ -131,9 +146,9 @@ def islocalmax(y: np.ndarray, min_separation: float = 0) -> np.ndarray:
def source_kinetics(
- traces: Sequence[Optional[np.ndarray]], tau_s: float, analyze_hz: float
+ traces: Sequence[np.ndarray | None], tau_s: float, analyze_hz: float
) -> tuple[np.ndarray, np.ndarray]:
- """Kinetics score of each source (``sourceKinetics.m``).
+ """Kinetics score of each source (sourceKinetics.m).
Each trial's trace is high-passed (moving mean over 1 s or 10 tau,
whichever is longer) and filtered with the sensor's decay (an
@@ -157,15 +172,13 @@ def source_kinetics(
Returns
-------
score : ndarray of shape (sources,)
- ``(avg(L) / avg(0)) / exp(-L / tau)`` with ``L = round(tau)``
- frames; NaN for sources with fewer than 5 events or when ``L`` is
+ (avg(L) / avg(0)) / exp(-L / tau) with L = round(tau)
+ frames; NaN for sources with fewer than 5 events or when L is
under 3 frames.
n_events : ndarray of int, shape (sources,)
Events averaged per source.
"""
- present = [
- np.asarray(t, dtype=np.float64) for t in traces if t is not None
- ]
+ present = [np.asarray(t, dtype=np.float64) for t in traces if t is not None]
present = [t for t in present if t.size]
n_src = present[0].shape[0] if present else 0
score = np.full(n_src, np.nan)
@@ -209,11 +222,7 @@ def source_kinetics(
if lo < 0 or hi > n_t - 1:
continue
q = lo + int(np.argmax(x[s, lo : hi + 1]))
- if (
- q + lag > n_t - 1
- or not valid[s, q]
- or not valid[s, q + lag]
- ):
+ if q + lag > n_t - 1 or not valid[s, q] or not valid[s, q + lag]:
continue
sum0[s] += x[s, q]
sum_l[s] += x[s, q + lag]
@@ -225,7 +234,7 @@ def source_kinetics(
@dataclass
class KineticsTest:
- """Result of the kinetics test (``rejectFastSources``).
+ """Result of the kinetics test (rejectFastSources).
Attributes
----------
@@ -250,19 +259,19 @@ class KineticsTest:
keep: np.ndarray
score: np.ndarray
n_events: np.ndarray
- weak: Optional[np.ndarray] = None
- snr: Optional[np.ndarray] = None
- event_rate: Optional[np.ndarray] = None
- seed_height: Optional[np.ndarray] = None
+ weak: np.ndarray | None = None
+ snr: np.ndarray | None = None
+ event_rate: np.ndarray | None = None
+ seed_height: np.ndarray | None = None
@property
def kept_score(self) -> np.ndarray:
- """Scores of the kept sources (MATLAB's ``kinetics.score``)."""
+ """Scores of the kept sources (MATLAB's kinetics.score)."""
return self.score[self.keep]
@property
def kept_n_events(self) -> np.ndarray:
- """Event counts of the kept sources (``kinetics.nEvents``)."""
+ """Event counts of the kept sources (kinetics.nEvents)."""
return self.n_events[self.keep]
@property
@@ -272,15 +281,15 @@ def rejected(self) -> np.ndarray:
def reject_fast_sources(
- traces: Sequence[Optional[np.ndarray]],
+ traces: Sequence[np.ndarray | None],
n_sources: int,
tau_s: float,
analyze_hz: float,
min_kinetic_score: float,
) -> KineticsTest:
- """Which sources the kinetics test keeps (``rejectFastSources.m``).
+ """Which sources the kinetics test keeps (rejectFastSources.m).
- Sources scoring below ``min_kinetic_score`` are removed when it is
+ Sources scoring below min_kinetic_score are removed when it is
above 0; sources that cannot be scored (NaN) are kept. The removed
sources were fitted together with the kept ones, so the kept sources'
traces are those of the joint fit.
@@ -312,15 +321,19 @@ def reject_fast_sources(
return KineticsTest(keep=keep, score=score, n_events=n_events)
-def mean_snr(
- snrs: Sequence[Optional[np.ndarray]], n_sources: int
-) -> np.ndarray:
- """Each source's SNR averaged over the trials that have one.
+def mean_snr(snrs: Sequence[np.ndarray | None], n_sources: int) -> np.ndarray:
+ """Compute each source's SNR averaged over the trials that have one.
- ``snrs`` holds each trial's per-source SNR (the solver's: the SD of the
- denoised activity over its noise, ``TrialActivity.snr``), or None for a
+ snrs holds each trial's per-source SNR (the solver's: the SD of the
+ denoised activity over its noise, TrialActivity.snr), or None for a
trial without sources; NaN where no trial has one. Only NaN is left
- out, as in the summary's ``SNR`` (an infinite SNR stays infinite).
+ out, as in the summary's SNR (an infinite SNR stays infinite).
+
+ Returns
+ -------
+ np.ndarray
+ The mean SNR of each source, shape (n_sources,); NaN where no
+ trial has one.
"""
total = np.zeros(n_sources)
count = np.zeros(n_sources)
@@ -336,11 +349,13 @@ def mean_snr(
def source_minutes(
- traces: Sequence[Optional[np.ndarray]], n_sources: int, analyze_hz: float
+ traces: Sequence[np.ndarray | None], n_sources: int, analyze_hz: float
) -> np.ndarray:
- """Minutes of each source's trace in which the kinetics test looks for
- events: its frames that were not discarded (not NaN) in the trials with
- traces (as for :func:`source_kinetics`), at ``analyze_hz``.
+ """Return the minutes of each source's trace that the kinetics test searches.
+
+ The kinetics test looks for events in each source's frames that were not
+ discarded (not NaN) in the trials with traces (as for
+ :func:`source_kinetics`), at analyze_hz.
Returns
-------
@@ -361,11 +376,11 @@ def weak_sources(
min_snr: float = 0.0,
min_event_rate: float = 0.0,
) -> np.ndarray:
- """Sources whose extracted activity is too weak (the evidence test).
+ """Return the sources whose extracted activity is too weak (the evidence test).
A source is weak when its SNR averaged over trials (:func:`mean_snr`) is
- below ``min_snr`` or when the kinetics test found fewer than
- ``min_event_rate`` events per minute of its trace (its events,
+ below min_snr or when the kinetics test found fewer than
+ min_event_rate events per minute of its trace (its events,
:func:`source_kinetics`, over :func:`source_minutes`); 0 turns either
criterion off. A rate rather than a count, so that the criterion means
the same in short and long recordings. A source without an SNR or a
@@ -377,6 +392,11 @@ def weak_sources(
Returns
-------
ndarray of bool, shape (sources,)
+
+ Raises
+ ------
+ ValueError
+ If min_snr or min_event_rate is negative.
"""
if min_snr < 0 or min_event_rate < 0:
raise ValueError("min_snr and min_event_rate must be nonnegative")
diff --git a/src/giant_python/extraction/raster/localization.py b/src/giant_python/extraction/raster/localization.py
index 5e59edcd..4850a1bf 100644
--- a/src/giant_python/extraction/raster/localization.py
+++ b/src/giant_python/extraction/raster/localization.py
@@ -1,16 +1,16 @@
"""Multi-ROI (raster) SiLo localization of one trial.
-Port of GIAnT-MATLAB's ``localizeSources_vIM.m`` (main at 9695d27), with an
+Port of GIAnT-MATLAB's localizeSources_vIM.m (main at 9695d27), with an
optional external baseline (GIAnT-MATLAB branch
-``localization-network-baseline``: the F0 network's ``*_BASELINE-80Hz.h5``).
+localization-network-baseline: the F0 network's ``*_BASELINE-80Hz.h5``).
One trial's movie, NaN where a pixel was not imaged or a frame was discarded,
becomes an activity image:
1. a baseline (the moving median of the 8-frame-smoothed movie, or the external
- one), and a Z-score against a variance model ``Vk b v + Vb`` fitted to the
+ one), and a Z-score against a variance model Vk b v + Vb fitted to the
first 500 frames;
2. the anticausal exponential filter of the sensor's decay in time;
-3. a Gaussian of ``sigma_px`` minus a Gaussian 5x as wide (the DoG) in space;
+3. a Gaussian of sigma_px minus a Gaussian 5x as wide (the DoG) in space;
4. the sum, over the frames in which a pixel is a local maximum in space (3x3)
and time, of the squared filtered value, divided by the number of
observations plus 300.
@@ -21,20 +21,20 @@
Options, all off by default (:class:`RasterLocalizationParams`):
-* ``surround=False`` keeps the Gaussian alone (no DoG surround), meant for an
+* surround=False keeps the Gaussian alone (no DoG surround), meant for an
unbiased baseline such as the F0 network's.
-* ``null="bootstrap"`` calibrates the activity image per pixel brightness with
+* null="bootstrap" calibrates the activity image per pixel brightness with
noise movies of the trial's baseline, gain, noise correlations and skew put
through the same filters (:mod:`giant_python.extraction.raster.null`), so
that one threshold means one false-positive rate on dim and bright pixels.
-* ``variance_floor=False`` drops ``Vb`` from the Z-score's variance (meant with
+* variance_floor=False drops Vb from the Z-score's variance (meant with
the bootstrap null, which handles the dim pixels). It needs an external
baseline: the moving median is biased low at low counts.
-* ``score="soft_threshold"`` sums ``max(0, u - soft_th)^2`` at the local maxima
- instead of their squares, with ``u`` the filtered value in robust SD units,
+* score="soft_threshold" sums max(0, u - soft_th)^2 at the local maxima
+ instead of their squares, with u the filtered value in robust SD units,
so noise maxima add nothing.
-Arrays are ``(frames, rows, cols)``: MATLAB's ``rows x cols x frames`` with the
+Arrays are (frames, rows, cols): MATLAB's rows x cols x frames with the
frame axis first. Rows and columns are those of the registered TIFF.
"""
@@ -44,13 +44,17 @@
import operator
import warnings
from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
import numpy as np
-import scipy.ndimage as ndimage
from numpy.lib.stride_tricks import sliding_window_view
+from scipy import ndimage
from .peaks import get_act_im_peaks
+if TYPE_CHECKING:
+ from .trial import PixelReader
+
_NULLS = ("none", "bootstrap")
_SCORES = ("squared_maxima", "soft_threshold")
@@ -62,44 +66,44 @@ class RasterLocalizationParams:
Attributes
----------
align_hz : float
- Frame rate of the registered movie (``alignHz``).
+ Frame rate of the registered movie (alignHz).
tau_s : float
- Decay time constant of the sensor (``tau_s``).
+ Decay time constant of the sensor (tau_s).
sigma_px : float
- Gaussian sigma of the PSF in pixels (``sigma_px``).
+ Gaussian sigma of the PSF in pixels (sigma_px).
baseline_window_s : float
- Moving-median window of the baseline (``baselineWindow_Glu_s``).
+ Moving-median window of the baseline (baselineWindow_Glu_s).
denoise_window_s : float
Twice the moving-mean window of the variance model
- (``denoiseWindow_s``).
+ (denoiseWindow_s).
vif : float
- Variance inflation factor of the floor ``Vb`` (``VIF``).
+ Variance inflation factor of the floor Vb (VIF).
peak_th : float
- Seed threshold in robust SDs of the summary image (``peakth``).
+ Seed threshold in robust SDs of the summary image (peakth).
min_peak_distance : int
- Minimum Chebyshev distance of residual seeds (``minPeakDistance``).
+ Minimum Chebyshev distance of residual seeds (minPeakDistance).
nan_thresh : float
- Largest fraction of NaN frames of an included pixel (``nanThresh``).
+ Largest fraction of NaN frames of an included pixel (nanThresh).
surround : bool
Subtract the 5-sigma surround (DoG); False keeps the Gaussian alone.
null : str
- ``"none"`` or ``"bootstrap"`` (per-brightness null calibration).
+ "none" or "bootstrap" (per-brightness null calibration).
null_draws : int
Noise movies per trial for the bootstrap null.
null_seed : int
- Seed of the first noise movie (draw ``k`` uses ``null_seed + k``).
+ Seed of the first noise movie (draw k uses null_seed + k).
null_scale : str
- Calibration per brightness: ``"tail"`` (median and 99.5th percentile)
- or ``"sd"`` (mean and SD).
+ Calibration per brightness: "tail" (median and 99.5th percentile)
+ or "sd" (mean and SD).
variance_floor : bool
- Add ``Vb`` to the Z-score's variance model.
+ Add Vb to the Z-score's variance model.
score : str
- ``"squared_maxima"`` or ``"soft_threshold"``.
+ "squared_maxima" or "soft_threshold".
soft_th : float
Threshold of the soft-threshold score, in robust SD units.
use_baseline_sd : bool
- Use ``baseline_sd`` when provided to :func:`localize_sources` or
- present as ``/sd`` in ``*_BASELINE-80Hz.h5`` (:func:`localize_trial`).
+ Use baseline_sd when provided to :func:`localize_sources` or
+ present as /sd in ``*_BASELINE-80Hz.h5`` (:func:`localize_trial`).
"""
align_hz: float = 80.0
@@ -122,7 +126,13 @@ class RasterLocalizationParams:
use_baseline_sd: bool = True
def __post_init__(self) -> None:
- """Validate the option values."""
+ """Validate the option values.
+
+ Raises
+ ------
+ ValueError
+ If an option is outside its allowed values.
+ """
for name in (
"align_hz",
"tau_s",
@@ -134,15 +144,11 @@ def __post_init__(self) -> None:
if not getattr(self, name) > 0:
raise ValueError(f"{name} must be positive")
if self.null not in _NULLS:
- raise ValueError(
- f"null must be one of {_NULLS}, not {self.null!r}"
- )
+ raise ValueError(f"null must be one of {_NULLS}, not {self.null!r}")
if self.null_scale not in ("tail", "sd"):
raise ValueError("null_scale must be 'tail' or 'sd'")
if self.score not in _SCORES:
- raise ValueError(
- f"score must be one of {_SCORES}, not {self.score!r}"
- )
+ raise ValueError(f"score must be one of {_SCORES}, not {self.score!r}")
if (
isinstance(self.null_draws, bool)
or not isinstance(self.null_draws, (int, np.integer))
@@ -167,17 +173,17 @@ class RasterLocalization:
Attributes
----------
act_im : ndarray of shape (rows, cols)
- The activity image (MATLAB's ``skIm``), NaN outside the valid pixels;
+ The activity image (MATLAB's skIm), NaN outside the valid pixels;
calibrated (null mean 0, SD 1 per brightness) with the bootstrap null.
summary : ndarray of shape (rows, cols)
The scaled activity image minus its 5x5 NaN-median (what is seeded).
peaks : ndarray of shape (N, 4)
- ``[amplitude, row, col, sigma]`` of the seeds at ``peak_th``
+ [amplitude, row, col, sigma] of the seeds at peak_th
(0-based), or None when peaks were not requested.
valid : ndarray of bool
- Pixels imaged in at least ``1 - nan_thresh`` of the frames.
+ Pixels imaged in at least 1 - nan_thresh of the frames.
info : dict
- ``Vk``, ``Vb``, the soft-threshold scale ``sd_u``, and with the
+ Vk, Vb, the soft-threshold scale sd_u, and with the
bootstrap null the noise model and calibration.
"""
@@ -194,19 +200,29 @@ class RasterLocalization:
def movmean_nan(x: np.ndarray, window: int) -> np.ndarray:
- """MATLAB ``smoothdata(x, 1, 'movmean', window, 'omitnan')`` (axis 0).
+ """MATLAB smoothdata(x, 1, 'movmean', window, 'omitnan') (axis 0).
- Even windows reach ``window/2`` frames back and ``window/2 - 1`` ahead, as
+ Even windows reach window/2 frames back and window/2 - 1 ahead, as
MATLAB's; the window shrinks at the ends; NaN where it holds no value.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ Movie or array, frames along axis 0.
+ window : int
+ Window length in frames.
+
+ Returns
+ -------
+ np.ndarray
+ The moving mean, of the shape and dtype of x.
"""
back = window // 2 if window % 2 == 0 else (window - 1) // 2
ahead = window - 1 - back
ok = ~np.isnan(x)
zero = np.zeros((1,) + x.shape[1:])
# float64 prefix sums: float32 ones drift over a long recording
- s = np.concatenate(
- [zero, np.cumsum(np.where(ok, x, 0.0), axis=0, dtype=np.float64)]
- )
+ s = np.concatenate([zero, np.cumsum(np.where(ok, x, 0.0), axis=0, dtype=np.float64)])
c = np.concatenate([zero, np.cumsum(ok, axis=0, dtype=np.float64)])
n = x.shape[0]
hi = np.minimum(np.arange(n) + ahead + 1, n)
@@ -217,31 +233,48 @@ def movmean_nan(x: np.ndarray, window: int) -> np.ndarray:
def movmedian_nan(x: np.ndarray, window: int) -> np.ndarray:
- """MATLAB ``smoothdata(x, 1, 'movmedian', window, 'omitnan')`` (axis 0).
+ """MATLAB smoothdata(x, 1, 'movmedian', window, 'omitnan') (axis 0).
The median of the non-NaN values in each window (the mean of the two middle
ones for an even count), window placement as in :func:`movmean_nan`; NaN
where the window holds no value.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ Movie or array, frames along axis 0.
+ window : int
+ Window length in frames.
+
+ Returns
+ -------
+ np.ndarray
+ The moving median, of the shape and dtype of x.
"""
import bottleneck as bn
back = window // 2 if window % 2 == 0 else (window - 1) // 2
ahead = window - 1 - back
pad_shape = lambda k: (k,) + x.shape[1:] # noqa: E731
- padded = np.concatenate(
- [
- np.full(pad_shape(back), np.nan, x.dtype),
- x,
- np.full(pad_shape(ahead), np.nan, x.dtype),
- ]
- )
+ padded = np.concatenate([
+ np.full(pad_shape(back), np.nan, x.dtype),
+ x,
+ np.full(pad_shape(ahead), np.nan, x.dtype),
+ ])
# a trailing window ending at padded frame t + window - 1 is centred on t
med = bn.move_median(padded, window, min_count=1, axis=0)
return med[window - 1 : window - 1 + x.shape[0]].astype(x.dtype)
def matlab_prctile(x: np.ndarray, p: float) -> float:
- """MATLAB ``prctile(x, p, 'all')``: NaN ignored, midpoint interpolation."""
+ """MATLAB prctile(x, p, 'all'): NaN ignored, midpoint interpolation.
+
+ Returns
+ -------
+ float
+ The p-th percentile of the non-NaN values of x, NaN when there
+ are none.
+ """
x = np.asarray(x, dtype=np.float64)
x = x[~np.isnan(x)]
if x.size == 0:
@@ -250,7 +283,13 @@ def matlab_prctile(x: np.ndarray, p: float) -> float:
def _nanvar1(x: np.ndarray) -> np.ndarray:
- """MATLAB ``var(x, 0, 1, 'omitmissing')`` (N-1, or N for one value)."""
+ """MATLAB var(x, 0, 1, 'omitmissing') (N-1, or N for one value).
+
+ Returns
+ -------
+ np.ndarray
+ Variance along axis 0 of the non-NaN values, NaN where there are none.
+ """
ok = ~np.isnan(x)
n = ok.sum(0)
x64 = np.where(ok, x, 0.0).astype(np.float64)
@@ -263,7 +302,13 @@ def _nanvar1(x: np.ndarray) -> np.ndarray:
def gaussian_kernel(sigma: float) -> np.ndarray:
- """MATLAB ``imgaussfilt``'s 1-D kernel: radius ceil(2 sigma), sum 1."""
+ """MATLAB imgaussfilt's 1-D kernel: radius ceil(2 sigma), sum 1.
+
+ Returns
+ -------
+ np.ndarray
+ The normalised Gaussian kernel, of length 2 * ceil(2 * sigma) + 1.
+ """
r = math.ceil(2 * sigma)
x = np.arange(-r, r + 1, dtype=np.float64)
h = np.exp(-(x**2) / (2 * sigma**2))
@@ -271,9 +316,14 @@ def gaussian_kernel(sigma: float) -> np.ndarray:
def gauss_filter(stack: np.ndarray, sigma: float) -> np.ndarray:
- """MATLAB ``imgaussfilt(stack, [sigma sigma])`` of each frame.
+ """MATLAB imgaussfilt(stack, [sigma sigma]) of each frame.
Separable, replicate padding; frames are axis 0.
+
+ Returns
+ -------
+ np.ndarray
+ The filtered stack, of the shape of stack.
"""
h = gaussian_kernel(sigma)
out = ndimage.correlate1d(stack, h, axis=1, mode="nearest")
@@ -281,14 +331,14 @@ def gauss_filter(stack: np.ndarray, sigma: float) -> np.ndarray:
def nanmedfilt2(a: np.ndarray, size: int = 5) -> np.ndarray:
- """GIAnT's ``nanmedfilt2``: the median of each window's non-NaN values.
+ """GIAnT's nanmedfilt2: the median of each window's non-NaN values.
NaN padding at the border; NaN where the window has no value.
Only the windows that hold a value are sorted: a SLAP2 frame is imaged
at a few percent of its pixels, and the windows away from them (most of
the frame) are NaN whatever is done with them. Such a window gives the
- plain ``np.nan``. Taking ``np.nanmedian`` along the last axis of all
+ plain np.nan. Taking np.nanmedian along the last axis of all
windows at once, as this function did before, gives the same bits for
windows of fewer than 600 elements (sides up to 23); for larger ones
that call can hand on the bits of a NaN of the window.
@@ -299,11 +349,20 @@ def nanmedfilt2(a: np.ndarray, size: int = 5) -> np.ndarray:
size : int
Side of the window, odd.
+ Returns
+ -------
+ np.ndarray
+ The median filter of a, of its shape, NaN where the window has no
+ value.
+
Raises
------
ValueError
- If ``size`` is not a positive odd whole number, or ``a`` is not a
+ If size is not a positive odd whole number, or a is not a
two-dimensional image.
+ TypeError
+ If size is a boolean (raised inside, and handled as an invalid
+ size).
"""
try:
if isinstance(size, (bool, np.bool_)):
@@ -339,6 +398,11 @@ def temporal_filter(imf: np.ndarray, tau: float) -> np.ndarray:
"""SiLo's anticausal exponential filter, in place (frames are axis 0).
A NaN frame value carries the filter's memory forward, as in MATLAB.
+
+ Returns
+ -------
+ np.ndarray
+ imf, filtered in place.
"""
gamma = np.float32(np.exp(-1.0 / tau))
one_minus = np.float32(1.0 - np.exp(-1.0 / tau))
@@ -353,7 +417,13 @@ def temporal_filter(imf: np.ndarray, tau: float) -> np.ndarray:
def _robust_scale(imf: np.ndarray, last: int) -> float:
- """1.4826 x MAD of the scored frames' filtered values (subsampled)."""
+ """1.4826 x MAD of the scored frames' filtered values (subsampled).
+
+ Returns
+ -------
+ float
+ The robust scale, 1.0 when there are no values or the MAD is 0.
+ """
x = imf[1:last].reshape(-1)
if x.size > 60_000_000: # sample before copying (most voxels are NaN)
x = x[:: int(np.ceil(x.size / 60_000_000))]
@@ -374,10 +444,16 @@ def activity_score(
) -> tuple[np.ndarray, float | None]:
"""Activity image of a Z-scored, high-passed movie (filters and score).
- ``imf`` (frames, rows, cols; NaN at ``nans``) is overwritten. Returns the
- activity image (MATLAB's ``skIm`` before masking) and the scale ``sd_u`` of
- the soft-threshold score (None for squared maxima). Passing ``sd_u`` reuses
- a trial's scale, so that its null movies go through the same function.
+ imf (frames, rows, cols; NaN at nans) is overwritten. Passing
+ sd_u reuses a trial's scale, so that its null movies go through the
+ same function.
+
+ Returns
+ -------
+ activity_image : np.ndarray
+ The activity image (MATLAB's skIm before masking).
+ sd_u : float or None
+ The scale of the soft-threshold score (None for squared maxima).
"""
tau = params.tau_frames
temporal_filter(imf, tau)
@@ -409,9 +485,16 @@ def _score_maxima(
params: RasterLocalizationParams,
sd_u: float | None,
) -> np.ndarray:
- """Sum over frames ``1 .. last-1`` of the squared values at the local
+ """Sum the squared values at the local maxima of a filtered movie.
+
+ The sum runs over frames 1 .. last-1 of the squared values at the local
maxima in space (3x3) and time of a filtered movie (NaN where not
- observed); with the soft-threshold score, of ``max(0, u - soft_th)^2``.
+ observed); with the soft-threshold score, of max(0, u - soft_th)^2.
+
+ Returns
+ -------
+ np.ndarray
+ The summed score image, of shape (rows, cols).
"""
soft = params.score == "soft_threshold"
sk = np.zeros(imf.shape[1:], dtype=np.float64)
@@ -421,22 +504,26 @@ def _score_maxima(
b = min(last, a + block) # frames a .. b-1, with neighbours
cur = imf[a:b]
is_max = (
- (cur == _max3x3(cur))
- & (cur > imf[a - 1 : b - 1])
- & (cur >= imf[a + 1 : b + 1])
+ (cur == _max3x3(cur)) & (cur > imf[a - 1 : b - 1]) & (cur >= imf[a + 1 : b + 1])
)
v = np.where(is_max, cur, 0).astype(np.float64)
if soft:
- v = np.where(
- is_max, np.maximum(0.0, v / sd_u - params.soft_th), 0.0
- )
+ v = np.where(is_max, np.maximum(0.0, v / sd_u - params.soft_th), 0.0)
sk += (v**2).sum(0)
return sk
def filter_reach(params: RasterLocalizationParams) -> int:
- """Pixels over which the spatial filters and the 3x3 maximum carry a
- value: the Gaussian's radius, the surround's, and one."""
+ """Return the pixels over which the spatial filters carry a value.
+
+ That is, the pixels over which the spatial filters and the 3x3 maximum
+ carry a value: the Gaussian's radius, the surround's, and one.
+
+ Returns
+ -------
+ int
+ The reach in pixels.
+ """
reach = math.ceil(2 * params.sigma_px)
if params.surround:
reach += math.ceil(2 * 5 * params.sigma_px)
@@ -444,9 +531,16 @@ def filter_reach(params: RasterLocalizationParams) -> int:
def _block_tiles(valid: np.ndarray, block: int) -> list[tuple]:
- """Rectangles of the occupied blocks of a ``block`` px grid: joined along
- rows, rows of equal column extent joined, each shrunk to its valid
- pixels."""
+ """Return the rectangles of the occupied blocks of a block px grid.
+
+ The blocks are joined along rows, rows of equal column extent joined, each
+ shrunk to its valid pixels.
+
+ Returns
+ -------
+ list[tuple]
+ Rectangles (r0, r1, c0, c1) covering the valid pixels.
+ """
rows, cols = valid.shape
rr, cc = np.nonzero(valid)
occ = np.zeros((-(-rows // block), -(-cols // block)), bool)
@@ -456,9 +550,7 @@ def _block_tiles(valid: np.ndarray, block: int) -> list[tuple]:
runs = set()
if br < occ.shape[0]:
edge = np.diff(np.r_[0, occ[br].astype(np.int8), 0])
- runs = set(
- zip(np.flatnonzero(edge == 1), np.flatnonzero(edge == -1))
- )
+ runs = set(zip(np.flatnonzero(edge == 1), np.flatnonzero(edge == -1)))
for run in [k for k in open_ if k not in runs]:
tiles.append((open_.pop(run), br, run[0], run[1]))
for run in runs:
@@ -476,26 +568,40 @@ def _block_tiles(valid: np.ndarray, block: int) -> list[tuple]:
def score_tiles(
valid: np.ndarray, margin: int, tile_cost: int = 2000
) -> list[tuple[int, int, int, int]]:
- """Rectangles ``(r0, r1, c0, c1)`` that together hold every valid pixel
- once, chosen so that the rectangles grown by ``margin`` cover little
- area.
+ """Return rectangles that together hold every valid pixel once.
+
+ The rectangles (r0, r1, c0, c1) are chosen so that the rectangles grown
+ by margin cover little area.
The scan images a few percent of the frame (the ROIs); the filters of
- :func:`activity_score_tiled` run on each rectangle grown by ``margin``
+ :func:`activity_score_tiled` run on each rectangle grown by margin
instead of on the whole frame. Of the single bounding box and the
tilings of a few block sizes (:func:`_block_tiles`), the one of the
- least grown area (plus ``tile_cost`` pixels per rectangle, for its
+ least grown area (plus tile_cost pixels per rectangle, for its
overhead) is returned. The result of the score does not depend on the
tiling.
+
+ Returns
+ -------
+ list[tuple[int, int, int, int]]
+ The rectangles (r0, r1, c0, c1); empty when there is no valid
+ pixel.
"""
rows, cols = valid.shape
if not valid.any():
return []
- def cost(tiles):
- """Sum over the tiles of each tile's area with its margin, cut to
- the frame (pixels in two tiles count twice), plus the fixed cost of
- each tile."""
+ def cost(tiles: list[tuple[int, int, int, int]]) -> int:
+ """Return the summed area of the tiles with their margins.
+
+ Each tile's area with its margin is cut to the frame (pixels in two
+ tiles count twice), plus the fixed cost of each tile.
+
+ Returns
+ -------
+ int
+ The summed area plus the fixed cost of each tile.
+ """
area = 0
for r0, r1, c0, c1 in tiles:
h = min(rows, r1 + margin) - max(0, r0 - margin)
@@ -519,11 +625,11 @@ def activity_score_tiled(
) -> np.ndarray:
""":func:`activity_score` from the valid pixels alone, the same values.
- ``y`` (frames, valid pixels; in the row-major order of ``valid``) is the
- Z-scored, high-passed movie at the valid pixels, NaN at ``nan_v``; it may
+ y (frames, valid pixels; in the row-major order of valid) is the
+ Z-scored, high-passed movie at the valid pixels, NaN at nan_v; it may
be overwritten. The filter in time runs per pixel, so on the valid pixels
only. The filters in space see zeros outside the observed samples and
- reach ``filter_reach`` pixels, so they run on rectangles around the
+ reach filter_reach pixels, so they run on rectangles around the
valid pixels (:func:`score_tiles`) grown by that reach: every value that
enters the score is the sum of the same terms in the same order as on
the whole frame. For the squared-maxima score (the soft threshold takes
@@ -534,11 +640,14 @@ def activity_score_tiled(
ndarray of shape (rows, cols)
The activity image, 0 outside the valid pixels as
:func:`activity_score`'s.
+
+ Raises
+ ------
+ ValueError
+ If the score is not the squared-maxima score.
"""
if params.score != "squared_maxima":
- raise ValueError(
- "activity_score_tiled is for the squared-maxima score"
- )
+ raise ValueError("activity_score_tiled is for the squared-maxima score")
tau = params.tau_frames
n_t = y.shape[0]
rows, cols = valid.shape
@@ -573,9 +682,7 @@ def activity_score_tiled(
# its pixels (the frame's own border keeps its zero padding)
s0, s1 = max(a0, r0 - 1), min(a1, r1 + 1)
t0, t1 = max(b0, c0 - 1), min(b1, c1 + 1)
- part = _score_maxima(
- imf[:, s0 - a0 : s1 - a0, t0 - b0 : t1 - b0], last, params, None
- )
+ part = _score_maxima(imf[:, s0 - a0 : s1 - a0, t0 - b0 : t1 - b0], last, params, None)
own = valid[r0:r1, c0:c1]
sk[r0:r1, c0:c1][own] = part[r0 - s0 : r1 - s0, c0 - t0 : c1 - t0][own]
del imf
@@ -588,53 +695,50 @@ def _max3x3(stack: np.ndarray) -> np.ndarray:
"""``ordfilt2(frame, 9, ones(3))`` of each frame (axis 0).
The 3x3 maximum with zero padding, NaN where the neighbourhood holds a NaN.
+
+ Returns
+ -------
+ np.ndarray
+ The 3x3 maximum of each frame, of the shape of stack.
"""
nan = np.isnan(stack)
out = ndimage.maximum_filter(
np.where(nan, -np.inf, stack), size=(1, 3, 3), mode="constant", cval=0
)
- nan_win = ndimage.maximum_filter(
- nan, size=(1, 3, 3), mode="constant", cval=False
- )
+ nan_win = ndimage.maximum_filter(nan, size=(1, 3, 3), mode="constant", cval=False)
out[nan_win] = np.nan
return out
def check_inputs(
- shape: tuple,
+ shape: tuple[int, ...],
params: RasterLocalizationParams,
- baseline=None,
- var_factor=None,
- baseline_sd=None,
+ baseline: np.ndarray | PixelReader | None = None,
+ var_factor: np.ndarray | PixelReader | None = None,
+ baseline_sd: np.ndarray | PixelReader | None = None,
) -> None:
"""Reject inputs :func:`localize_sources` cannot use (before any retry).
Raises
------
ValueError
- If ``variance_floor=False`` has no external baseline, if
- ``baseline_sd`` is given without ``baseline``, or if the baseline,
+ If variance_floor=False has no external baseline, if
+ baseline_sd is given without baseline, or if the baseline,
its SD, or the variance factor does not have the movie's shape.
"""
if var_factor is not None and np.shape(var_factor) != tuple(shape):
- raise ValueError(
- f"var_factor is {np.shape(var_factor)}, the movie {shape}"
- )
+ raise ValueError(f"var_factor is {np.shape(var_factor)}, the movie {shape}")
if not params.variance_floor and baseline is None:
# the moving median is biased low at low counts (often 0), so without
# the floor dim pixels' Z-scores blow up (4x lower AP on simulations)
raise ValueError("variance_floor=False needs an external baseline")
if baseline is not None and np.shape(baseline) != tuple(shape):
- raise ValueError(
- f"external baseline is {np.shape(baseline)}, the movie {shape}"
- )
+ raise ValueError(f"external baseline is {np.shape(baseline)}, the movie {shape}")
if baseline_sd is not None:
if baseline is None:
raise ValueError("baseline_sd needs an external baseline")
if np.shape(baseline_sd) != tuple(shape):
- raise ValueError(
- f"baseline_sd is {np.shape(baseline_sd)}, the movie {shape}"
- )
+ raise ValueError(f"baseline_sd is {np.shape(baseline_sd)}, the movie {shape}")
def _network_std(
@@ -648,17 +752,24 @@ def _network_std(
) -> tuple[np.ndarray, np.ndarray, float]:
"""Frame-scaled network noise SD, variance, and single-frame floor.
- Scales ``bsd`` by ``sqrt(vf_raw_t / mean_t(vf_raw))`` using the
+ Scales bsd by sqrt(vf_raw_t / mean_t(vf_raw)) using the
unsmoothed per-frame variance factor so brief motion/sampling spikes
modulate the single-frame noise prediction, and optionally adds the
- single-frame 10th-percentile variance floor ``vif * prctile(var_1, 10)``
+ single-frame 10th-percentile variance floor vif * prctile(var_1, 10)
in quadrature.
+
+ Returns
+ -------
+ std : np.ndarray
+ The frame-scaled network noise SD.
+ net_var : np.ndarray
+ The frame-scaled network noise variance.
+ vb_sd : float
+ The single-frame variance floor (0 without the floor).
"""
ok_vf = np.isfinite(vf_raw)
cnt_vf = ok_vf.sum(axis=0)
- vf_sum = np.where(ok_vf, vf_raw, np.float32(0)).sum(
- axis=0, dtype=np.float64
- )
+ vf_sum = np.where(ok_vf, vf_raw, np.float32(0)).sum(axis=0, dtype=np.float64)
del ok_vf
with np.errstate(invalid="ignore", divide="ignore"):
vf_mean = np.where(cnt_vf > 0, vf_sum / cnt_vf, np.nan)
@@ -674,11 +785,7 @@ def _network_std(
bad = (~nan_v) & (~np.isfinite(net_var) | ~(net_var > 0))
if bad.any():
good = (~nan_v) & ~bad & (fallback_var > 0)
- scale = (
- float(np.nanmedian(net_var[good] / fallback_var[good]))
- if good.any()
- else 1.0
- )
+ scale = float(np.nanmedian(net_var[good] / fallback_var[good])) if good.any() else 1.0
net_var = np.where(bad, np.float32(scale) * fallback_var, net_var)
net_var = np.fmax(np.float32(0), net_var)
net_var[nan_v] = np.nan
@@ -695,12 +802,19 @@ def _network_std(
return std, net_var, vb_sd
-def _at_pixels(a, n_frames: int, vidx: np.ndarray) -> np.ndarray:
- """``a`` (frames, rows, cols) at the pixels ``vidx`` (row-major), as a
- new float32 array (frames, pixels). ``a`` is an array, or an object that
- reads the pixels from a file (``at_pixels``:
+def _at_pixels(a: np.ndarray | PixelReader, n_frames: int, vidx: np.ndarray) -> np.ndarray:
+ """Return a (frames, rows, cols) at the pixels vidx (row-major).
+
+ The result is a new float32 array (frames, pixels). a is an array, or
+ an object that reads the pixels from a file (at_pixels:
:class:`~giant_python.extraction.raster.trial.PixelReader`), so that the
- whole frames are never in memory."""
+ whole frames are never in memory.
+
+ Returns
+ -------
+ np.ndarray
+ The values at vidx, of shape (frames, pixels).
+ """
if hasattr(a, "at_pixels"):
return a.at_pixels(vidx)
a = np.asarray(a)
@@ -708,7 +822,13 @@ def _at_pixels(a, n_frames: int, vidx: np.ndarray) -> np.ndarray:
def summary_image(act_im: np.ndarray, valid: np.ndarray) -> np.ndarray:
- """The image SiLo seeds in: scaled, minus its 5x5 NaN-median."""
+ """Return the image SiLo seeds in: scaled, minus its 5x5 NaN-median.
+
+ Returns
+ -------
+ np.ndarray
+ The summary image, NaN outside valid.
+ """
s = np.array(act_im, dtype=np.float64)
top = np.nanmax(s) if np.isfinite(s).any() else np.nan
if top > 0:
@@ -719,20 +839,25 @@ def summary_image(act_im: np.ndarray, valid: np.ndarray) -> np.ndarray:
return s
-def _left_out(shape2d, find_peaks: bool, reason) -> RasterLocalization:
- """The localization of a trial left out of seeding: no valid pixels, a
- NaN activity image (as a trial without valid pixels; SILo's valid trials
- then leave it out). Used when the bootstrap null cannot be measured, e.g.
- for a trial of a single frame."""
+def _left_out(shape2d: tuple[int, ...], find_peaks: bool, reason: object) -> RasterLocalization:
+ """Return the localization of a trial left out of seeding.
+
+ It has no valid pixels and a NaN activity image (as a trial without valid
+ pixels; SILo's valid trials then leave it out). Used when the bootstrap
+ null cannot be measured, e.g. for a trial of a single frame.
+
+ Returns
+ -------
+ RasterLocalization
+ The localization with a NaN activity image and no valid pixels.
+ """
warnings.warn(f"Trial left out of localization: {reason}")
empty = np.full(shape2d, np.nan)
peaks = np.zeros((0, 4)) if find_peaks else None
- return RasterLocalization(
- empty, empty.copy(), peaks, np.zeros(shape2d, bool)
- )
+ return RasterLocalization(empty, empty.copy(), peaks, np.zeros(shape2d, bool))
-def localize_sources( # noqa: C901
+def localize_sources(
movie: np.ndarray,
var_factor: np.ndarray | None = None,
params: RasterLocalizationParams | None = None,
@@ -741,19 +866,19 @@ def localize_sources( # noqa: C901
*,
find_peaks: bool = True,
) -> RasterLocalization:
- """Localize sources in one trial (port of ``localizeSources_vIM``).
+ """Localize sources in one trial (port of localizeSources_vIM).
Parameters
----------
movie : ndarray of shape (frames, rows, cols)
The trial's activity channel, NaN where not imaged or discarded; or
- an object that holds it at its imaged pixels (``shape``,
- ``valid_pixels``, ``at_pixels``:
+ an object that holds it at its imaged pixels (shape,
+ valid_pixels, at_pixels:
:class:`~giant_python.extraction.raster.trial.SparseMovie`).
var_factor : ndarray of the same shape, optional
- SLAP2's variance factor (``varFacDS``); ones for raster imaging. It,
- ``baseline`` and ``baseline_sd`` may be objects with ``shape`` and
- ``at_pixels`` (read from a file at the valid pixels only).
+ SLAP2's variance factor (varFacDS); ones for raster imaging. It,
+ baseline and baseline_sd may be objects with shape and
+ at_pixels (read from a file at the valid pixels only).
params : RasterLocalizationParams, optional
Parameters and options (defaults: GIAnT-MATLAB's SLAP2 SiLo).
baseline : ndarray of the same shape, optional
@@ -761,14 +886,21 @@ def localize_sources( # noqa: C901
replaces the moving median in the high-pass and the variance model.
baseline_sd : ndarray of the same shape, optional
External single-frame noise SD in the movie's units (the F0 network's
- ``/sd``); when ``params.use_baseline_sd`` is True, scales by
- ``sqrt(var_factor_t / mean_t(var_factor))`` to form the Z-score SD.
+ /sd); when params.use_baseline_sd is True, scales by
+ sqrt(var_factor_t / mean_t(var_factor)) to form the Z-score SD.
find_peaks : bool
- Seed sources at ``params.peak_th`` (MATLAB's ``P``).
+ Seed sources at params.peak_th (MATLAB's P).
Returns
-------
RasterLocalization
+ The localization of the trial.
+
+ Raises
+ ------
+ ValueError
+ If the inputs cannot be used (see :func:`check_inputs`), or no
+ positive noise variance remains without the variance floor.
"""
p = params or RasterLocalizationParams()
sparse = hasattr(movie, "valid_pixels") # the movie at its imaged pixels
@@ -800,11 +932,7 @@ def localize_sources( # noqa: C901
# as the one on whole frames; the soft threshold takes its scale from
# the whole filtered movie
tiled = p.score == "squared_maxima"
- vf = (
- np.ones(y.shape, np.float32)
- if var_factor is None
- else _at_pixels(var_factor, n_t, vidx)
- )
+ vf = np.ones(y.shape, np.float32) if var_factor is None else _at_pixels(var_factor, n_t, vidx)
nan_v = np.isnan(y)
vf[nan_v] = np.nan
@@ -842,9 +970,7 @@ def localize_sources( # noqa: C901
sel_bright = var_pred > top
if not sel_bright.any(): # uniform brightness: MATLAB's Vk is NaN
sel_bright = var_pred >= top
- vk = matlab_prctile(
- (var_im[sel_bright] - vb / p.vif) / var_pred[sel_bright], 10
- )
+ vk = matlab_prctile((var_im[sel_bright] - vb / p.vif) / var_pred[sel_bright], 10)
if not p.variance_floor and not vk > 0:
# without the floor nothing else keeps the variance positive
vk = float(np.nanmedian(var_im / var_pred))
@@ -857,9 +983,7 @@ def localize_sources( # noqa: C901
bsd_v[nan_v] = np.nan
with np.errstate(invalid="ignore"):
fb_var = np.fmax(np.float32(0), np.float32(vk) * imb * vf)
- std, net_var, vb_sd = _network_std(
- bsd_v, vf_raw, y, first, nan_v, fb_var, p
- )
+ std, net_var, vb_sd = _network_std(bsd_v, vf_raw, y, first, nan_v, fb_var, p)
info["sd_source"] = "network"
info["Vb_sd"] = vb_sd
del bsd_v, fb_var
@@ -879,10 +1003,7 @@ def localize_sources( # noqa: C901
if not use_sd:
with np.errstate(invalid="ignore"):
- std = np.sqrt(
- np.fmax(np.float32(0), np.float32(vk) * imb * vf)
- + np.float32(vb_used)
- )
+ std = np.sqrt(np.fmax(np.float32(0), np.float32(vk) * imb * vf) + np.float32(vb_used))
if not p.variance_floor:
guard = 0.01 * np.nanmedian(std[~nan_v])
if not guard > 0:
@@ -929,9 +1050,5 @@ def localize_sources( # noqa: C901
summary = summary_image(sk, valid)
sk[~valid] = np.nan
- peaks = (
- get_act_im_peaks(summary, p.peak_th, None, p.min_peak_distance)
- if find_peaks
- else None
- )
+ peaks = get_act_im_peaks(summary, p.peak_th, None, p.min_peak_distance) if find_peaks else None
return RasterLocalization(sk, summary, peaks, valid, info)
diff --git a/src/giant_python/extraction/raster/null.py b/src/giant_python/extraction/raster/null.py
index 21f312d4..c504e3e9 100644
--- a/src/giant_python/extraction/raster/null.py
+++ b/src/giant_python/extraction/raster/null.py
@@ -13,20 +13,20 @@
1 row and column, and the skew, from the residual (movie - baseline) of the
dimmer half of the valid pixels;
* :func:`null_movie` draws filtered compound Poisson noise with that model,
- ``y = b + s (k * (N - lambda))``, ``N ~ Poisson(lambda)`` per voxel and ``k``
+ y = b + s (k * (N - lambda)), N ~ Poisson(lambda) per voxel and k
a separable kernel with the measured correlations; its mean is the baseline,
- its variance ``gain * b * v`` (scaled per voxel where the rate varies across
- the kernel, in space or time), and its skew ``q`` times that of filtered
+ its variance gain * b * v (scaled per voxel where the rate varies across
+ the kernel, in space or time), and its skew q times that of filtered
Poisson noise at that gain (larger photon events, as in
- ``slap2_f0.simulate``);
+ slap2_f0.simulate);
* :func:`null_calibration` scores the null movies like the trial and returns
- ``(act_im - m0) / s0``, with ``m0`` and ``s0`` the null image's centre and
+ (act_im - m0) / s0, with m0 and s0 the null image's centre and
scale among pixels of similar brightness (12 equal-count bins of log photons
per frame, fewer if a bin would hold under 500 null values). By default
- (``null_scale="tail"``) they are the median and the distance from it to
+ (null_scale="tail") they are the median and the distance from it to
the 99.5th percentile in Gaussian units, so every
brightness has the same upper tail: at 0.03-0.3 photons the null image is
- so heavy-tailed that a bin's SD hangs on a few pixels. ``"sd"`` uses the
+ so heavy-tailed that a bin's SD hangs on a few pixels. "sd" uses the
mean and SD.
"""
@@ -34,13 +34,20 @@
import math
import time
+from collections.abc import Callable
+from typing import TYPE_CHECKING
import numpy as np
+if TYPE_CHECKING:
+ from .localization import RasterLocalizationParams
+
class NullUnavailable(ValueError):
- """A trial has too few pixels with enough frames for the noise model or
- the null calibration (a trial of a few frames, or almost unimaged)."""
+ """A trial has too few pixels with enough frames for the noise model or the null calibration.
+
+ That is a trial of a few frames, or almost unimaged.
+ """
_N_BINS = 12
@@ -50,7 +57,13 @@ class NullUnavailable(ValueError):
def _pooled_corr(a: np.ndarray, b: np.ndarray) -> float:
- """Pooled correlation of centred values (sum of products over norms)."""
+ """Return the pooled correlation of centred values (sum of products over norms).
+
+ Returns
+ -------
+ float
+ The correlation; 0 where it is undefined.
+ """
ok = ~np.isnan(a) & ~np.isnan(b)
a = np.where(ok, a, 0.0)
b = np.where(ok, b, 0.0)
@@ -60,18 +73,29 @@ def _pooled_corr(a: np.ndarray, b: np.ndarray) -> float:
def spatial_kernel(rho: float) -> np.ndarray:
- """``[a, 1, a] / (1 + 2a)``, whose neighbour correlation is ``rho``."""
+ """Return [a, 1, a] / (1 + 2a), whose neighbour correlation is rho.
+
+ Returns
+ -------
+ np.ndarray
+ The three taps of the kernel.
+ """
rho = float(np.clip(rho, 0.0, 0.7))
a = 0.0 if rho == 0 else (1 - np.sqrt(1 - 2 * rho**2)) / (2 * rho)
return np.array([a, 1.0, a]) / (1 + 2 * a)
def temporal_kernel(t1: float, t2: float) -> np.ndarray:
- """Seven symmetric taps fitted to the correlations at 1 and 2 frames.
+ """Return seven symmetric taps fitted to the correlations at 1 and 2 frames.
- As ``slap2_f0.simulate.noise_kernels`` without its long-average term; short
+ As slap2_f0.simulate.noise_kernels without its long-average term; short
kernels are preferred where the two lags leave taps free. Sums to 1; only
taps whose raw sum is at least 0.5 are considered, so it stays finite.
+
+ Returns
+ -------
+ np.ndarray
+ The seven taps of the kernel.
"""
t1 = float(np.clip(t1, 0.0, 0.9))
t2 = float(np.clip(t2, -0.2, 0.8))
@@ -85,11 +109,7 @@ def temporal_kernel(t1: float, t2: float) -> np.ndarray:
r0 = 1 + 2 * (k1**2 + k2**2 + k3**2)
r1 = 2 * (k1 + k1 * k2 + k2 * k3)
r2 = 2 * k2 + k1**2 + 2 * k1 * k3
- err = (
- (r1 / r0 - t1) ** 2
- + (r2 / r0 - t2) ** 2
- + 1e-6 * (k1**2 + k2**2 + k3**2)
- )
+ err = (r1 / r0 - t1) ** 2 + (r2 / r0 - t2) ** 2 + 1e-6 * (k1**2 + k2**2 + k3**2)
# only kernels that can be normalised: a sum near 0 (negative lag-2
# correlations) would blow the taps up
err = np.where(1 + 2 * (k1 + k2 + k3) >= 0.5, err, np.inf)
@@ -115,7 +135,7 @@ def noise_model(
Movie minus baseline, the baseline (counts) and the variance factor
at the valid pixels (NaN where not imaged).
vidx : ndarray of int
- Flat index of each valid pixel in the frame (``shape2d``).
+ Flat index of each valid pixel in the frame (shape2d).
shape2d : tuple
Frame shape (rows, cols).
frames : ndarray of int, optional
@@ -124,11 +144,16 @@ def noise_model(
Returns
-------
dict
- ``gain`` (single-frame variance / (baseline x variance factor)),
- ``rho`` (correlations at 1, 2 frames, 1 row, 1 column), kernels ``kt``,
- ``kr``, ``kc``, their ``W2 = sum k^2``, ``q`` (photon event size
- against Poisson, 1-3) and the medians ``skew_measured`` and
- ``skew_poisson``.
+ gain (single-frame variance / (baseline x variance factor)),
+ rho (correlations at 1, 2 frames, 1 row, 1 column), kernels kt,
+ kr, kc, their W2 = sum k^2, q (photon event size
+ against Poisson, 1-3) and the medians skew_measured and
+ skew_poisson.
+
+ Raises
+ ------
+ NullUnavailable
+ If too few imaged pixels are available to measure the noise model.
"""
sel = slice(None) if frames is None else frames
r = resid[sel].astype(np.float64)
@@ -147,9 +172,7 @@ def noise_model(
if use.sum() >= 10:
use &= b_mean <= np.median(b_mean[use])
if use.sum() < 10:
- raise NullUnavailable(
- "too few imaged pixels to measure the noise model"
- )
+ raise NullUnavailable("too few imaged pixels to measure the noise model")
gain = float(np.median(var[use] / bv_mean[use]))
# lags in recorded frames: each measured frame is paired with the one k
@@ -183,21 +206,27 @@ def noise_model(
skew_poisson = float(np.median(skew_p))
q = skew_measured / skew_poisson if skew_poisson > 0 else 1.0
q = float(np.clip(q, 1.0, 3.0)) if np.isfinite(q) else 1.0
- return dict(
- gain=gain,
- rho=np.array(rho),
- kt=kt,
- kr=kr,
- kc=kc,
- W2=w2,
- q=q,
- skew_measured=skew_measured,
- skew_poisson=skew_poisson,
- )
-
+ return {
+ "gain": gain,
+ "rho": np.array(rho),
+ "kt": kt,
+ "kr": kr,
+ "kc": kc,
+ "W2": w2,
+ "q": q,
+ "skew_measured": skew_measured,
+ "skew_poisson": skew_poisson,
+ }
+
+
+def _filter_rows_cols(d: np.ndarray, kr: np.ndarray, kc: np.ndarray) -> np.ndarray:
+ """Return the zero-padded 'same' convolution of each frame with kr and kc.
-def _filter_rows_cols(d: np.ndarray, kr: np.ndarray, kc: np.ndarray):
- """Zero-padded 'same' convolution of each frame with ``kr`` and ``kc``."""
+ Returns
+ -------
+ np.ndarray
+ The filtered frames, shaped like d.
+ """
from scipy import ndimage
out = ndimage.correlate1d(d, kr, axis=1, mode="constant", cval=0.0)
@@ -205,8 +234,16 @@ def _filter_rows_cols(d: np.ndarray, kr: np.ndarray, kc: np.ndarray):
def _fill_unobserved(lam: np.ndarray) -> np.ndarray:
- """Rates at non-finite voxels from the nearest earlier observed frame of
- the same pixel (the next later one before the first); 0 if never."""
+ """Return rates with non-finite voxels filled.
+
+ A voxel takes the rate from the nearest earlier observed frame of the same
+ pixel (the next later one before the first); 0 if never.
+
+ Returns
+ -------
+ np.ndarray
+ The rates, without non-finite voxels.
+ """
ok = np.isfinite(lam)
if ok.all():
return lam
@@ -221,17 +258,32 @@ def _fill_unobserved(lam: np.ndarray) -> np.ndarray:
return out
-def _variance_factor(lam, a, b, h, vidx, rows, cols, kt, kr, kc):
- """Per-voxel factor (frames a..b-1) that gives each voxel the variance
- ``gain * b * v``.
+def _variance_factor(
+ lam: np.ndarray,
+ a: int,
+ b: int,
+ h: int,
+ vidx: np.ndarray,
+ rows: int,
+ cols: int,
+ kt: np.ndarray,
+ kr: np.ndarray,
+ kc: np.ndarray,
+) -> np.ndarray:
+ """Return the per-voxel factor (frames a..b-1) giving each voxel variance gain * b * v.
The kernels mix the neighbouring voxels' Poisson fluctuations into a
voxel, in space and time, so where the rate changes across the kernel
(next to bright structures, or where the baseline changes within a few
frames) the variance would follow the neighbours' rates. This scales each
- voxel by ``sqrt(sum(k^2) lam / (k^2 * lam))`` (1 where the rates are
+ voxel by sqrt(sum(k^2) lam / (k^2 * lam)) (1 where the rates are
uniform, 0 at a zero rate), with zero rates outside the trial as in the
draw.
+
+ Returns
+ -------
+ np.ndarray
+ The factor for frames a to b - 1 at the valid pixels.
"""
n_t = lam.shape[0]
lo, hi = max(0, a - h), min(n_t, b + h)
@@ -255,9 +307,22 @@ def _variance_factor(lam, a, b, h, vidx, rows, cols, kt, kr, kc):
def _build_shot_arrays(
- baseline, var_factor, std, noise_var, noise, block: int = 256
-):
- """Build float32 ``(lam_all, gain_z)`` in bounded frame blocks."""
+ baseline: np.ndarray,
+ var_factor: np.ndarray,
+ std: np.ndarray,
+ noise_var: np.ndarray,
+ noise: dict,
+ block: int = 256,
+) -> tuple[np.ndarray, np.ndarray]:
+ """Build float32 (lam_all, gain_z) in bounded frame blocks.
+
+ Returns
+ -------
+ lam_all : np.ndarray
+ The Poisson rate at each sample.
+ gain_z : np.ndarray
+ The scale of the shot noise in Z-score units at each sample.
+ """
n_t = baseline.shape[0]
lam_scale = noise["W2"] / (noise["q"] ** 2 * noise["gain"])
w2 = noise["W2"]
@@ -271,11 +336,7 @@ def _build_shot_arrays(
vf_blk = var_factor[a:b].astype(np.float64)
nv_blk = noise_var[a:b].astype(np.float64)
st_blk = std[a:b].astype(np.float64)
- nan_in = (
- ~np.isfinite(nv_blk)
- | ~np.isfinite(b_blk)
- | ~np.isfinite(vf_blk)
- )
+ nan_in = ~np.isfinite(nv_blk) | ~np.isfinite(b_blk) | ~np.isfinite(vf_blk)
nv = np.maximum(0.0, nv_blk)
b_pos = np.maximum(0.0, b_blk)
shot = np.minimum(nv, np.maximum(0.0, gain * b_pos * vf_blk))
@@ -294,10 +355,25 @@ def _build_shot_arrays(
def _build_add_arrays(
- baseline, var_factor, std, noise_var, noise, block: int = 256
-):
- """Build float32 ``(add_all, inv_std)`` in blocks when additive variance
- exists, else ``(None, None)`` with zero full-trial allocation."""
+ baseline: np.ndarray,
+ var_factor: np.ndarray,
+ std: np.ndarray,
+ noise_var: np.ndarray,
+ noise: dict,
+ block: int = 256,
+) -> tuple[np.ndarray, np.ndarray] | tuple[None, None]:
+ """Build float32 (add_all, inv_std) in blocks when additive variance exists.
+
+ Without additive variance, (None, None) with zero full-trial
+ allocation.
+
+ Returns
+ -------
+ add_all : np.ndarray or None
+ The additive noise variance at each sample.
+ inv_std : np.ndarray or None
+ The inverse of the Z-score's SD at each sample.
+ """
n_t = baseline.shape[0]
gain = noise["gain"]
any_add = False
@@ -305,11 +381,7 @@ def _build_add_arrays(
for a in range(0, n_t, block):
b = min(n_t, a + block)
nv = noise_var[a:b]
- p_v = (
- np.float32(gain)
- * np.fmax(np.float32(0), baseline[a:b])
- * var_factor[a:b]
- )
+ p_v = np.float32(gain) * np.fmax(np.float32(0), baseline[a:b]) * var_factor[a:b]
if np.any(nv > p_v):
any_add = True
break
@@ -324,35 +396,44 @@ def _build_add_arrays(
vf_blk = var_factor[a:b].astype(np.float64)
nv_blk = noise_var[a:b].astype(np.float64)
st_blk = std[a:b].astype(np.float64)
- nan_in = (
- ~np.isfinite(nv_blk)
- | ~np.isfinite(b_blk)
- | ~np.isfinite(vf_blk)
- )
+ nan_in = ~np.isfinite(nv_blk) | ~np.isfinite(b_blk) | ~np.isfinite(vf_blk)
nv = np.maximum(0.0, nv_blk)
b_pos = np.maximum(0.0, b_blk)
shot = np.minimum(nv, np.maximum(0.0, gain * b_pos * vf_blk))
adv = np.maximum(0.0, nv - shot)
adv[nan_in] = np.nan
add_all[a:b] = adv.astype(np.float32)
- inv_std[a:b] = np.where(st_blk > 0, 1.0 / st_blk, 0.0).astype(
- np.float32
- )
+ inv_std[a:b] = np.where(st_blk > 0, 1.0 / st_blk, 0.0).astype(np.float32)
add_all = _fill_unobserved(add_all)
add_all[~(add_all > 0)] = 0.0
return add_all, inv_std
-def _filter_block(drawn, a, b, h, n_t, rows, cols, kr, kc, kt):
- """Apply spatial ``(kr, kc)`` and temporal ``kt`` kernels to ``drawn``."""
+def _filter_block(
+ drawn: np.ndarray,
+ a: int,
+ b: int,
+ h: int,
+ n_t: int,
+ rows: int,
+ cols: int,
+ kr: np.ndarray,
+ kc: np.ndarray,
+ kt: np.ndarray,
+) -> np.ndarray:
+ """Apply spatial (kr, kc) and temporal kt kernels to drawn.
+
+ Returns
+ -------
+ np.ndarray
+ The filtered movie of frames a to b - 1, (frames, rows, cols).
+ """
f = _filter_rows_cols(drawn.reshape(-1, rows, cols), kr, kc)
- f = np.concatenate(
- [
- np.zeros((max(0, h - a), rows, cols), np.float32),
- f,
- np.zeros((max(0, b + h - n_t), rows, cols), np.float32),
- ]
- )
+ f = np.concatenate([
+ np.zeros((max(0, h - a), rows, cols), np.float32),
+ f,
+ np.zeros((max(0, b + h - n_t), rows, cols), np.float32),
+ ])
n_out = f.shape[0] - kt.size + 1 # 'valid' in time: frames a .. b-1
g = np.zeros((n_out, rows, cols), np.float32)
for j, w in enumerate(kt[::-1]):
@@ -361,8 +442,17 @@ def _filter_block(drawn, a, b, h, n_t, rows, cols, kr, kc, kt):
def _accumulate_component(
- flat_out, rate, scale_z, vidx, n_t, rows, cols, noise, block, draw_fn
-):
+ flat_out: np.ndarray,
+ rate: np.ndarray,
+ scale_z: np.ndarray,
+ vidx: np.ndarray,
+ n_t: int,
+ rows: int,
+ cols: int,
+ noise: dict,
+ block: int,
+ draw_fn: Callable[[np.ndarray], np.ndarray],
+) -> None:
"""Draw, filter, and variance-correct one latent noise component."""
kt, kr, kc = noise["kt"], noise["kr"], noise["kc"]
h = (kt.size - 1) // 2
@@ -382,9 +472,7 @@ def _accumulate_component(
d0 += drop
f = _filter_block(drawn, a, b, h, n_t, rows, cols, kr, kc, kt)
corr = _variance_factor(rate, a, b, h, vidx, rows, cols, kt, kr, kc)
- flat_out[a:b, vidx] += (
- f.reshape(b - a, -1)[:, vidx] * scale_z[a:b] * corr
- )
+ flat_out[a:b, vidx] += f.reshape(b - a, -1)[:, vidx] * scale_z[a:b] * corr
def null_movie(
@@ -398,7 +486,7 @@ def null_movie(
block: int = 256,
noise_var: np.ndarray | None = None,
) -> np.ndarray:
- """A Z-scored noise movie with the trial's baseline and noise model.
+ """Draw a Z-scored noise movie with the trial's baseline and noise model.
Parameters
----------
@@ -418,14 +506,14 @@ def null_movie(
noise_var : ndarray of shape (frames, n_valid), optional
Target single-frame noise variance at the valid pixels (before any
variance floor). Splits into compound-Poisson shot noise up to
- ``gain * max(0, baseline) * var_factor`` plus zero-mean correlated
+ gain * max(0, baseline) * var_factor plus zero-mean correlated
Gaussian additive noise for any remaining variance (including at
nonpositive baselines).
Returns
-------
- ndarray of float32, shape of ``nans``
- ``(y - baseline) / std``: what the localization sees after its
+ ndarray of float32, shape of nans
+ (y - baseline) / std: what the localization sees after its
high-pass if the trial held only noise.
"""
rng = np.random.default_rng(seed)
@@ -437,9 +525,7 @@ def null_movie(
s = noise["q"] * noise["gain"] / noise["W2"]
lam_scale = noise["W2"] / (noise["q"] ** 2 * noise["gain"])
with np.errstate(invalid="ignore", divide="ignore"):
- lam_all = (
- baseline.astype(np.float64) * lam_scale / var_factor
- ).astype(np.float32)
+ lam_all = (baseline.astype(np.float64) * lam_scale / var_factor).astype(np.float32)
gain_z = (s * var_factor / std).astype(np.float32)
lam_all = _fill_unobserved(lam_all)
lam_all[~(lam_all > 0)] = 0.0
@@ -457,9 +543,7 @@ def null_movie(
)
del lam_all, gain_z
else:
- lam_all, gain_z = _build_shot_arrays(
- baseline, var_factor, std, noise_var, noise, block
- )
+ lam_all, gain_z = _build_shot_arrays(baseline, var_factor, std, noise_var, noise, block)
if (lam_all > 0).any():
_accumulate_component(
flat_out,
@@ -474,9 +558,7 @@ def null_movie(
lambda lam: (rng.poisson(lam) - lam).astype(np.float32),
)
del lam_all, gain_z
- add_all, inv_std = _build_add_arrays(
- baseline, var_factor, std, noise_var, noise, block
- )
+ add_all, inv_std = _build_add_arrays(baseline, var_factor, std, noise_var, noise, block)
if add_all is not None:
inv_w2 = 1.0 / np.sqrt(noise["W2"])
_accumulate_component(
@@ -489,9 +571,9 @@ def null_movie(
cols,
noise,
block,
- lambda av: (
- rng.standard_normal(av.shape) * np.sqrt(av) * inv_w2
- ).astype(np.float32),
+ lambda av: (rng.standard_normal(av.shape) * np.sqrt(av) * inv_w2).astype(
+ np.float32
+ ),
)
del add_all, inv_std
out[nans] = np.nan
@@ -499,18 +581,31 @@ def null_movie(
def _pixel_index(valid: np.ndarray) -> np.ndarray:
- """Each valid pixel's number among the valid ones (row-major), -1
- elsewhere."""
+ """Return each valid pixel's number among the valid ones (row-major).
+
+ Returns
+ -------
+ np.ndarray
+ The numbers, -1 elsewhere.
+ """
index = np.full(valid.shape, -1, np.int64)
index[valid] = np.arange(int(valid.sum()))
return index
def _tile_views(valid: np.ndarray, index: np.ndarray, reach: int) -> list:
- """For rectangles around the valid pixels grown by ``reach``
- (:func:`~giant_python.extraction.raster.localization.score_tiles`):
+ """Return the views for rectangles around the valid pixels grown by reach.
+
+ The rectangles are those of
+ :func:`~giant_python.extraction.raster.localization.score_tiles`. A view is
the grown rectangle's shape, where its valid pixels sit in it and their
- numbers, and the same for the pixels of the rectangle itself."""
+ numbers, and the same for the pixels of the rectangle itself.
+
+ Returns
+ -------
+ list
+ One view per rectangle.
+ """
from .localization import score_tiles
rows, cols = valid.shape
@@ -522,20 +617,26 @@ def _tile_views(valid: np.ndarray, index: np.ndarray, reach: int) -> list:
pr, pc = np.nonzero(sub >= 0)
own = index[r0:r1, c0:c1]
qr, qc = np.nonzero(own >= 0)
- views.append(
- (
- (a1 - a0, b1 - b0),
- (pr, pc, sub[pr, pc]),
- (qr + r0 - a0, qc + c0 - b0, own[qr, qc]),
- )
- )
+ views.append((
+ (a1 - a0, b1 - b0),
+ (pr, pc, sub[pr, pc]),
+ (qr + r0 - a0, qc + c0 - b0, own[qr, qc]),
+ ))
return views
-def _filter_valid(x: np.ndarray, views: list, kr, kc) -> np.ndarray:
- """:func:`_filter_rows_cols` of frames that hold ``x`` (frames, valid
- pixels) at the valid pixels and zeros elsewhere, at the valid pixels:
- filtered on rectangles around them, the same sums."""
+def _filter_valid(x: np.ndarray, views: list, kr: np.ndarray, kc: np.ndarray) -> np.ndarray:
+ """Return :func:`_filter_rows_cols` of frames that hold x at the valid pixels.
+
+ x is (frames, valid pixels) with zeros elsewhere in the frames; the
+ result is at the valid pixels, filtered on rectangles around them, the
+ same sums.
+
+ Returns
+ -------
+ np.ndarray
+ The filtered values, (frames, valid pixels).
+ """
out = np.empty(x.shape, np.float32)
for shape, (pr, pc, col), (qr, qc, own) in views:
crop = np.zeros((x.shape[0],) + shape, np.float32)
@@ -544,9 +645,25 @@ def _filter_valid(x: np.ndarray, views: list, kr, kc) -> np.ndarray:
return out
-def _variance_factor_valid(lam, a, b, h, views, kt, kr, kc):
- """:func:`_variance_factor` from rates at the valid pixels (frames,
- valid pixels), at the valid pixels: the same values."""
+def _variance_factor_valid(
+ lam: np.ndarray,
+ a: int,
+ b: int,
+ h: int,
+ views: list,
+ kt: np.ndarray,
+ kr: np.ndarray,
+ kc: np.ndarray,
+) -> np.ndarray:
+ """Return :func:`_variance_factor` from rates at the valid pixels.
+
+ The rates are (frames, valid pixels), at the valid pixels: the same values.
+
+ Returns
+ -------
+ np.ndarray
+ The per-voxel factor for frames a to b - 1 at the valid pixels.
+ """
n_t, n_v = lam.shape
lo, hi = max(0, a - h), min(n_t, b + h)
full = np.zeros((b - a + 2 * h, n_v), np.float32)
@@ -566,12 +683,20 @@ def _variance_factor_valid(lam, a, b, h, views, kt, kr, kc):
def _accumulate_component_valid(
- out, rate, scale_z, views, noise, block, draw_fn
-):
- """:func:`_accumulate_component` at the valid pixels: ``out``, ``rate``
- and ``scale_z`` are (frames, valid pixels); the draws are the same, the
- filters in space run on rectangles around the valid pixels and the
- filter in time per pixel."""
+ out: np.ndarray,
+ rate: np.ndarray,
+ scale_z: np.ndarray,
+ views: list,
+ noise: dict,
+ block: int,
+ draw_fn: Callable[[np.ndarray], np.ndarray],
+) -> None:
+ """Run :func:`_accumulate_component` at the valid pixels.
+
+ out, rate and scale_z are (frames, valid pixels); the draws
+ are the same, the filters in space run on rectangles around the valid
+ pixels and the filter in time per pixel.
+ """
kt, kr, kc = noise["kt"], noise["kr"], noise["kc"]
h = (kt.size - 1) // 2
n_t, n_v = out.shape
@@ -589,13 +714,11 @@ def _accumulate_component_valid(
drawn = drawn[drop:]
d0 += drop
f = _filter_valid(drawn, views, kr, kc)
- f = np.concatenate(
- [
- np.zeros((max(0, h - a), n_v), np.float32),
- f,
- np.zeros((max(0, b + h - n_t), n_v), np.float32),
- ]
- )
+ f = np.concatenate([
+ np.zeros((max(0, h - a), n_v), np.float32),
+ f,
+ np.zeros((max(0, b + h - n_t), n_v), np.float32),
+ ])
n_out = f.shape[0] - kt.size + 1 # 'valid' in time: frames a .. b-1
g = np.zeros((n_out, n_v), np.float32)
for j, w in enumerate(kt[::-1]):
@@ -641,36 +764,32 @@ def null_movie_valid(
views = _tile_views(valid, _pixel_index(valid), max(kr.size, kc.size) // 2)
out = np.zeros(nan_v.shape, dtype=np.float32)
- def shot(lam):
- """Compound-Poisson draws around their rate."""
+ def shot(lam: np.ndarray) -> np.ndarray:
+ """Return compound-Poisson draws around their rate.
+
+ Returns
+ -------
+ np.ndarray
+ The draws (float32), centred on zero.
+ """
return (rng.poisson(lam) - lam).astype(np.float32)
if noise_var is None:
s = noise["q"] * noise["gain"] / noise["W2"]
lam_scale = noise["W2"] / (noise["q"] ** 2 * noise["gain"])
with np.errstate(invalid="ignore", divide="ignore"):
- lam_all = (
- baseline.astype(np.float64) * lam_scale / var_factor
- ).astype(np.float32)
+ lam_all = (baseline.astype(np.float64) * lam_scale / var_factor).astype(np.float32)
gain_z = (s * var_factor / std).astype(np.float32)
lam_all = _fill_unobserved(lam_all)
lam_all[~(lam_all > 0)] = 0.0
- _accumulate_component_valid(
- out, lam_all, gain_z, views, noise, block, shot
- )
+ _accumulate_component_valid(out, lam_all, gain_z, views, noise, block, shot)
del lam_all, gain_z
else:
- lam_all, gain_z = _build_shot_arrays(
- baseline, var_factor, std, noise_var, noise, block
- )
+ lam_all, gain_z = _build_shot_arrays(baseline, var_factor, std, noise_var, noise, block)
if (lam_all > 0).any():
- _accumulate_component_valid(
- out, lam_all, gain_z, views, noise, block, shot
- )
+ _accumulate_component_valid(out, lam_all, gain_z, views, noise, block, shot)
del lam_all, gain_z
- add_all, inv_std = _build_add_arrays(
- baseline, var_factor, std, noise_var, noise, block
- )
+ add_all, inv_std = _build_add_arrays(baseline, var_factor, std, noise_var, noise, block)
if add_all is not None:
inv_w2 = 1.0 / np.sqrt(noise["W2"])
_accumulate_component_valid(
@@ -680,9 +799,9 @@ def shot(lam):
views,
noise,
block,
- lambda av: (
- rng.standard_normal(av.shape) * np.sqrt(av) * inv_w2
- ).astype(np.float32),
+ lambda av: (rng.standard_normal(av.shape) * np.sqrt(av) * inv_w2).astype(
+ np.float32
+ ),
)
del add_all, inv_std
out[nan_v] = np.nan
@@ -690,47 +809,64 @@ def shot(lam):
def _edge_valid(nan_v: np.ndarray, valid: np.ndarray) -> np.ndarray:
- """Pixels whose 3x3 neighbourhood holds a sample not imaged (or a pixel
- outside the frame) in more than half the frames, from the valid pixels'
- samples: the whole-frame filter's values at the valid pixels (True
- elsewhere)."""
+ """Return the pixels whose 3x3 neighbourhood holds a sample not imaged.
+
+ A pixel outside the frame counts too, in more than half the frames, from
+ the valid pixels' samples: the whole-frame filter's values at the valid
+ pixels (True elsewhere).
+
+ Returns
+ -------
+ np.ndarray
+ Boolean map of the frame, True at such pixels (and at pixels that are
+ not valid).
+ """
from scipy import ndimage
edge = np.ones(valid.shape, bool)
rows_of, cols_of = np.nonzero(valid)
- for shape, (pr, pc, col), (qr, qc, own) in _tile_views(
- valid, _pixel_index(valid), 1
- ):
+ for shape, (pr, pc, col), (qr, qc, own) in _tile_views(valid, _pixel_index(valid), 1):
nans = np.ones((nan_v.shape[0],) + shape, bool)
nans[:, pr, pc] = nan_v[:, col]
- part = (
- ndimage.maximum_filter(
- nans, size=(1, 3, 3), mode="constant", cval=1
- ).mean(0)
- > 0.5
- )
+ part = ndimage.maximum_filter(nans, size=(1, 3, 3), mode="constant", cval=1).mean(0) > 0.5
edge[rows_of[own], cols_of[own]] = part[qr, qc]
return edge
-def _brightness_bins(lp: np.ndarray, draws: int):
- """Bins of log brightness, each holding at least ``_MIN_BIN_VALUES``
- null values (pixels x draws) when there are that many in all.
+def _brightness_bins(lp: np.ndarray, draws: int) -> tuple[np.ndarray, np.ndarray]:
+ """Return bins of log brightness, each holding at least _MIN_BIN_VALUES null values.
+
+ The null values are pixels x draws, when there are that many in all.
- Up to ``_N_BINS`` equal-count bins by value, so tied pixels stay
+ Up to _N_BINS equal-count bins by value, so tied pixels stay
together; a bin left under the minimum (ties collapse edges, or a few
pixels sit below a tied block) is merged with its smaller neighbour until
none is. With few values, a bin's 99.5th percentile would be its maximum.
- Returns each pixel's bin and the null values per bin.
+ Returns
+ -------
+ bins : np.ndarray
+ Each pixel's bin.
+ counts : np.ndarray
+ The null values per bin.
"""
n0 = int(np.clip(lp.size * draws // _MIN_BIN_VALUES, 1, _N_BINS))
edges = np.unique(np.quantile(lp, np.linspace(0, 1, n0 + 1)))
if edges.size == 1: # a single brightness: one bin
edges = np.repeat(edges, 2)
- def assign(edges):
- """Bin of each pixel and values per bin; the top value goes last."""
+ def assign(edges: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Return the bin of each pixel and the values per bin.
+
+ The top value goes last.
+
+ Returns
+ -------
+ b : np.ndarray
+ The bin of each pixel.
+ counts : np.ndarray
+ The null values per bin.
+ """
b = np.clip(np.searchsorted(edges, lp, side="right") - 1, 0, None)
b = np.minimum(b, edges.size - 2)
return b, np.bincount(b, minlength=edges.size - 1) * draws
@@ -746,10 +882,22 @@ def assign(edges):
return bins, counts
-def _calibration_maps(photons, centre, m0, s0):
- """Per-pixel null centre and scale: linear in log photons between the
- bins' centres, constant beyond the outer ones. Zero or negative
- brightness takes the dimmest bin; undefined (NaN) the middle one."""
+def _calibration_maps(
+ photons: np.ndarray, centre: np.ndarray, m0: np.ndarray, s0: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """Return the per-pixel null centre and scale.
+
+ They are linear in log photons between the bins' centres, constant beyond
+ the outer ones. Zero or negative brightness takes the dimmest bin;
+ undefined (NaN) the middle one.
+
+ Returns
+ -------
+ m_map : np.ndarray
+ The null centre at each pixel.
+ s_map : np.ndarray
+ The null scale at each pixel.
+ """
with np.errstate(divide="ignore", invalid="ignore"):
lp = np.log(photons)
m_map = np.interp(lp, centre, m0)
@@ -762,8 +910,22 @@ def _calibration_maps(photons, centre, m0, s0):
return m_map, s_map
-def _fit_bins(lp: np.ndarray, vals: np.ndarray, draws: int, null_scale: str):
- """Centre, location ``m0``, scale ``s0``, and sample counts per bin."""
+def _fit_bins(
+ lp: np.ndarray, vals: np.ndarray, draws: int, null_scale: str
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Return the centre, location m0, scale s0, and sample counts per bin.
+
+ Returns
+ -------
+ centre : np.ndarray
+ Each bin's centre, in log photons.
+ m0 : np.ndarray
+ Each bin's location.
+ s0 : np.ndarray
+ Each bin's scale.
+ used : np.ndarray
+ The number of null values in each bin.
+ """
bins, counts = _brightness_bins(lp, draws)
centre, m0, s0, used = [], [], [], []
for k in range(counts.size):
@@ -785,23 +947,31 @@ def _fit_bins(lp: np.ndarray, vals: np.ndarray, draws: int, null_scale: str):
def _dark_null_values(
- dark_ok,
- null_ims,
- baseline,
- var_factor,
- std,
- nans,
- vidx,
- noise,
- noise_var,
- params,
- sd_u,
- nan_v=None,
-):
- """Null scores on nonpositive-baseline pixels, adding cropped draws when
- needed to reach ``_MIN_BIN_VALUES`` samples. With ``nan_v`` (frames x
- valid pixels) and the squared-maxima score the cropped draws are made
- and scored at the valid pixels (the same values; ``nans`` not used)."""
+ dark_ok: np.ndarray,
+ null_ims: np.ndarray,
+ baseline: np.ndarray,
+ var_factor: np.ndarray,
+ std: np.ndarray,
+ nans: np.ndarray,
+ vidx: np.ndarray,
+ noise: dict,
+ noise_var: np.ndarray,
+ params: RasterLocalizationParams,
+ sd_u: float | None,
+ nan_v: np.ndarray | None = None,
+) -> np.ndarray:
+ """Return null scores on nonpositive-baseline pixels.
+
+ Cropped draws are added when needed to reach _MIN_BIN_VALUES samples.
+ With nan_v (frames x valid pixels) and the squared-maxima score the
+ cropped draws are made and scored at the valid pixels (the same values;
+ nans not used).
+
+ Returns
+ -------
+ np.ndarray
+ The null scores at the dark pixels, one row per null draw.
+ """
from .localization import activity_score, activity_score_tiled
on_valid = nan_v is not None and params.score == "squared_maxima"
@@ -818,12 +988,8 @@ def _dark_null_values(
+ 3
)
rr, cc = np.nonzero(dark_ok)
- r0, r1 = max(0, int(rr.min()) - pad), min(
- rows, int(rr.max()) + pad + 1
- )
- c0, c1 = max(0, int(cc.min()) - pad), min(
- cols, int(cc.max()) + pad + 1
- )
+ r0, r1 = max(0, int(rr.min()) - pad), min(rows, int(rr.max()) + pad + 1)
+ c0, c1 = max(0, int(cc.min()) - pad), min(cols, int(cc.max()) + pad + 1)
vr, vc = vidx // cols, vidx % cols
in_c = (vr >= r0) & (vr < r1) & (vc >= c0) & (vc < c1)
c_vidx = (vr[in_c] - r0) * (c1 - c0) + (vc[in_c] - c0)
@@ -866,10 +1032,29 @@ def _dark_null_values(
def _photons_and_nv(
- baseline, var_factor, std, noise_var, noise, shape, vidx, block: int = 256
-):
- """Effective photons, mean ``noise_var``, and floor-attenuation maps,
- accumulated in bounded frame blocks without full-trial float64 copies."""
+ baseline: np.ndarray,
+ var_factor: np.ndarray,
+ std: np.ndarray,
+ noise_var: np.ndarray | None,
+ noise: dict,
+ shape: tuple[int, int],
+ vidx: np.ndarray,
+ block: int = 256,
+) -> tuple[np.ndarray, np.ndarray | None, np.ndarray | None]:
+ """Return effective photons, mean noise_var, and floor-attenuation maps.
+
+ They are accumulated in bounded frame blocks without full-trial float64
+ copies.
+
+ Returns
+ -------
+ photons : np.ndarray
+ The effective photons per frame, as a frame-shaped map.
+ nv_map : np.ndarray or None
+ The mean noise_var map; None without noise_var.
+ al_map : np.ndarray or None
+ The floor-attenuation map; None without noise_var.
+ """
n_t, n_px = baseline.shape
gain = noise["gain"]
if noise_var is None:
@@ -878,9 +1063,7 @@ def _photons_and_nv(
with np.errstate(invalid="ignore", divide="ignore"):
for a in range(0, n_t, block):
b = min(n_t, a + block)
- q = baseline[a:b].astype(np.float64) / (
- gain * var_factor[a:b].astype(np.float64)
- )
+ q = baseline[a:b].astype(np.float64) / (gain * var_factor[a:b].astype(np.float64))
ok_q = np.isfinite(q)
ph_sum += np.where(ok_q, q, 0.0).sum(0)
cnt += ok_q.sum(0)
@@ -902,9 +1085,7 @@ def _photons_and_nv(
vf_blk = var_factor[a:b].astype(np.float64)
nv_blk = noise_var[a:b].astype(np.float64)
st_blk = std[a:b].astype(np.float64)
- ok_v = (
- np.isfinite(nv_blk) & np.isfinite(b_blk) & np.isfinite(vf_blk)
- )
+ ok_v = np.isfinite(nv_blk) & np.isfinite(b_blk) & np.isfinite(vf_blk)
nv = np.maximum(0.0, nv_blk)
b_pos = np.maximum(0.0, b_blk)
shot = np.minimum(nv, np.maximum(0.0, gain * b_pos * vf_blk))
@@ -922,9 +1103,7 @@ def _photons_and_nv(
sv_m = np.where(cnt > 0, sv_sum / cnt, np.nan)
nv_m = np.where(cnt > 0, nv_sum / cnt, np.nan)
al_m = np.where(cnt_al > 0, al_sum / cnt_al, np.nan)
- ph = np.where(
- (sv_m > 0) & (ph_raw > 0), ph_raw * (nv_m / sv_m) ** 3, 0.0
- )
+ ph = np.where((sv_m > 0) & (ph_raw > 0), ph_raw * (nv_m / sv_m) ** 3, 0.0)
ph[np.isnan(nv_m)] = np.nan
n_all = shape[0] * shape[1]
photons, nv_map, al_map = (np.full(n_all, np.nan) for _ in range(3))
@@ -936,8 +1115,16 @@ def _photons_and_nv(
)
-def _alpha_bands(al_ok: np.ndarray, draws: int):
- """Band index per pixel for ``alpha_map``, keeping imbalanced plateaus."""
+def _alpha_bands(al_ok: np.ndarray, draws: int) -> tuple[np.ndarray, int]:
+ """Return the band index per pixel for alpha_map, keeping imbalanced plateaus.
+
+ Returns
+ -------
+ bins : np.ndarray
+ The band of each pixel.
+ n_bands : int
+ The number of bands.
+ """
n_bands = int(np.clip(al_ok.size * draws // _MIN_BIN_VALUES, 2, 4))
u_al = np.unique(al_ok)
if u_al.size <= n_bands:
@@ -946,16 +1133,22 @@ def _alpha_bands(al_ok: np.ndarray, draws: int):
else:
edges = np.linspace(float(al_ok.min()), float(al_ok.max()), 8 + 1)
- def assign(ed):
- """Band of each pixel and null sample count per band."""
+ def assign(ed: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Return the band of each pixel and the null sample count per band.
+
+ Returns
+ -------
+ b : np.ndarray
+ The band of each pixel.
+ counts : np.ndarray
+ The null sample count per band.
+ """
b = np.clip(np.searchsorted(ed, al_ok, side="right") - 1, 0, None)
b = np.minimum(b, ed.size - 2)
return b, np.bincount(b, minlength=ed.size - 1) * draws
bins, counts = assign(edges)
- while counts.size > 1 and (
- counts.min() < _MIN_BIN_VALUES or counts.size > n_bands
- ):
+ while counts.size > 1 and (counts.min() < _MIN_BIN_VALUES or counts.size > n_bands):
if counts.min() < _MIN_BIN_VALUES:
k = int(np.argmin(counts))
else:
@@ -972,9 +1165,23 @@ def assign(ed):
return bins, counts.size
-def _positive_maps_soft_th(photons, alpha_map, ok, null_ims, params):
- """2-D ``(alpha, log_photons)`` calibration maps when ``soft_threshold``
- makes floor attenuation nonlinear."""
+def _positive_maps_soft_th(
+ photons: np.ndarray,
+ alpha_map: np.ndarray,
+ ok: np.ndarray,
+ null_ims: np.ndarray,
+ params: RasterLocalizationParams,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray] | None:
+ """Return 2-D (alpha, log_photons) calibration maps.
+
+ Used when soft_threshold makes floor attenuation nonlinear.
+
+ Returns
+ -------
+ tuple of np.ndarray or None
+ The null centre map and scale map, and the bins' centres, locations
+ m0, scales s0 and null value counts; None if no bin was fitted.
+ """
al_ok = alpha_map[ok]
if not (al_ok.size >= 4 and al_ok.max() > 1.05 * max(al_ok.min(), 1e-12)):
c, m0, s0, u = _fit_bins(
@@ -1016,9 +1223,7 @@ def _positive_maps_soft_th(photons, alpha_map, ok, null_ims, params):
return m_stack[0], s_stack[0], *first_fit
ac = np.asarray(al_centres)
ms, ss = np.stack(m_stack), np.stack(s_stack)
- al_clamped = np.clip(
- np.where(np.isfinite(alpha_map), alpha_map, ac[0]), ac[0], ac[-1]
- )
+ al_clamped = np.clip(np.where(np.isfinite(alpha_map), alpha_map, ac[0]), ac[0], ac[-1])
hi = np.clip(np.searchsorted(ac, al_clamped, side="right"), 1, ac.size - 1)
lo = hi - 1
den = np.maximum(ac[hi] - ac[lo], 1e-12)
@@ -1029,8 +1234,21 @@ def _positive_maps_soft_th(photons, alpha_map, ok, null_ims, params):
return m_map, s_map, *first_fit
-def _fit_positive_maps(photons, alpha_map, ok, work_ims, params):
- """Fit positive-baseline calibration maps and bin summary tuple."""
+def _fit_positive_maps(
+ photons: np.ndarray,
+ alpha_map: np.ndarray | None,
+ ok: np.ndarray,
+ work_ims: np.ndarray,
+ params: RasterLocalizationParams,
+) -> tuple[np.ndarray | None, np.ndarray | None, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Fit positive-baseline calibration maps and bin summary tuple.
+
+ Returns
+ -------
+ tuple
+ The null centre map and scale map (None if no bin was fitted) and the
+ bins' centres, locations m0, scales s0 and null value counts.
+ """
if ok.sum() < 2:
empty = np.array([])
return None, None, empty, empty, empty, empty
@@ -1053,27 +1271,36 @@ def _fit_positive_maps(photons, alpha_map, ok, work_ims, params):
def _apply_dark_calibration(
- m_map,
- s_map,
- dark_pos,
- dark_ok,
- nv_map,
- scale_div,
- null_ims,
- baseline,
- var_factor,
- std,
- nans,
- vidx,
- noise,
- noise_var,
- params,
- sd_u,
- fallback_ms,
- nan_v=None,
-):
- """Fill ``(m_map, s_map)`` at nonpositive-baseline pixels and return the
- dark-region bin tuple when fitted."""
+ m_map: np.ndarray | None,
+ s_map: np.ndarray | None,
+ dark_pos: np.ndarray,
+ dark_ok: np.ndarray,
+ nv_map: np.ndarray | None,
+ scale_div: np.ndarray | None,
+ null_ims: np.ndarray,
+ baseline: np.ndarray,
+ var_factor: np.ndarray,
+ std: np.ndarray,
+ nans: np.ndarray,
+ vidx: np.ndarray,
+ noise: dict,
+ noise_var: np.ndarray | None,
+ params: RasterLocalizationParams,
+ sd_u: float | None,
+ fallback_ms: tuple[float, float] | None,
+ nan_v: np.ndarray | None = None,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] | None:
+ """Fill (m_map, s_map) at nonpositive-baseline pixels.
+
+ The maps are filled in place, and the dark-region bin tuple is returned
+ when fitted.
+
+ Returns
+ -------
+ tuple of np.ndarray or None
+ The dark-region bins' centres, locations m0, scales s0 and null
+ value counts; None if no bin was fitted.
+ """
dark_fit = None
if dark_ok.sum() >= 2:
d_vals = _dark_null_values(
@@ -1119,30 +1346,47 @@ def null_calibration(
valid: np.ndarray,
vidx: np.ndarray,
noise: dict,
- params,
+ params: RasterLocalizationParams,
sd_u: float | None,
noise_var: np.ndarray | None = None,
nan_v: np.ndarray | None = None,
) -> tuple[np.ndarray, dict]:
"""Calibrate a trial's activity image per pixel brightness.
- Runs ``params.null_draws`` null movies (:func:`null_movie`) through the
- trial's activity score (with the trial's ``sd_u``) and returns
- ``(act_im - m0) / s0``: ``m0`` and ``s0`` are the null image's centre and
+ Runs params.null_draws null movies (:func:`null_movie`) through the
+ trial's activity score (with the trial's sd_u) and returns
+ (act_im - m0) / s0: m0 and s0 are the null image's centre and
scale among pixels of similar brightness (12 equal-count bins of the log
mean photons per frame, fewer if a bin would hold under 500 null values;
linear in between, constant beyond the outer bins'
- centres): with ``params.null_scale`` "tail" the median and
- ``(q99.5 - median) / 2.576``, with "sd" the mean and SD. Also returns
- the noise model, bin brightness (photons per frame), ``m0``, ``s0``,
- the null images calibrated the same way (``null_im``, ``(draws, rows,
- cols)`` float32, NaN outside the valid pixels) and the seconds taken.
+ centres): with params.null_scale "tail" the median and
+ (q99.5 - median) / 2.576, with "sd" the mean and SD. Also returns
+ the noise model, bin brightness (photons per frame), m0, s0,
+ the null images calibrated the same way (null_im, (draws, rows,
+ cols) float32, NaN outside the valid pixels) and the seconds taken.
- With ``nan_v`` (the samples not imaged, frames x valid pixels) and the
+ With nan_v (the samples not imaged, frames x valid pixels) and the
squared-maxima score, the null movies are made and scored at the valid
pixels (:func:`null_movie_valid`,
:func:`~giant_python.extraction.raster.localization.activity_score_tiled`):
- the same values without whole frames; ``nans`` is then not used.
+ the same values without whole frames; nans is then not used.
+
+ Returns
+ -------
+ out : np.ndarray
+ The calibrated activity image (act_im - m0) / s0.
+ info : dict
+ The noise model (noise), the bin brightness (photons, photons
+ per frame), m0, s0, the null values per bin (counts), the
+ number of null movies (draws), the calibrated null images
+ (null_im) and the seconds taken (seconds).
+
+ Raises
+ ------
+ NullUnavailable
+ If too few imaged pixels remain for the null calibration.
+ ValueError
+ If the null activity image has no spread.
"""
from .localization import activity_score, activity_score_tiled
@@ -1192,12 +1436,7 @@ def null_calibration(
else:
from scipy import ndimage
- edge = (
- ndimage.maximum_filter(
- nans, size=(1, 3, 3), mode="constant", cval=1
- ).mean(0)
- > 0.5
- )
+ edge = ndimage.maximum_filter(nans, size=(1, 3, 3), mode="constant", cval=1).mean(0) > 0.5
finite_null = np.isfinite(null_ims).all(0)
ok = valid & ~edge & (photons > 0) & finite_null
dark_pos = (
@@ -1245,16 +1484,16 @@ def null_calibration(
m_map = m_map * scale_div
s_map = s_map * scale_div
out = (act_im - m_map) / s_map
- info = dict(
- noise=noise,
- photons=np.exp(centre),
- m0=m0,
- s0=s0,
- counts=used,
- draws=params.null_draws,
+ info = {
+ "noise": noise,
+ "photons": np.exp(centre),
+ "m0": m0,
+ "s0": s0,
+ "counts": used,
+ "draws": params.null_draws,
# the null movies' activity images, calibrated like the trial's:
# what the calibrated image would be if the trial held only noise
- null_im=((null_ims - m_map) / s_map).astype(np.float32),
- seconds=time.time() - t0,
- )
+ "null_im": ((null_ims - m_map) / s_map).astype(np.float32),
+ "seconds": time.time() - t0,
+ }
return out, info
diff --git a/src/giant_python/extraction/raster/peaks.py b/src/giant_python/extraction/raster/peaks.py
index 9cac1685..f9686537 100644
--- a/src/giant_python/extraction/raster/peaks.py
+++ b/src/giant_python/extraction/raster/peaks.py
@@ -1,26 +1,26 @@
"""Source seeds in a multi-ROI (raster) SiLo activity image.
-Port of GIAnT-MATLAB's ``getActImPeaks.m`` and its ``gaussianPeaksIntegrated``
+Port of GIAnT-MATLAB's getActImPeaks.m and its gaussianPeaksIntegrated
(the 2-D raster version; the band-scan port in
:mod:`giant_python.numerics.peaks` is a different algorithm). Candidate peaks
are local maxima whose second-largest 3x3 neighbour exceeds the threshold
-(median plus ``peak_th`` MAD-scaled SDs of the whole image). Isotropic
+(median plus peak_th MAD-scaled SDs of the whole image). Isotropic
Gaussians, each integrated over its pixel, are fitted jointly to the image
around them; residual maxima above the threshold are then added one at a time
(refitting the peaks of their connected region), and fitted peaks whose
amplitude is too small for the threshold are dropped.
-MATLAB fits with ``lsqcurvefit`` (trust-region-reflective, finite-difference
+MATLAB fits with lsqcurvefit (trust-region-reflective, finite-difference
Jacobian, at most 5000 function evaluations). This port uses
-:func:`scipy.optimize.least_squares` (``trf``) with the analytical Jacobian and
+:func:`scipy.optimize.least_squares` (trf) with the analytical Jacobian and
caps its evaluations at the number of iterations those 5000 evaluations allow
(one plus one per parameter each), so fits of many peaks stop early as in
MATLAB. The optimizers' paths differ, so positions agree to a small fraction
of a pixel rather than exactly.
-``fit='local'`` is a faster variant of the same search (not in MATLAB):
+fit='local' is a faster variant of the same search (not in MATLAB):
each Gaussian is evaluated only near its start pixel, every fit runs to
-convergence, and a residual peak refits only its neighbours. ``merge_px``
+convergence, and a residual peak refits only its neighbours. merge_px
(either fit) also rejects a residual peak that ends next to another peak:
an activity image's peaks are often split in two that way.
@@ -31,17 +31,15 @@
from __future__ import annotations
import numpy as np
-import scipy.ndimage as ndimage
-import scipy.sparse as sparse
+import numpy.typing as npt
from numpy.lib.stride_tricks import sliding_window_view
-from scipy.optimize import least_squares
+from scipy import ndimage, sparse
+from scipy.optimize import OptimizeResult, least_squares
from scipy.special import erf
_AMP_SCALE = 1.0 / 0.75
_SIGMA0 = 0.35 # starting width of every fitted peak
-_MAD_SCALE = (
- 0.6741891400433162 # MATLAB's getActImPeaks divides mad(x, 1) by this
-)
+_MAD_SCALE = 0.6741891400433162 # MATLAB's getActImPeaks divides mad(x, 1) by this
_MAX_FUN_EVALS = 5000
_SQRT_PI_2 = np.sqrt(np.pi / 2)
_SQRT2 = np.sqrt(2.0)
@@ -61,13 +59,21 @@
_LOCAL_TOL = 1e-4
_LOCAL_DENSE_MAX = 400
+# per-axis Gaussian integral, or (integral, d/dmu, d/dsigma) when derivatives are asked for
+_Terms = np.ndarray | tuple[np.ndarray, np.ndarray, np.ndarray]
+
def ordfilt3x3(a: np.ndarray, order: int) -> np.ndarray:
- """MATLAB ``ordfilt2(a, order, ones(3))`` for a 2-D float image.
+ """MATLAB ordfilt2(a, order, ones(3)) for a 2-D float image.
- The ``order``-th smallest value (9 = maximum, 8 = second largest) of each
+ The order-th smallest value (9 = maximum, 8 = second largest) of each
3x3 neighbourhood, with zero padding at the border, and NaN wherever the
- neighbourhood contains a NaN (as MATLAB's ``ordfilt2`` returns).
+ neighbourhood contains a NaN (as MATLAB's ordfilt2 returns).
+
+ Returns
+ -------
+ np.ndarray
+ The filtered image, of the same shape as a.
"""
nan = np.isnan(a)
padded = np.pad(np.where(nan, 0.0, a), 1, constant_values=0.0)
@@ -83,18 +89,21 @@ def _edges(u: np.ndarray) -> np.ndarray:
The pixel size is the median spacing of the unique centres; interior edges
are midpoints between neighbouring centres (so pixels next to a gap in the
selection are wider, as in MATLAB).
+
+ Returns
+ -------
+ np.ndarray
+ The u.size + 1 pixel edges, in increasing order.
"""
d = float(np.median(np.diff(u))) if u.size > 1 else 1.0
- return np.concatenate(
- [[u[0] - d / 2], (u[:-1] + u[1:]) / 2, [u[-1] + d / 2]]
- )
+ return np.concatenate([[u[0] - d / 2], (u[:-1] + u[1:]) / 2, [u[-1] + d / 2]])
class _IntegratedGaussians:
"""Integrated isotropic Gaussians at a fixed set of pixels.
- ``theta`` is flattened column-major like MATLAB's ``N x 4`` matrix
- ``[A, mu_y, mu_x, sigma]``: all amplitudes, then all ``mu_y``, ...
+ theta is flattened column-major like MATLAB's N x 4 matrix
+ [A, mu_y, mu_x, sigma]: all amplitudes, then all mu_y, ...
"""
def __init__(self, y: np.ndarray, x: np.ndarray) -> None:
@@ -106,9 +115,19 @@ def __init__(self, y: np.ndarray, x: np.ndarray) -> None:
self.x_lo, self.x_hi = xe[:-1][xi], xe[1:][xi]
@staticmethod
- def _axis(lo, hi, mu, s, derivs=True):
- """Integral over [lo, hi] and (with ``derivs``) its derivatives in mu
- and sigma."""
+ def _axis(
+ lo: np.ndarray, hi: np.ndarray, mu: np.ndarray, s: np.ndarray, derivs: bool = True
+ ) -> _Terms:
+ """Integral over [lo, hi] and (with derivs) its derivatives.
+
+ The derivatives are in mu and sigma.
+
+ Returns
+ -------
+ _Terms
+ The integrals (pixels x peaks) alone when derivs is False, otherwise the
+ tuple (integral, d/dmu, d/dsigma), each of that shape.
+ """
u_hi = (hi[:, None] - mu[None, :]) / (_SQRT2 * s[None, :])
u_lo = (lo[:, None] - mu[None, :]) / (_SQRT2 * s[None, :])
val = _SQRT_PI_2 * s[None, :] * (erf(u_hi) - erf(u_lo))
@@ -119,9 +138,21 @@ def _axis(lo, hi, mu, s, derivs=True):
d_s = val / s[None, :] - _SQRT2 * (u_hi * e_hi - u_lo * e_lo)
return val, d_mu, d_s
- def parts(self, theta: np.ndarray, derivs: bool = True):
- """Per-axis integrals (pixels x peaks), with their derivatives
- unless ``derivs`` is False."""
+ def parts(self, theta: np.ndarray, derivs: bool = True) -> tuple[np.ndarray, _Terms, _Terms]:
+ """Per-axis integrals (pixels x peaks).
+
+ With their derivatives unless derivs is False.
+
+ Returns
+ -------
+ a : np.ndarray
+ The amplitudes of the peaks.
+ iy : _Terms
+ The integrals over the pixels' row extents (and derivatives unless derivs
+ is False).
+ ix : _Terms
+ The same over the pixels' column extents.
+ """
n = theta.size // 4
a, my, mx = theta[:n], theta[n : 2 * n], theta[2 * n : 3 * n]
s = np.maximum(theta[3 * n :], np.finfo(float).eps)
@@ -130,100 +161,167 @@ def parts(self, theta: np.ndarray, derivs: bool = True):
return a, iy, ix
def value(self, theta: np.ndarray) -> np.ndarray:
- """Model value at each selected pixel."""
+ """Model value at each selected pixel.
+
+ Returns
+ -------
+ np.ndarray
+ The sum of the integrated Gaussians at each selected pixel.
+ """
a, vy, vx = self.parts(theta, derivs=False)
return (vy * vx) @ a
def jacobian(self, theta: np.ndarray) -> np.ndarray:
- """Jacobian (pixels x parameters), parameters column-major."""
+ """Jacobian (pixels x parameters), parameters column-major.
+
+ Returns
+ -------
+ np.ndarray
+ The Jacobian of the model value with respect to theta.
+ """
a, (vy, dmy, dsy), (vx, dmx, dsx) = self.parts(theta)
- return np.hstack(
- [vy * vx, a * dmy * vx, a * vy * dmx, a * (dsy * vx + vy * dsx)]
- )
+ return np.hstack([vy * vx, a * dmy * vx, a * vy * dmx, a * (dsy * vx + vy * dsx)])
def _eval_budget(n_par: int) -> int:
- """``max_nfev`` that gives ``least_squares`` MATLAB's iterations.
+ """max_nfev that gives least_squares MATLAB's iterations.
- ``lsqcurvefit`` with ``MaxFunEvals`` 5000 and finite differences spends
- one evaluation on the start and ``n_par + 1`` per iteration (Jacobian
- and step), so ``(5000 - 1) // (n_par + 1)`` iterations. With the
+ lsqcurvefit with MaxFunEvals 5000 and finite differences spends
+ one evaluation on the start and n_par + 1 per iteration (Jacobian
+ and step), so (5000 - 1) // (n_par + 1) iterations. With the
analytical Jacobian each iteration costs one evaluation here, plus one
for the start.
+
+ Returns
+ -------
+ int
+ The max_nfev for a fit of n_par parameters.
"""
return 1 + (_MAX_FUN_EVALS - 1) // (n_par + 1)
-def _fit(theta0, y, x, data, lb, ub):
- """lsqcurvefit-like bounded least squares of integrated Gaussians."""
+def _fit(
+ theta0: np.ndarray,
+ y: np.ndarray,
+ x: np.ndarray,
+ data: np.ndarray,
+ lb: np.ndarray,
+ ub: np.ndarray,
+) -> np.ndarray:
+ """lsqcurvefit-like bounded least squares of integrated Gaussians.
+
+ Returns
+ -------
+ np.ndarray
+ The fitted parameters, in the shape of theta0.
+ """
model = _IntegratedGaussians(y, x)
lb_f, ub_f = lb.ravel(order="F"), ub.ravel(order="F")
x0 = np.clip(theta0.ravel(order="F").astype(float), lb_f, ub_f)
max_iter = _eval_budget(x0.size)
- kw = dict(
- jac=model.jacobian,
- bounds=(lb_f, ub_f),
- method="trf",
- ftol=1e-6,
- xtol=1e-6,
- gtol=1e-6,
- max_nfev=max_iter,
- )
+ kw = {
+ "jac": model.jacobian,
+ "bounds": (lb_f, ub_f),
+ "method": "trf",
+ "ftol": 1e-6,
+ "xtol": 1e-6,
+ "gtol": 1e-6,
+ "max_nfev": max_iter,
+ }
try:
res = least_squares(lambda t: model.value(t) - data, x0, **kw)
except np.linalg.LinAlgError:
# LAPACK's SVD now and then fails to converge on a fit that succeeds
# when rerun (once in a run of 24 simulated trials under full load);
# the lsmr trust-region solver needs no SVD
- res = least_squares(
- lambda t: model.value(t) - data, x0, tr_solver="lsmr", **kw
- )
+ res = least_squares(lambda t: model.value(t) - data, x0, tr_solver="lsmr", **kw)
return res.x.reshape(theta0.shape, order="F")
-def _bounds(locs: np.ndarray, shape) -> tuple[np.ndarray, np.ndarray]:
- """getActImPeaks' bounds: positions within 1.5 px of the start."""
+def _bounds(locs: np.ndarray, shape: tuple[int, ...]) -> tuple[np.ndarray, np.ndarray]:
+ """GetActImPeaks' bounds: positions within 1.5 px of the start.
+
+ Returns
+ -------
+ lb : np.ndarray
+ Lower bounds of [A, mu_y, mu_x, sigma] for each peak.
+ ub : np.ndarray
+ Upper bounds, in the same layout.
+ """
n = locs.shape[0]
- ub = np.column_stack(
- [
- np.full(n, np.inf),
- np.minimum(shape[0] + 0.5, locs[:, 0] + 1.5),
- np.minimum(shape[1] + 0.5, locs[:, 1] + 1.5),
- np.full(n, 5.0),
- ]
- )
- lb = np.column_stack(
- [
- np.zeros(n),
- np.maximum(0.5, locs[:, 0] - 1.5),
- np.maximum(0.5, locs[:, 1] - 1.5),
- np.zeros(n),
- ]
- )
+ ub = np.column_stack([
+ np.full(n, np.inf),
+ np.minimum(shape[0] + 0.5, locs[:, 0] + 1.5),
+ np.minimum(shape[1] + 0.5, locs[:, 1] + 1.5),
+ np.full(n, 5.0),
+ ])
+ lb = np.column_stack([
+ np.zeros(n),
+ np.maximum(0.5, locs[:, 0] - 1.5),
+ np.maximum(0.5, locs[:, 1] - 1.5),
+ np.zeros(n),
+ ])
return lb, ub
def _find_f(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
- """1-based (row, col) of true pixels in MATLAB's column-major order."""
+ """1-based (row, col) of true pixels in MATLAB's column-major order.
+
+ Returns
+ -------
+ rows : np.ndarray
+ The 1-based row of each true pixel.
+ cols : np.ndarray
+ The 1-based column of each true pixel.
+ """
c, r = np.nonzero(mask.T)
return r + 1.0, c + 1.0
-def _round(x):
- """MATLAB's ``round`` (halves away from zero; numpy's go to even)."""
+def _round(x: npt.ArrayLike) -> np.ndarray | np.floating:
+ """MATLAB's round (halves away from zero; numpy's go to even).
+
+ Returns
+ -------
+ np.ndarray | np.floating
+ x rounded to the nearest integer value, halves away from zero.
+ """
x = np.asarray(x, dtype=float)
return np.sign(x) * np.floor(np.abs(x) + 0.5)
-def _rounded_index(theta: np.ndarray, shape) -> tuple[np.ndarray, np.ndarray]:
- """0-based pixel of each fitted peak (rounded and clamped)."""
+def _rounded_index(theta: np.ndarray, shape: tuple[int, ...]) -> tuple[np.ndarray, np.ndarray]:
+ """0-based pixel of each fitted peak (rounded and clamped).
+
+ Returns
+ -------
+ iy : np.ndarray
+ The 0-based row of each fitted peak.
+ ix : np.ndarray
+ The 0-based column of each fitted peak.
+ """
iy = np.clip(_round(theta[:, 1]), 1, shape[0]).astype(int) - 1
ix = np.clip(_round(theta[:, 2]), 1, shape[1]).astype(int) - 1
return iy, ix
-def _explore(res_im, buffer_mask, exclusion, reject, fit_support, sel, th):
- """getActImPeaks' search image for the next residual peak and its peak."""
+def _explore(
+ res_im: np.ndarray,
+ buffer_mask: np.ndarray,
+ exclusion: np.ndarray,
+ reject: np.ndarray,
+ fit_support: np.ndarray,
+ sel: np.ndarray,
+ th: float,
+) -> np.ndarray:
+ """GetActImPeaks' search image for the next residual peak and its peak.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean image marking the pixel of the next residual peak, or all False when no
+ candidate exceeds th.
+ """
explored = res_im * ~buffer_mask * ~exclusion * ~reject * fit_support * sel
if fit_support.any() and np.isfinite(explored).any():
top = np.nanmax(explored)
@@ -232,7 +330,7 @@ def _explore(res_im, buffer_mask, exclusion, reject, fit_support, sel, th):
return np.zeros(explored.shape, bool)
-def get_act_im_peaks( # noqa: C901
+def get_act_im_peaks(
act_im: np.ndarray,
peak_th: float,
exclusion_mask: np.ndarray | None = None,
@@ -242,7 +340,7 @@ def get_act_im_peaks( # noqa: C901
background: tuple[float, float] | None = None,
amplitude_rule: str = "matlab",
) -> np.ndarray:
- """Seed sources in a 2-D activity image (port of ``getActImPeaks.m``).
+ """Seed sources in a 2-D activity image (port of getActImPeaks.m).
Parameters
----------
@@ -256,9 +354,9 @@ def get_act_im_peaks( # noqa: C901
min_peak_distance : int
Minimum Chebyshev distance between a residual peak and fitted peaks.
fit : {'matlab', 'local'}
- ``'matlab'``: MATLAB's fits (all candidates jointly, then each
+ 'matlab': MATLAB's fits (all candidates jointly, then each
residual peak with its whole connected region, every fit stopped
- after MATLAB's evaluation budget). ``'local'``: each Gaussian only
+ after MATLAB's evaluation budget). 'local': each Gaussian only
within 10 px of its start pixel, every fit run to convergence, a
residual peak refitted with the peaks within 6 px of it (the others
held), and a rejected residual peak leaves its neighbours' previous
@@ -271,40 +369,41 @@ def get_act_im_peaks( # noqa: C901
pixels is otherwise often fitted as two peaks less than a pixel
apart.
background : (float, float), optional
- The centre and scale that ``peak_th`` counts from, in place of the
+ The centre and scale that peak_th counts from, in place of the
image's median and robust SD (MATLAB's); e.g. those of a null image
(:func:`~giant_python.extraction.raster.seeding.null_threshold`).
The centre is also the level the Gaussians are fitted above.
amplitude_rule : {'matlab', 'pixel'}
- The final test of every fitted peak. ``'matlab'``: its amplitude
- times ``pi/2 s^2 erf(1/(sqrt(2) s))^2`` (the Gaussian's mean over a
+ The final test of every fitted peak. 'matlab': its amplitude
+ times pi/2 s^2 erf(1/(sqrt(2) s))^2 (the Gaussian's mean over a
2 x 2 pixel square) must reach the threshold, which a peak narrower
than a pixel (the activity image's usual peak) fails at up to about
- four times the threshold. ``'pixel'`` (not in MATLAB): the fitted
+ four times the threshold. 'pixel' (not in MATLAB): the fitted
Gaussian's own value on the pixel its centre falls in must reach it.
Returns
-------
ndarray of shape (N, 4)
- ``[amplitude, row, col, sigma]`` of each seed, rows and columns
+ [amplitude, row, col, sigma] of each seed, rows and columns
0-based (subpixel).
+
+ Raises
+ ------
+ ValueError
+ If fit or amplitude_rule is not one of the accepted values, if merge_px is
+ negative, or if background is not a finite centre and a scale above 0.
+ RuntimeError
+ If a residual peak does not fall in any connected component of the fitted pixels.
"""
if fit not in SEED_FITS:
raise ValueError(f"fit must be one of {SEED_FITS}, not {fit!r}")
if amplitude_rule not in AMPLITUDE_RULES:
- raise ValueError(
- f"amplitude_rule must be one of {AMPLITUDE_RULES}, "
- f"not {amplitude_rule!r}"
- )
+ raise ValueError(f"amplitude_rule must be one of {AMPLITUDE_RULES}, not {amplitude_rule!r}")
if not merge_px >= 0:
raise ValueError("merge_px must be nonnegative")
act = np.asarray(act_im, dtype=float)
shape = act.shape
- excl = (
- np.zeros(shape, bool)
- if exclusion_mask is None
- else np.asarray(exclusion_mask, bool)
- )
+ excl = np.zeros(shape, bool) if exclusion_mask is None else np.asarray(exclusion_mask, bool)
min_peak_distance = max(1, int(min_peak_distance))
buffer_se = np.ones((2 * min_peak_distance - 1,) * 2, bool)
finite = ~np.isnan(act)
@@ -315,16 +414,12 @@ def get_act_im_peaks( # noqa: C901
else:
mu_bg, sigma_bg = (float(v) for v in background)
if not (np.isfinite(mu_bg) and sigma_bg > 0):
- raise ValueError(
- "background must be a finite centre and scale > 0"
- )
+ raise ValueError("background must be a finite centre and scale > 0")
peak_thresh = mu_bg + peak_th * sigma_bg
explored = act * ~excl
with np.errstate(invalid="ignore"):
- p_tmp = (ordfilt3x3(explored, 8) > peak_thresh) & (
- explored == ordfilt3x3(explored, 9)
- )
+ p_tmp = (ordfilt3x3(explored, 8) > peak_thresh) & (explored == ordfilt3x3(explored, 9))
if not p_tmp.any():
return np.zeros((0, 4))
if fit == "local":
@@ -350,15 +445,29 @@ def get_act_im_peaks( # noqa: C901
data = act[(sy - 1).astype(int), (sx - 1).astype(int)] - mu_bg
theta = _fit(theta, sy, sx, data, lb, ub)
- def fit_image(theta_now, ys, xs, fit_im):
- """Write the model of all peaks at the given pixels into fit_im."""
- fit_im[(ys - 1).astype(int), (xs - 1).astype(int)] = (
- _IntegratedGaussians(ys, xs).value(theta_now.ravel(order="F"))
+ def fit_image(
+ theta_now: np.ndarray, ys: np.ndarray, xs: np.ndarray, fit_im: np.ndarray
+ ) -> np.ndarray:
+ """Write the model of all peaks at the given pixels into fit_im.
+
+ Returns
+ -------
+ np.ndarray
+ fit_im, updated in place.
+ """
+ fit_im[(ys - 1).astype(int), (xs - 1).astype(int)] = _IntegratedGaussians(ys, xs).value(
+ theta_now.ravel(order="F")
)
return fit_im
- def peak_image(theta_now):
- """Mask of the fitted peaks' rounded positions."""
+ def peak_image(theta_now: np.ndarray) -> np.ndarray:
+ """Mask of the fitted peaks' rounded positions.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean image, True at the pixel of each fitted peak.
+ """
p_im = np.zeros(shape, bool)
iy, ix = _rounded_index(theta_now, shape)
p_im[iy, ix] = True
@@ -371,20 +480,16 @@ def peak_image(theta_now):
fit_support = fit_im > 1e-3
reject = np.zeros(shape, bool)
with np.errstate(invalid="ignore"):
- p_tmp = _explore(
- res_im, buffer_mask, excl, reject, fit_support, sel, peak_th
- )
+ p_tmp = _explore(res_im, buffer_mask, excl, reject, fit_support, sel, peak_th)
struct8 = np.ones((3, 3), bool)
while p_tmp.any():
c_new, r_new = np.nonzero(p_tmp.T)
r_new, c_new = int(r_new[0]), int(c_new[0])
- theta = np.vstack(
- [
- theta,
- [act[r_new, c_new] * _AMP_SCALE, r_new + 1, c_new + 1, 0.35],
- ]
- )
+ theta = np.vstack([
+ theta,
+ [act[r_new, c_new] * _AMP_SCALE, r_new + 1, c_new + 1, 0.35],
+ ])
locs = np.vstack([locs, [r_new + 1, c_new + 1]])
new_idx = theta.shape[0] - 1
@@ -405,8 +510,7 @@ def peak_image(theta_now):
my_new, mx_new = theta[new_idx, 1], theta[new_idx, 2]
if (
- abs(my_new - _round(my_new)) < 1e-3
- and abs(mx_new - _round(mx_new)) < 1e-3
+ abs(my_new - _round(my_new)) < 1e-3 and abs(mx_new - _round(mx_new)) < 1e-3
) or _next_to_another(theta, new_idx, merge_px):
# the new peak did not move (or ends next to another peak):
# refit the others without it, reject
@@ -426,9 +530,7 @@ def peak_image(theta_now):
sel = ndimage.binary_dilation(p_im, np.ones((9, 9), bool)) & finite
fit_support = fit_im > 1e-3
with np.errstate(invalid="ignore"):
- p_tmp = _explore(
- res_im, buffer_mask, excl, reject, fit_support, sel, peak_th
- )
+ p_tmp = _explore(res_im, buffer_mask, excl, reject, fit_support, sel, peak_th)
return _finish(
theta,
@@ -441,8 +543,14 @@ def peak_image(theta_now):
)
-def _next_to_another(theta, idx, merge_px):
- """Whether peak ``idx``'s centre is within ``merge_px`` of another's."""
+def _next_to_another(theta: np.ndarray, idx: int, merge_px: float) -> bool:
+ """Whether peak idx's centre is within merge_px of another's.
+
+ Returns
+ -------
+ bool
+ True when another peak's centre is closer than merge_px to peak idx's.
+ """
if merge_px <= 0 or theta.shape[0] < 2:
return False
d = np.hypot(theta[:, 1] - theta[idx, 1], theta[:, 2] - theta[idx, 2])
@@ -450,12 +558,19 @@ def _next_to_another(theta, idx, merge_px):
return bool(d.min() < merge_px)
-def _pixel_bounds(finite: np.ndarray):
- """1-based ``(lo, hi)`` edges of every row and of every column, as the
- local fit integrates them: from the rows and columns that hold data
+def _pixel_bounds(finite: np.ndarray) -> list[tuple[np.ndarray, np.ndarray]]:
+ """1-based (lo, hi) edges of every row and of every column.
+
+ As the local fit integrates them: from the rows and columns that hold data
(:func:`_edges`, so a pixel beside a gap is wider), unit pixels
elsewhere. (MATLAB's fit takes the edges of the pixels it fits, a
- subset; they differ only beside gaps of that subset.)"""
+ subset; they differ only beside gaps of that subset.)
+
+ Returns
+ -------
+ list[tuple[np.ndarray, np.ndarray]]
+ (lo, hi) edges of the rows, then of the columns.
+ """
out = []
for axis in (1, 0): # rows (any column finite), then columns
n = finite.shape[1 - axis]
@@ -470,23 +585,35 @@ def _pixel_bounds(finite: np.ndarray):
def _finish(
- theta, peak_thresh, excl, masked, rule="matlab", mu_bg=0.0, bounds=None
-):
- """Drop peaks too small for the threshold and (if ``masked``) peaks
- whose centre ended in the exclusion mask; 0-based ``N x 4``.
-
- ``rule`` 'matlab': getActImPeaks' test; 'pixel': the peak's own value
- (above ``mu_bg``, the level it was fitted above) on the pixel its centre
- falls in, integrated over that pixel's edges in the fits (``bounds``
+ theta: np.ndarray,
+ peak_thresh: float,
+ excl: np.ndarray,
+ masked: bool,
+ rule: str = "matlab",
+ mu_bg: float = 0.0,
+ bounds: list[tuple[np.ndarray, np.ndarray]] | None = None,
+) -> np.ndarray:
+ """Drop peaks too small for the threshold and (if masked) masked peaks.
+
+ Masked peaks are those whose centre ended in the exclusion mask; 0-based
+ N x 4.
+
+ rule 'matlab': getActImPeaks' test; 'pixel': the peak's own value
+ (above mu_bg, the level it was fitted above) on the pixel its centre
+ falls in, integrated over that pixel's edges in the fits (bounds
from :func:`_pixel_bounds`; unit pixels when None; see
- :func:`get_act_im_peaks`)."""
+ :func:`get_act_im_peaks`).
+
+ Returns
+ -------
+ np.ndarray
+ The kept peaks as N x 4 [amplitude, row, col, sigma], rows and columns 0-based.
+ """
s = np.maximum(theta[:, 3], np.finfo(float).eps)
if rule == "pixel":
iy, ix = _rounded_index(theta, excl.shape)
if bounds is None:
- (ylo, yhi), (xlo, xhi) = (
- (np.arange(n) + 0.5, np.arange(n) + 1.5) for n in excl.shape
- )
+ (ylo, yhi), (xlo, xhi) = ((np.arange(n) + 0.5, np.arange(n) + 1.5) for n in excl.shape)
else:
(ylo, yhi), (xlo, xhi) = bounds
own = theta[:, 0] * (
@@ -495,9 +622,7 @@ def _finish(
)
theta = theta[~(own + mu_bg < peak_thresh)]
else:
- adj_thresh = peak_thresh / (
- np.pi / 2 * s**2 * erf(1.0 / (_SQRT2 * s)) ** 2
- )
+ adj_thresh = peak_thresh / (np.pi / 2 * s**2 * erf(1.0 / (_SQRT2 * s)) ** 2)
theta = theta[~(theta[:, 0] < adj_thresh)]
if masked and theta.shape[0]:
# a fit may move a centre up to 1.5 px into the mask (not in MATLAB)
@@ -508,9 +633,18 @@ def _finish(
return out
-def _integral(lo, hi, mu, s, derivs=False):
- """Integral of a unit Gaussian over [lo, hi], elementwise, and (with
- ``derivs``) its derivatives in ``mu`` and ``s``."""
+def _integral(
+ lo: np.ndarray, hi: np.ndarray, mu: np.ndarray, s: np.ndarray, derivs: bool = False
+) -> _Terms:
+ """Integral of a unit Gaussian over [lo, hi], elementwise.
+
+ With derivs, also its derivatives in mu and s.
+
+ Returns
+ -------
+ _Terms
+ The integrals alone, or with derivs the tuple (integral, d/dmu, d/ds).
+ """
u_hi = (hi - mu) / (_SQRT2 * s)
u_lo = (lo - mu) / (_SQRT2 * s)
val = _SQRT_PI_2 * s * (erf(u_hi) - erf(u_lo))
@@ -525,19 +659,26 @@ def _integral(lo, hi, mu, s, derivs=False):
class _WindowedGaussians:
"""Integrated Gaussians, each only within a window of its start pixel.
- The local fit's model: peak ``k`` contributes to the data pixels within
- ``window`` pixels (Chebyshev) of its start pixel ``starts[k]`` and
+ The local fit's model: peak k contributes to the data pixels within
+ window pixels (Chebyshev) of its start pixel starts[k] and
nowhere else, so the Jacobian is sparse. Positions are parameters as
- offsets from the start pixel: ``x`` holds all amplitudes, then all row
+ offsets from the start pixel: x holds all amplitudes, then all row
offsets, column offsets and widths.
"""
- def __init__(self, idx_im, edges, starts, window, rows):
+ def __init__(
+ self,
+ idx_im: np.ndarray,
+ edges: tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray],
+ starts: np.ndarray,
+ window: int,
+ rows: np.ndarray,
+ ) -> None:
"""Pair each peak with the data pixels in its window.
- ``idx_im`` maps a pixel to its index in the data (-1 elsewhere),
- ``edges`` holds every data pixel's ``(y_lo, y_hi, x_lo, x_hi)``,
- ``starts`` the peaks' 0-based start pixels, ``rows`` the data
+ idx_im maps a pixel to its index in the data (-1 elsewhere),
+ edges holds every data pixel's (y_lo, y_hi, x_lo, x_hi),
+ starts the peaks' 0-based start pixels, rows the data
indices the model is evaluated at.
"""
h, w = idx_im.shape
@@ -562,8 +703,20 @@ def __init__(self, idx_im, edges, starts, window, rows):
st = np.asarray(starts, float).reshape(-1, 2)
self.y0, self.x0 = st[:, 0] + 1.0, st[:, 1] + 1.0
- def _pairs(self, x):
- """Amplitude, centre and width of the peak of every pixel pair."""
+ def _pairs(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Amplitude, centre and width of the peak of every pixel pair.
+
+ Returns
+ -------
+ a : np.ndarray
+ Amplitude of the peak of each pair.
+ my : np.ndarray
+ Row centre (1-based) of the peak of each pair.
+ mx : np.ndarray
+ Column centre (1-based) of the peak of each pair.
+ s : np.ndarray
+ Width of the peak of each pair.
+ """
n, k = self.n, self.k
s = np.maximum(x[3 * n :], np.finfo(float).eps)
return (
@@ -573,15 +726,27 @@ def _pairs(self, x):
s[k],
)
- def value(self, x):
- """Model value at each of the rows."""
+ def value(self, x: np.ndarray) -> np.ndarray:
+ """Model value at each of the rows.
+
+ Returns
+ -------
+ np.ndarray
+ The summed windowed Gaussians at each of the m data rows.
+ """
a, my, mx, s = self._pairs(x)
vy = _integral(self.lo_y, self.hi_y, my, s)
vx = _integral(self.lo_x, self.hi_x, mx, s)
return np.bincount(self.p, a * vy * vx, minlength=self.m)
- def jacobian(self, x, dense):
- """Jacobian (rows x parameters), dense or sparse (CSR)."""
+ def jacobian(self, x: np.ndarray, dense: bool) -> np.ndarray | sparse.csr_matrix:
+ """Jacobian (rows x parameters), dense or sparse (CSR).
+
+ Returns
+ -------
+ np.ndarray | sparse.csr_matrix
+ The Jacobian of the model value, dense when dense is True, else CSR.
+ """
a, my, mx, s = self._pairs(x)
vy, dmy, dsy = _integral(self.lo_y, self.hi_y, my, s, True)
vx, dmx, dsx = _integral(self.lo_x, self.hi_x, mx, s, True)
@@ -607,58 +772,73 @@ def jacobian(self, x, dense):
)
-def _to_offsets(theta, starts):
- """``N x 4`` [A, mu_y, mu_x, sigma] (1-based) as the local fit's x."""
- return np.concatenate(
- [
- theta[:, 0],
- theta[:, 1] - (starts[:, 0] + 1),
- theta[:, 2] - (starts[:, 1] + 1),
- theta[:, 3],
- ]
- )
+def _to_offsets(theta: np.ndarray, starts: np.ndarray) -> np.ndarray:
+ """N x 4 [A, mu_y, mu_x, sigma] (1-based) as the local fit's x.
+
+ Returns
+ -------
+ np.ndarray
+ The flattened parameters: amplitudes, then row offsets, column offsets and widths.
+ """
+ return np.concatenate([
+ theta[:, 0],
+ theta[:, 1] - (starts[:, 0] + 1),
+ theta[:, 2] - (starts[:, 1] + 1),
+ theta[:, 3],
+ ])
-def _from_offsets(x, starts):
- """The local fit's x as ``N x 4`` [A, mu_y, mu_x, sigma] (1-based)."""
+def _from_offsets(x: np.ndarray, starts: np.ndarray) -> np.ndarray:
+ """Convert the local fit's x to N x 4 [A, mu_y, mu_x, sigma] (1-based).
+
+ Returns
+ -------
+ np.ndarray
+ The N x 4 peak parameters.
+ """
n = starts.shape[0]
- return np.column_stack(
- [
- x[:n],
- x[n : 2 * n] + starts[:, 0] + 1,
- x[2 * n : 3 * n] + starts[:, 1] + 1,
- x[3 * n :],
- ]
- )
+ return np.column_stack([
+ x[:n],
+ x[n : 2 * n] + starts[:, 0] + 1,
+ x[2 * n : 3 * n] + starts[:, 1] + 1,
+ x[3 * n :],
+ ])
+
+def _offset_bounds(starts: np.ndarray, shape: tuple[int, ...]) -> tuple[np.ndarray, np.ndarray]:
+ """GetActImPeaks' bounds as offsets.
-def _offset_bounds(starts, shape):
- """getActImPeaks' bounds as offsets: within 1.5 px of the start pixel
- and inside the image; widths in [0, 5]."""
+ Within 1.5 px of the start pixel and inside the image; widths in [0, 5].
+
+ Returns
+ -------
+ lb : np.ndarray
+ Lower bounds of the offset parameters.
+ ub : np.ndarray
+ Upper bounds of the offset parameters.
+ """
n = starts.shape[0]
y0, x0 = starts[:, 0] + 1.0, starts[:, 1] + 1.0
- lb = np.concatenate(
- [
- np.zeros(n),
- np.maximum(0.5 - y0, -1.5),
- np.maximum(0.5 - x0, -1.5),
- np.zeros(n),
- ]
- )
- ub = np.concatenate(
- [
- np.full(n, np.inf),
- np.minimum(shape[0] + 0.5 - y0, 1.5),
- np.minimum(shape[1] + 0.5 - x0, 1.5),
- np.full(n, 5.0),
- ]
- )
+ lb = np.concatenate([
+ np.zeros(n),
+ np.maximum(0.5 - y0, -1.5),
+ np.maximum(0.5 - x0, -1.5),
+ np.zeros(n),
+ ])
+ ub = np.concatenate([
+ np.full(n, np.inf),
+ np.minimum(shape[0] + 0.5 - y0, 1.5),
+ np.minimum(shape[1] + 0.5 - x0, 1.5),
+ np.full(n, 5.0),
+ ])
return lb, ub
-def _cover(cover, pix, sign):
- """Add ``sign`` to the 9 x 9 squares around pixels (``cover`` is padded
- by 4 on every side)."""
+def _cover(cover: np.ndarray, pix: np.ndarray, sign: int) -> None:
+ """Add sign to the 9 x 9 squares around pixels.
+
+ cover is padded by 4 on every side.
+ """
for r, c in pix:
cover[r : r + 9, c : c + 9] += sign
@@ -666,11 +846,18 @@ def _cover(cover, pix, sign):
class _LocalFit:
"""getActImPeaks' search with windowed, converged, local fits.
- See :func:`get_act_im_peaks` (``fit='local'``). Peaks are kept as
- 1-based ``theta`` rows with their 0-based start pixels.
+ See :func:`get_act_im_peaks` (fit='local'). Peaks are kept as
+ 1-based theta rows with their 0-based start pixels.
"""
- def __init__(self, act, background, peak_th, excl, buffer_se):
+ def __init__(
+ self,
+ act: np.ndarray,
+ background: tuple[float, float],
+ peak_th: float,
+ excl: np.ndarray,
+ buffer_se: np.ndarray,
+ ) -> None:
"""Index the image's finite pixels and their pixel edges."""
self.act, self.shape = act, act.shape
self.mu_bg, self.sigma_bg = background
@@ -686,24 +873,46 @@ def __init__(self, act, background, peak_th, excl, buffer_se):
self.edges = (ye[:-1][yi], ye[1:][yi], xe[:-1][xi], xe[1:][xi])
self.data = act[rows, cols] - self.mu_bg
- def rows_of(self, mask):
- """Sorted data indices of the pixels of a mask."""
+ def rows_of(self, mask: np.ndarray) -> np.ndarray:
+ """Sorted data indices of the pixels of a mask.
+
+ Returns
+ -------
+ np.ndarray
+ The sorted data indices of the mask's pixels that hold data.
+ """
r = self.idx_im[mask]
return np.sort(r[r >= 0])
- def solve(self, theta, starts, rows, fixed=None):
- """Fit peaks to the data at ``rows`` (minus ``fixed``)."""
- model = _WindowedGaussians(
- self.idx_im, self.edges, starts, _LOCAL_WINDOW, rows
- )
+ def solve(
+ self,
+ theta: np.ndarray,
+ starts: np.ndarray,
+ rows: np.ndarray,
+ fixed: np.ndarray | None = None,
+ ) -> np.ndarray:
+ """Fit peaks to the data at rows (minus fixed).
+
+ Returns
+ -------
+ np.ndarray
+ The fitted peaks as N x 4 [A, mu_y, mu_x, sigma] (1-based).
+ """
+ model = _WindowedGaussians(self.idx_im, self.edges, starts, _LOCAL_WINDOW, rows)
target = self.data[rows]
if fixed is not None:
target = target - fixed
lb, ub = _offset_bounds(starts, self.shape)
start = np.clip(_to_offsets(theta, starts), lb, ub)
- def run(dense):
- """least_squares with a dense (SVD) or sparse (lsmr) solver."""
+ def run(dense: bool) -> OptimizeResult:
+ """least_squares with a dense (SVD) or sparse (lsmr) solver.
+
+ Returns
+ -------
+ OptimizeResult
+ The result of the fit.
+ """
return least_squares(
lambda x: model.value(x) - target,
start,
@@ -726,8 +935,14 @@ def run(dense):
res = run(False)
return _from_offsets(res.x, starts)
- def model_at(self, theta, starts, rows):
- """All peaks' model at ``rows`` (peaks whose window reaches them)."""
+ def model_at(self, theta: np.ndarray, starts: np.ndarray, rows: np.ndarray) -> np.ndarray:
+ """All peaks' model at rows (peaks whose window reaches them).
+
+ Returns
+ -------
+ np.ndarray
+ The model value at each of rows.
+ """
if rows.size == 0 or theta.shape[0] == 0:
return np.zeros(rows.size)
ry, rx = self.ry[rows], self.rx[rows]
@@ -740,13 +955,21 @@ def model_at(self, theta, starts, rows):
)
if not near.any():
return np.zeros(rows.size)
- model = _WindowedGaussians(
- self.idx_im, self.edges, starts[near], w, rows
- )
+ model = _WindowedGaussians(self.idx_im, self.edges, starts[near], w, rows)
return model.value(_to_offsets(theta[near], starts[near]))
- def explore(self, fit_im, pix, cover, reject):
- """The next residual peak (mask) and the fitted peaks' region."""
+ def explore(
+ self, fit_im: np.ndarray, pix: np.ndarray, cover: np.ndarray, reject: np.ndarray
+ ) -> tuple[np.ndarray, np.ndarray]:
+ """Find the next residual peak (mask) and the fitted peaks' region.
+
+ Returns
+ -------
+ new : np.ndarray
+ Boolean mask of the next residual peak (all False when there is none).
+ sel : np.ndarray
+ Boolean mask of the region around the fitted peaks (finite pixels only).
+ """
sel = (cover[4:-4, 4:-4] > 0) & self.finite
p_im = np.zeros(self.shape, bool)
p_im[pix[:, 0], pix[:, 1]] = True
@@ -768,29 +991,29 @@ def explore(self, fit_im, pix, cover, reject):
)
return new, sel
- def run(self, cand, merge_px):
- """Fit the candidates, then add residual peaks; ``N x 4`` theta."""
+ def run(self, cand: np.ndarray, merge_px: float) -> np.ndarray:
+ """Fit the candidates, then add residual peaks; N x 4 theta.
+
+ Returns
+ -------
+ np.ndarray
+ The fitted peaks as N x 4 [A, mu_y, mu_x, sigma] (1-based).
+ """
c, r = np.nonzero(cand.T)
starts = np.column_stack([r, c]).astype(int)
- theta = np.column_stack(
- [
- self.act[r, c] * _AMP_SCALE,
- starts + 1.0,
- np.full(len(starts), _SIGMA0),
- ]
- )
+ theta = np.column_stack([
+ self.act[r, c] * _AMP_SCALE,
+ starts + 1.0,
+ np.full(len(starts), _SIGMA0),
+ ])
sel0 = ndimage.binary_dilation(cand, np.ones((9, 9), bool))
rows = self.rows_of(sel0 & self.finite)
theta = self.solve(theta, starts, rows)
# the model everywhere the peaks' windows reach
side = 2 * _LOCAL_WINDOW + 1
- reach = self.rows_of(
- ndimage.binary_dilation(cand, np.ones((side, side), bool))
- )
+ reach = self.rows_of(ndimage.binary_dilation(cand, np.ones((side, side), bool)))
fit_im = np.zeros(self.shape)
- fit_im[self.ry[reach], self.rx[reach]] = self.model_at(
- theta, starts, reach
- )
+ fit_im[self.ry[reach], self.rx[reach]] = self.model_at(theta, starts, reach)
pix = np.column_stack(_rounded_index(theta, self.shape))
# how many peaks' 9 x 9 squares cover each pixel (padded by 4)
cover = np.zeros((self.shape[0] + 8, self.shape[1] + 8), np.int32)
@@ -811,12 +1034,28 @@ def run(self, cand, merge_px):
new, sel = self.explore(fit_im, pix, cover, reject)
return theta
- def _add(self, theta, starts, pix, sel, fit_im, rc, merge_px):
+ def _add(
+ self,
+ theta: np.ndarray,
+ starts: np.ndarray,
+ pix: np.ndarray,
+ sel: np.ndarray,
+ fit_im: np.ndarray,
+ rc: tuple[int, int],
+ merge_px: float,
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] | None:
"""Fit a residual peak with its neighbours; None if rejected.
- Updates ``fit_im`` in place when the peak is kept and returns the
+ Updates fit_im in place when the peak is kept and returns the
new theta and starts, the indices of the peaks that changed and the
pixels those had before.
+
+ Returns
+ -------
+ tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] | None
+ (theta, starts, changed, old): the new theta and starts, the indices of the
+ peaks that changed and the pixels those had before; None if the residual peak
+ is rejected.
"""
r_n, c_n = rc
labels, _ = ndimage.label(sel, structure=np.ones((3, 3), bool))
@@ -825,12 +1064,10 @@ def _add(self, theta, starts, pix, sel, fit_im, rc, merge_px):
dist = np.hypot(theta[:, 1] - (r_n + 1), theta[:, 2] - (c_n + 1))
free = in_comp & (dist <= _LOCAL_REFIT_RADIUS)
f_starts = np.vstack([starts[free], [[r_n, c_n]]])
- f_theta = np.vstack(
- [
- theta[free],
- [[self.act[r_n, c_n] * _AMP_SCALE, r_n + 1, c_n + 1, _SIGMA0]],
- ]
- )
+ f_theta = np.vstack([
+ theta[free],
+ [[self.act[r_n, c_n] * _AMP_SCALE, r_n + 1, c_n + 1, _SIGMA0]],
+ ])
region = np.zeros(self.shape, bool)
w = _LOCAL_WINDOW
for r, c in f_starts:
@@ -860,7 +1097,5 @@ def _add(self, theta, starts, pix, sel, fit_im, rc, merge_px):
# refresh the model wherever the refitted peaks' windows reach,
# beyond their region too
reach = self.rows_of(region)
- fit_im[self.ry[reach], self.rx[reach]] = self.model_at(
- theta, starts, reach
- )
+ fit_im[self.ry[reach], self.rx[reach]] = self.model_at(theta, starts, reach)
return theta, starts, changed, old
diff --git a/src/giant_python/extraction/raster/plan.py b/src/giant_python/extraction/raster/plan.py
index 9d730525..15a664a4 100644
--- a/src/giant_python/extraction/raster/plan.py
+++ b/src/giant_python/extraction/raster/plan.py
@@ -1,13 +1,13 @@
"""SiLo's path-level plan: alignment, sources, pixels and subproblems.
-Port of what GIAnT-MATLAB's ``SILo.m`` (main at 5a0673b) does for one imaging
+Port of what GIAnT-MATLAB's SILo.m (main at 5a0673b) does for one imaging
path between the per-trial localizations and the extraction of the trials,
-and of the grouping at the top of ``extractTrial.m``:
+and of the grouping at the top of extractTrial.m:
1. the trials' mean and activity images are put on one canvas and aligned
(:mod:`~giant_python.extraction.raster.alignment`): a shift per trial,
refined for the valid trials to an affine map or a patchwise field
- (``inter_trial_alignment``);
+ (inter_trial_alignment);
2. valid trials are those whose mean image matches the template and whose
activity image covers enough pixels; their aligned activity images are
averaged into the combined activity image, minus its local median;
@@ -18,32 +18,35 @@
(:func:`group_sources`), which are the same in every trial.
The result is an :class:`ExtractionPlan`, stored with :func:`write_plan` and
-:func:`read_plan` (``extraction_plan.h5``).
+:func:`read_plan` (extraction_plan.h5).
Conventions shared with the trial loader and the subproblem solver. The
-consensus frame is the across-trial aligned pixel grid ``(rows, cols)`` of
+consensus frame is the across-trial aligned pixel grid (rows, cols) of
the path, in MATLAB's orientation and zero-based. The selected pixels are
listed in MATLAB's column-major order of the selected-pixel map
-(``find(selPix)``), so that index ``k`` of the list is row ``k`` of MATLAB's
+(find(selPix)), so that index k of the list is row k of MATLAB's
data and footprints. A subproblem (:class:`SubproblemGroup`) holds indices
into that list and into the path's source list, and a crop of the map.
"""
from __future__ import annotations
+import itertools
import json
import math
import warnings
+from collections.abc import Callable, Sequence
from dataclasses import asdict, dataclass, field
from pathlib import Path
-from typing import Optional, Sequence
import h5py
import numpy as np
-import scipy.ndimage as ndimage
+import numpy.typing as npt
+from scipy import ndimage
from ...parallel import check_workers
from .alignment import (
+ AlignmentInfo,
TrialWarp,
align_trials,
align_trials_affine,
@@ -52,7 +55,7 @@
matlab_round,
warp_trial_image,
)
-from .localization import nanmedfilt2
+from .localization import RasterLocalization, nanmedfilt2
from .peaks import AMPLITUDE_RULES, SEED_FITS
from .seeding import (
SEED_ACCEPTANCE,
@@ -63,6 +66,7 @@
sources_from_seeds,
)
from .solver_setup import Subproblem
+from .trial import RegisteredTrial
from .trial_data import RigidShift
from .wmf import find_sources_wmf
@@ -79,69 +83,69 @@ class PlanParams:
----------
nan_thresh : float
Largest fraction of valid trials in which a pixel may be missing
- (``nanThresh``).
+ (nanThresh).
max_shift : int
Search range of the across-trial alignment and margin of its
- template (``maxshift`` in ``SILo.m``).
+ template (maxshift in SILo.m).
align_clip : float
- ``clip`` of the whole-pixel estimate (80 in ``SILo.m``).
+ clip of the whole-pixel estimate (80 in SILo.m).
template_trials : int
Largest number of trials the template is made from (20).
max_corr_thresh : float
Upper limit of the correlation a valid trial must exceed (0.90).
inter_trial_alignment : str
- ``"rigid"`` (a shift per trial), ``"affine"`` (an affine map per
- valid trial) or ``"patchwise"`` (a smooth displacement field per
+ "rigid" (a shift per trial), "affine" (an affine map per
+ valid trial) or "patchwise" (a smooth displacement field per
valid trial on top of its affine plane; the default)
- (``interTrialAlignment``).
+ (interTrialAlignment).
align_patch_px : float
- Imaged pixels per patch of the patchwise field (``alignPatchPx``).
+ Imaged pixels per patch of the patchwise field (alignPatchPx).
peak_method : str
- ``"getactimpeaks"`` fits Gaussian peaks in the combined image.
- ``"wmf"`` uses whitened matched filtering of the aligned activity
- images when at least four valid trials have data (``peakMethod``).
+ "getactimpeaks" fits Gaussian peaks in the combined image.
+ "wmf" uses whitened matched filtering of the aligned activity
+ images when at least four valid trials have data (peakMethod).
wmf_peak_th, wmf_dip, wmf_deblend_th : float
Minimum matched-filter peak, intervening dip and residual peak in
- robust SDs (``wmfPeakth``, ``wmfDip``, ``wmfDeblendth``). Positive
+ robust SDs (wmfPeakth, wmfDip, wmfDeblendth). Positive
infinity skips the deblending fit.
seed_fit : str
- ``"local"`` (the default: local Gaussian fits run to convergence,
- seconds per path) or ``"matlab"`` (MATLAB's capped joint fits). See
+ "local" (the default: local Gaussian fits run to convergence,
+ seconds per path) or "matlab" (MATLAB's capped joint fits). See
:func:`~giant_python.extraction.raster.peaks.get_act_im_peaks`.
seed_merge_px : float
Reject a residual peak that ends closer than this to another peak
(default 1.5; 0: MATLAB's rule only).
peak_th : float
Seed threshold in robust SDs of the combined activity image
- (``peakth``: 3 for SLAP2, 8 otherwise).
+ (peakth: 3 for SLAP2, 8 otherwise).
seed_acceptance : str
- ``"image"`` (the default, MATLAB's): ``peak_th`` counts in robust
- SDs of the combined image. ``"null"``: the threshold is set from
- the combined image's null so that ``seed_false_per_field`` false
+ "image" (the default, MATLAB's): peak_th counts in robust
+ SDs of the combined image. "null": the threshold is set from
+ the combined image's null so that seed_false_per_field false
seeds are expected per path (needs every valid trial's null images,
- :attr:`TrialImages.null_im`; ``peak_th`` is then not used). See
+ :attr:`TrialImages.null_im`; peak_th is then not used). See
:func:`~giant_python.extraction.raster.seeding.null_threshold`.
- ``"null_sd"``: ``peak_th`` counts in robust SDs of that null.
+ "null_sd": peak_th counts in robust SDs of that null.
seed_false_per_field : float
- Expected false seeds per path with ``seed_acceptance="null"``.
+ Expected false seeds per path with seed_acceptance="null".
seed_amplitude_rule : str
- The seeding's final test of each fitted peak: ``"matlab"`` (the
- default) or ``"pixel"`` (its value on its own pixel; see
+ The seeding's final test of each fitted peak: "matlab" (the
+ default) or "pixel" (its value on its own pixel; see
:func:`~giant_python.extraction.raster.peaks.get_act_im_peaks`).
min_peak_distance : int
- ``minPeakDistance``.
+ minPeakDistance.
d_xy : float
- How large sources can be, in pixels (``dXY``).
+ How large sources can be, in pixels (dXY).
sigma_px : float
- Gaussian sigma of the PSF in pixels (``sigma_px``).
+ Gaussian sigma of the PSF in pixels (sigma_px).
valid_kernel : int
- Side of the footprints' support (``validKernel``; 5 by default,
+ Side of the footprints' support (validKernel; 5 by default,
MATLAB's is 3), which widens the zones that group sources.
min_source_pixels : int
A source needs more selected pixels than this (5).
warp_interp : {'linear', 'cubic', 'cubic_clamped'}
Interpolation of trial activity, null, and mean images into the
- consensus frame (MATLAB's: ``'linear'``).
+ consensus frame (MATLAB's: 'linear').
"""
nan_thresh: float = 0.33
@@ -169,7 +173,13 @@ class PlanParams:
wmf_deblend_th: float = 8.0
def __post_init__(self) -> None:
- """Validate the option values."""
+ """Validate the option values.
+
+ Raises
+ ------
+ ValueError
+ If an option has a value that is not allowed.
+ """
if self.warp_interp not in ("linear", "cubic", "cubic_clamped"):
raise ValueError(
"warp_interp must be 'linear', 'cubic', or 'cubic_clamped', "
@@ -182,13 +192,10 @@ def __post_init__(self) -> None:
)
if self.peak_method not in SEEDING_METHODS:
raise ValueError(
- f"peak_method must be one of {SEEDING_METHODS}, "
- f"not {self.peak_method!r}"
+ f"peak_method must be one of {SEEDING_METHODS}, not {self.peak_method!r}"
)
if self.seed_fit not in SEED_FITS:
- raise ValueError(
- f"seed_fit must be one of {SEED_FITS}, not {self.seed_fit!r}"
- )
+ raise ValueError(f"seed_fit must be one of {SEED_FITS}, not {self.seed_fit!r}")
if not self.seed_merge_px >= 0:
raise ValueError("seed_merge_px must be nonnegative")
self._check_acceptance()
@@ -207,7 +214,13 @@ def __post_init__(self) -> None:
raise ValueError("align_patch_px must be at least 1 pixel")
def _check_acceptance(self) -> None:
- """Validate the seed threshold's settings."""
+ """Validate the seed threshold's settings.
+
+ Raises
+ ------
+ ValueError
+ If a setting has a value that is not allowed.
+ """
for name in ("wmf_peak_th", "wmf_dip"):
if not 0 <= getattr(self, name) < math.inf:
raise ValueError(f"{name} must be finite and nonnegative")
@@ -217,8 +230,7 @@ def _check_acceptance(self) -> None:
object.__setattr__(self, "wmf_deblend_th", float(self.wmf_deblend_th))
if self.seed_acceptance not in SEED_ACCEPTANCE:
raise ValueError(
- f"seed_acceptance must be one of {SEED_ACCEPTANCE}, "
- f"not {self.seed_acceptance!r}"
+ f"seed_acceptance must be one of {SEED_ACCEPTANCE}, not {self.seed_acceptance!r}"
)
if not self.seed_false_per_field > 0:
raise ValueError("seed_false_per_field must be positive")
@@ -230,7 +242,7 @@ def _check_acceptance(self) -> None:
@property
def sel_radius(self) -> int:
- """Radius of a source's selected pixels (``selRadius``)."""
+ """Radius of a source's selected pixels (selRadius)."""
return math.ceil(2 * self.d_xy)
@property
@@ -246,9 +258,9 @@ class TrialImages:
Attributes
----------
mean_im : ndarray of shape (rows, cols, channels)
- The trial's mean image (``RegisteredTrial.mean_im``).
+ The trial's mean image (RegisteredTrial.mean_im).
act_im : ndarray of shape (rows, cols)
- The trial's activity image (``RasterLocalization.act_im``).
+ The trial's activity image (RasterLocalization.act_im).
peaks : ndarray of shape (n, 4), optional
The trial's own seeds, carried into the plan.
discard : ndarray of bool, optional
@@ -257,8 +269,8 @@ class TrialImages:
Mean images of two halves of the trial's frames, which weight the
patchwise alignment's patches (only that mode uses them).
null_im : ndarray of shape (draws, rows, cols), optional
- The trial's null activity images, calibrated like ``act_im``
- (``seed_acceptance="null"`` combines them as the activity images).
+ The trial's null activity images, calibrated like act_im
+ (seed_acceptance="null" combines them as the activity images).
"""
mean_im: np.ndarray
@@ -269,10 +281,20 @@ class TrialImages:
null_im: np.ndarray | None = None
@classmethod
- def from_localization(cls, localization, trial) -> "TrialImages":
- """From the two results of
+ def from_localization(
+ cls, localization: RasterLocalization, trial: RegisteredTrial
+ ) -> TrialImages:
+ """Build the images from the two results of localize_trial.
+
+ The two results are those of
:func:`~giant_python.extraction.raster.trial.localize_trial` (with
- the bootstrap null's images, when the localization drew them)."""
+ the bootstrap null's images, when the localization drew them).
+
+ Returns
+ -------
+ TrialImages
+ The trial's images, peaks, discarded frames, half images and null images.
+ """
return cls(
trial.mean_im,
localization.act_im,
@@ -296,8 +318,8 @@ class SubproblemGroup:
row0, col0 : int
Origin of the crop in the consensus frame.
sel : ndarray of bool, shape (crop rows, crop cols)
- The group's pixels within the crop (MATLAB's ``selPix_p``); its
- column-major order is the order of ``pixels``.
+ The group's pixels within the crop (MATLAB's selPix_p); its
+ column-major order is the order of pixels.
sources_rc : ndarray of int, shape (n, 2)
The sources' positions within the crop.
"""
@@ -313,19 +335,19 @@ def subproblem(
self,
y: np.ndarray,
finv: np.ndarray,
- baseline: Optional[np.ndarray] = None,
+ baseline: np.ndarray | None = None,
) -> Subproblem:
- """The group's subproblem in one trial.
+ """Return the group's subproblem in one trial.
Parameters
----------
y : ndarray of shape (channels, pixels, frames)
The trial's data at all of the path's selected pixels
- (``TrialData.y``).
+ (TrialData.y).
finv : ndarray of shape (pixels, frames)
- Its variance multiplier (``TrialData.finv``).
+ Its variance multiplier (TrialData.finv).
baseline : ndarray of shape (pixels, frames), optional
- The group's external baseline (``Subproblem.baseline``), at the
+ The group's external baseline (Subproblem.baseline), at the
group's pixels only.
Returns
@@ -346,23 +368,25 @@ def subproblem(
)
-def loader_warp(warp: TrialWarp, trial: int):
- """A trial's across-trial map in the form the trial loader takes.
+def loader_warp(
+ warp: TrialWarp, trial: int
+) -> RigidShift | Callable[[npt.ArrayLike, npt.ArrayLike], tuple[np.ndarray, np.ndarray]]:
+ """Return a trial's across-trial map in the form the trial loader takes.
Parameters
----------
warp : TrialWarp
- The plan's alignment (``ExtractionPlan.warp``).
+ The plan's alignment (ExtractionPlan.warp).
trial : int
Zero-based trial; it must have been aligned.
Returns
-------
RigidShift or callable
- The trial's shift (added to its motion, MATLAB's ``isShift`` path),
+ The trial's shift (added to its motion, MATLAB's isShift path),
or, for an affine map or a patchwise field, a function from
- zero-based consensus ``(rows, cols)`` to zero-based positions in
- the trial's registered frame (MATLAB's ``trialWarpCoords`` path).
+ zero-based consensus (rows, cols) to zero-based positions in
+ the trial's registered frame (MATLAB's trialWarpCoords path).
Raises
------
@@ -375,16 +399,31 @@ def loader_warp(warp: TrialWarp, trial: int):
row, col = warp.shift(trial)
return RigidShift(float(row), float(col))
- def coords(rows, cols):
- """Consensus to trial-frame positions (zero-based)."""
+ def coords(rows: npt.ArrayLike, cols: npt.ArrayLike) -> tuple[np.ndarray, np.ndarray]:
+ """Return the trial-frame positions (zero-based) of consensus points.
+
+ Returns
+ -------
+ rows_t, cols_t : ndarray
+ The points' coordinates in the trial's registered frame.
+ """
return warp.coords(trial, rows, cols)
return coords
def _matlab_order_labels(zones: np.ndarray) -> tuple[np.ndarray, int]:
- """4-connected components numbered as MATLAB's ``bwconncomp(z, 4)``: by
- their first pixel in column-major order (labels from 1)."""
+ """Label the 4-connected components as MATLAB's bwconncomp(z, 4) does.
+
+ They are numbered by their first pixel in column-major order (labels from 1).
+
+ Returns
+ -------
+ labels : np.ndarray
+ The label of each pixel of zones (0 outside the components).
+ n : int
+ The number of components.
+ """
labels, n = ndimage.label(zones.T)
flat = labels.ravel() # column-major order of zones
_, first = np.unique(flat, return_index=True)
@@ -397,9 +436,21 @@ def _matlab_order_labels(zones: np.ndarray) -> tuple[np.ndarray, int]:
def _group_pixels(
rows: np.ndarray, cols: np.ndarray, sel: np.ndarray, nhood: np.ndarray
) -> tuple[np.ndarray, int, int]:
- """A group's selected pixels (cropped) and the crop's origin.
+ """Return a group's selected pixels (cropped) and the crop's origin.
+
+ The disks of nhood around the group's sources, within sel.
- The disks of ``nhood`` around the group's sources, within ``sel``.
+ Returns
+ -------
+ crop : np.ndarray
+ The group's selected pixels within the crop.
+ row0, col0 : int
+ The crop's origin in the consensus frame.
+
+ Raises
+ ------
+ ValueError
+ If the group has no selected pixels.
"""
h, w = sel.shape
half = (nhood.shape[0] - 1) // 2
@@ -424,12 +475,12 @@ def group_sources(
zone_radius: int,
sel_radius: int,
) -> list[SubproblemGroup]:
- """Group sources into separable subproblems (as ``extractTrial.m``).
+ """Group sources into separable subproblems (as extractTrial.m).
- A disk of ``zone_radius`` is put on every source; sources whose disks
+ A disk of zone_radius is put on every source; sources whose disks
are 4-connected form a group. A group's pixels are the selected pixels
- within ``sel_radius`` disks of its sources, cropped to their bounding
- box. Groups are in MATLAB's order (``bwconncomp``: by the first pixel of
+ within sel_radius disks of its sources, cropped to their bounding
+ box. Groups are in MATLAB's order (bwconncomp: by the first pixel of
their zone, column by column), and so are each group's sources and
pixels.
@@ -466,9 +517,7 @@ def group_sources(
for g in range(1, n_groups + 1):
src = np.flatnonzero(source_label == g)
crop, row0, col0 = _group_pixels(rows[src], cols[src], sel, nhood)
- index = sel_index[
- row0 : row0 + crop.shape[0], col0 : col0 + crop.shape[1]
- ]
+ index = sel_index[row0 : row0 + crop.shape[0], col0 : col0 + crop.shape[1]]
groups.append(
SubproblemGroup(
sources=src,
@@ -476,9 +525,7 @@ def group_sources(
row0=row0,
col0=col0,
sel=crop,
- sources_rc=np.column_stack(
- [rows[src] - row0, cols[src] - col0]
- ),
+ sources_rc=np.column_stack([rows[src] - row0, cols[src] - col0]),
)
)
return groups
@@ -489,8 +536,8 @@ class ExtractionPlan:
"""The plan of one imaging path: what every trial's extraction shares.
Images are in MATLAB's orientation; trials, sources and pixels are
- zero-based. ``T`` trials, ``(H, W)`` consensus frame, ``C`` channels,
- ``N`` sources, ``P`` selected pixels.
+ zero-based. T trials, (H, W) consensus frame, C channels,
+ N sources, P selected pixels.
Attributes
----------
@@ -503,11 +550,11 @@ class ExtractionPlan:
template_trials : ndarray of int
Trials the template was made from.
shifts : ndarray of shape (T, 2)
- Each trial's shift ``(rows, cols)``: consensus pixel ``(r, c)`` is
- at ``(r, c) + shift`` in the trial's registered image; NaN for
- trials that were not aligned (MATLAB's ``motOutput``). For an
+ Each trial's shift (rows, cols): consensus pixel (r, c) is
+ at (r, c) + shift in the trial's registered image; NaN for
+ trials that were not aligned (MATLAB's motOutput). For an
affine or patchwise alignment, the displacement at the canvas
- centre (the offsets of the motion records); ``warp`` holds the
+ centre (the offsets of the motion records); warp holds the
maps.
corr : ndarray of shape (T,)
Correlation of each trial's mean image with the template.
@@ -538,12 +585,12 @@ class ExtractionPlan:
px_always_valid : ndarray of bool, shape (H, W)
Pixels imaged in enough of the valid trials.
seeds : ndarray of shape (n_seeds, 4)
- ``[value, row, col, sigma]`` of every seed. WMF stores the filtered
+ [value, row, col, sigma] of every seed. WMF stores the filtered
peak value and NaN for the Gaussian width.
source_rows, source_cols : ndarray of int, shape (N,)
The sources' pixels.
source_values : ndarray of shape (N,)
- The sources' seed values (``sources.V``). Gaussian seeding stores
+ The sources' seed values (sources.V). Gaussian seeding stores
fitted amplitudes, including on fallback. WMF stores matched-filter
scores of the peaks or deblending residual peaks.
sel : ndarray of bool, shape (H, W)
@@ -560,7 +607,7 @@ class ExtractionPlan:
frame_offset : ndarray of int, shape (T, 2), optional
Where each trial's registered image starts on the raster, relative
to the earliest kept trial (rows, columns; zero unless the ROIs
- changed between acquisitions). ``shifts`` and ``warp`` include it.
+ changed between acquisitions). shifts and warp include it.
None in plans made before it existed (all zero).
"""
@@ -619,14 +666,28 @@ def aligned_trials(self) -> np.ndarray:
return np.flatnonzero(self.warp.aligned)
def selected_pixels(self) -> tuple[np.ndarray, np.ndarray]:
- """Rows and columns of the selected-pixel list (the order of
- MATLAB's ``find(selPix)``: column by column)."""
+ """Return the rows and columns of the selected-pixel list.
+
+ The order is that of MATLAB's find(selPix): column by column.
+
+ Returns
+ -------
+ rows, cols : np.ndarray
+ The row and the column of each selected pixel, in list order.
+ """
cols, rows = np.nonzero(self.sel.T)
return rows, cols
def source_mask(self, source: int) -> np.ndarray:
- """One source's selected pixels as a map (a slice of MATLAB's
- ``selPix``)."""
+ """Return one source's selected pixels as a map.
+
+ The map is a slice of MATLAB's selPix.
+
+ Returns
+ -------
+ np.ndarray
+ A boolean map of the consensus frame, True at the source's selected pixels.
+ """
rows, cols = self.selected_pixels()
mask = np.zeros(self.shape, bool)
index = self.source_pixels[source]
@@ -637,7 +698,7 @@ def source_mask(self, source: int) -> np.ndarray:
def read_frame_origins(alignment_files: Sequence) -> np.ndarray:
"""Where each trial's registered image starts on the raster.
- Port of ``trialFrameOrigins.m`` (GIAnT-MATLAB ``wisc_dev``). A
+ Port of trialFrameOrigins.m (GIAnT-MATLAB wisc_dev). A
registered image covers the bounding box of the imaged ROIs plus the
motion margin, so its start is the same in every trial unless the ROIs
changed between acquisitions: deleting the leftmost ROIs moves it
@@ -647,12 +708,12 @@ def read_frame_origins(alignment_files: Sequence) -> np.ndarray:
Parameters
----------
alignment_files : sequence of (str, Path or None)
- Each trial's ``_ALIGNMENTDATA.h5`` (None for a trial without one).
+ Each trial's _ALIGNMENTDATA.h5 (None for a trial without one).
Returns
-------
ndarray of shape (trials, 2)
- ``[row, col]`` of the raster (``slap2/cropRow``, ``slap2/cropCol``);
+ [row, col] of the raster (slap2/cropRow, slap2/cropCol);
NaN where the file or the fields are missing.
"""
out = np.full((len(alignment_files), 2), np.nan)
@@ -668,10 +729,17 @@ def read_frame_origins(alignment_files: Sequence) -> np.ndarray:
return out
-def frame_offsets(origins, n_trials: int) -> np.ndarray:
- """Each trial's start relative to the earliest of the path, whole
- pixels ``(trials, 2)``; zero for trials without a known origin (and
- for all trials when ``origins`` is None)."""
+def frame_offsets(origins: npt.ArrayLike | None, n_trials: int) -> np.ndarray:
+ """Return each trial's start relative to the earliest of the path.
+
+ The offsets are whole pixels (trials, 2); zero for trials without a known origin (and
+ for all trials when origins is None).
+
+ Returns
+ -------
+ np.ndarray
+ Each trial's offset [row, col], of shape (n_trials, 2) and dtype int64.
+ """
off = np.zeros((n_trials, 2), np.int64)
if origins is None:
return off
@@ -684,8 +752,14 @@ def frame_offsets(origins, n_trials: int) -> np.ndarray:
return np.round(rel).astype(np.int64)
-def _trial_size(trial) -> tuple[int, int]:
- """Rows and columns that a trial's images take on the canvas."""
+def _trial_size(trial: TrialImages) -> tuple[int, int]:
+ """Return the rows and columns that a trial's images take on the canvas.
+
+ Returns
+ -------
+ tuple[int, int]
+ The larger of the mean image's and the activity image's rows, and of their columns.
+ """
return (
max(trial.mean_im.shape[0], trial.act_im.shape[0]),
max(trial.mean_im.shape[1], trial.act_im.shape[1]),
@@ -693,16 +767,22 @@ def _trial_size(trial) -> tuple[int, int]:
def _place_trials(
- mean_sum: np.ndarray, trials: Sequence, keep: np.ndarray, offset
+ mean_sum: np.ndarray, trials: Sequence, keep: np.ndarray, offset: np.ndarray
) -> np.ndarray:
- """The trials' images moved to where they start on the raster, for the
- template and the rigid alignment (``Mplaced`` in ``SILo.m``).
+ """Return the trials' images moved to where they start on the raster.
+
+ They serve the template and the rigid alignment (Mplaced in SILo.m).
When no trial is offset and all images have one size this is
- ``mean_sum`` itself. Otherwise the trials image different areas (the
+ mean_sum itself. Otherwise the trials image different areas (the
ROIs changed), and only the pixels that at least 90% of the kept
trials imaged are left: areas imaged in some trials only (deleted
ROIs) would otherwise set the template and the shifts.
+
+ Returns
+ -------
+ np.ndarray
+ The placed images, of the shape of mean_sum.
"""
sizes = {_trial_size(t) for t, k in zip(trials, keep) if k}
if not offset[keep].any() and len(sizes) <= 1:
@@ -719,16 +799,30 @@ def _place_trials(
return placed
-def _canvas(trials: Sequence, keep: np.ndarray, offset=None):
- """The trials' mean and activity images on one canvas (top left),
- NaN elsewhere and for trials that are not kept. With ``offset`` the
- canvas also holds every trial moved by its offset."""
+def _canvas(
+ trials: Sequence, keep: np.ndarray, offset: np.ndarray | None = None
+) -> tuple[np.ndarray, np.ndarray]:
+ """Return the trials' mean and activity images on one canvas (top left).
+
+ NaN elsewhere and for trials that are not kept. With offset the
+ canvas also holds every trial moved by its offset.
+
+ Returns
+ -------
+ mean_ims : np.ndarray
+ The mean images, of shape (trials, rows, cols, channels).
+ act_ims : np.ndarray
+ The activity images, of shape (trials, rows, cols).
+
+ Raises
+ ------
+ ValueError
+ If the kept trials' mean images differ in channels.
+ """
kept = [t for t, k in zip(trials, keep) if k]
- off = (
- np.zeros((len(trials), 2), np.int64)
- if offset is None
- else np.asarray(offset)
- )[np.asarray(keep, dtype=bool)]
+ off = (np.zeros((len(trials), 2), np.int64) if offset is None else np.asarray(offset))[
+ np.asarray(keep, dtype=bool)
+ ]
h = max(_trial_size(t)[0] + o[0] for t, o in zip(kept, off))
w = max(_trial_size(t)[1] + o[1] for t, o in zip(kept, off))
n_channels = np.atleast_3d(kept[0].mean_im).shape[2]
@@ -747,11 +841,19 @@ def _canvas(trials: Sequence, keep: np.ndarray, offset=None):
return mean_ims, act_ims
-def _valid_trials(corr, act_aligned, max_corr_thresh):
- """SiLo's valid trials: outliers of alignment quality and coverage out.
+def _valid_trials(
+ corr: np.ndarray, act_aligned: np.ndarray, max_corr_thresh: float
+) -> tuple[np.ndarray, float, np.ndarray]:
+ """Return SiLo's valid trials: outliers of alignment quality and coverage out.
- Returns the valid trials, the correlation threshold and each trial's
- covered fraction.
+ Returns
+ -------
+ valid : np.ndarray
+ The valid trials.
+ thresh : float
+ The correlation threshold.
+ covered : np.ndarray
+ Each trial's covered fraction.
"""
known = corr[~np.isnan(corr)]
thresh = max_corr_thresh
@@ -767,9 +869,10 @@ def _valid_trials(corr, act_aligned, max_corr_thresh):
def combined_activity_image(
act_aligned: np.ndarray, nan_thresh: float
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- """The combined activity image, from aligned activity images (the
- image the Gaussian seeding works in; WMF seeds from the aligned trials
- themselves).
+ """Return the combined activity image, from aligned activity images.
+
+ It is the image the Gaussian seeding works in; WMF seeds from the aligned trials
+ themselves.
The mean over the trials (NaN where any is NaN), scaled so that its
maximum is between 10 and 100, minus its 5 x 5 NaN-median.
@@ -804,11 +907,11 @@ def combined_activity_image(
def combined_null_image(
null_aligned: np.ndarray, act_aligned: np.ndarray, nan_thresh: float
) -> np.ndarray:
- """The combined activity image's null, combined as the image itself.
+ """Return the combined activity image's null, combined as the image itself.
Each draw's null images of the trials (aligned like the activity
images) are averaged, scaled by the factor that scaled the combined
- activity image (from ``act_aligned``), set to NaN where that image is
+ activity image (from act_aligned), set to NaN where that image is
NaN, and their own 5 x 5 NaN-median is subtracted
(:func:`combined_activity_image`).
@@ -839,11 +942,28 @@ def combined_null_image(
def _aligned_nulls(
- trials, valid, warp, shape, refined, method: str = "linear"
+ trials: Sequence[TrialImages | None],
+ valid: np.ndarray,
+ warp: TrialWarp,
+ shape: tuple[int, int],
+ refined: bool,
+ method: str = "linear",
) -> np.ndarray:
- """The valid trials' null images in the consensus frame,
- ``(trials, draws, rows, cols)``, placed and warped as the activity
- images."""
+ """Return the valid trials' null images in the consensus frame.
+
+ The shape is (trials, draws, rows, cols); they are placed and warped as the activity
+ images.
+
+ Returns
+ -------
+ np.ndarray
+ The aligned null images, of shape (valid trials, draws, rows, cols).
+
+ Raises
+ ------
+ ValueError
+ If a valid trial has no null images.
+ """
nulls = []
for t in valid:
im = trials[t].null_im if trials[t] is not None else None
@@ -862,9 +982,7 @@ def _aligned_nulls(
canvas = np.full(shape, np.nan)
n = nulls[i][k]
canvas[: n.shape[0], : n.shape[1]] = n
- out[i, k] = warp_trial_image(
- canvas, warp, t, method=method, coords=grid
- )
+ out[i, k] = warp_trial_image(canvas, warp, t, method=method, coords=grid)
return out
@@ -890,28 +1008,48 @@ def _aligned_nulls(
def _saved_params(text: str) -> dict:
- """A plan file's saved PlanParams; fields it predates get the values
- it was made with, not today's defaults."""
+ """Return a plan file's saved PlanParams.
+
+ Fields it predates get the values it was made with, not today's defaults.
+
+ Returns
+ -------
+ dict
+ The saved parameters by field name.
+ """
saved = json.loads(text)
for name, before in _PLAN_FIELDS_ADDED.items():
saved.setdefault(name, before)
return saved
-def _soma_canvas(soma_mask, shape, warp=None, trial=None) -> np.ndarray:
- """The soma mask on the consensus canvas (top left).
+def _soma_canvas(
+ soma_mask: np.ndarray | None,
+ shape: tuple[int, int],
+ warp: TrialWarp | None = None,
+ trial: int | None = None,
+) -> np.ndarray:
+ """Return the soma mask on the consensus canvas (top left).
- With ``trial``, the mask is in that trial's registered image and is
+ With trial, the mask is in that trial's registered image and is
moved into the consensus frame through the trial's map.
+
+ Returns
+ -------
+ np.ndarray
+ The soma mask as a boolean map of the consensus frame; all False without a mask.
+
+ Raises
+ ------
+ ValueError
+ If the mask is not two-dimensional or is larger than the consensus frame.
"""
out = np.zeros(shape, bool)
if soma_mask is None:
return out
mask = np.asarray(soma_mask, dtype=bool)
if mask.ndim != 2 or mask.shape[0] > shape[0] or mask.shape[1] > shape[1]:
- raise ValueError(
- f"soma_mask is {mask.shape}, the consensus frame {shape}"
- )
+ raise ValueError(f"soma_mask is {mask.shape}, the consensus frame {shape}")
out[: mask.shape[0], : mask.shape[1]] = mask
if trial is None:
return out
@@ -923,10 +1061,17 @@ def _soma_canvas(soma_mask, shape, warp=None, trial=None) -> np.ndarray:
return mask_to_consensus(out, warp, trial, shape)
-def _canvas_halves(trials: Sequence, keep: np.ndarray, shape) -> np.ndarray:
- """The kept trials' half images summed over channels, on the canvas
- (MATLAB's ``Mhalves``: ``(trials, 2, rows, cols)``); NaN for trials
- without them."""
+def _canvas_halves(trials: Sequence, keep: np.ndarray, shape: tuple[int, int]) -> np.ndarray:
+ """Return the kept trials' half images summed over channels, on the canvas.
+
+ The shape is that of MATLAB's Mhalves: (trials, 2, rows, cols); NaN for trials
+ without them.
+
+ Returns
+ -------
+ np.ndarray
+ The summed half images, of shape (trials, 2, rows, cols).
+ """
out = np.full((len(trials), 2) + tuple(shape), np.nan)
for k, trial in enumerate(trials):
if not keep[k] or trial is None or trial.half_ims is None:
@@ -946,9 +1091,11 @@ def refine_alignment(
params: PlanParams,
halves: np.ndarray | None = None,
workers: int = 1,
-):
- """Refine the rigid alignment of the valid trials (``SILo.m`` after the
- rigid fit): affine maps or patchwise fields, groupwise. Trials that are
+) -> tuple[TrialWarp, np.ndarray, AlignmentInfo]:
+ """Refine the rigid alignment of the valid trials.
+
+ This is SILo.m after the
+ rigid fit: affine maps or patchwise fields, groupwise. Trials that are
aligned but not valid keep their shift (as a field: the shift at every
centre).
@@ -961,8 +1108,8 @@ def refine_alignment(
valid : ndarray of int
The valid trials.
params : PlanParams
- ``inter_trial_alignment`` ('affine' or 'patchwise') and
- ``align_patch_px``.
+ inter_trial_alignment ('affine' or 'patchwise') and
+ align_patch_px.
halves : ndarray of shape (trials, 2, rows, cols), optional
The trials' half images summed over channels (patchwise only).
workers : int
@@ -975,9 +1122,10 @@ def refine_alignment(
The refined alignment.
shifts : ndarray of shape (trials, 2)
Each aligned trial's displacement at the canvas centre (MATLAB's
- updated ``motOutput``: the rigid-equivalent offsets of the motion
+ updated motOutput: the rigid-equivalent offsets of the motion
records).
info : AlignmentInfo
+ The refinement's diagnostics.
"""
check_workers(workers)
n_trials = warp.n_trials
@@ -1010,7 +1158,13 @@ def refine_alignment(
def _nanmean0(stack: np.ndarray) -> np.ndarray:
- """Mean over axis 0 with NaN ignored (NaN where nothing is left)."""
+ """Mean over axis 0 with NaN ignored (NaN where nothing is left).
+
+ Returns
+ -------
+ np.ndarray
+ The mean over the first axis of stack.
+ """
ok = ~np.isnan(stack)
count = ok.sum(axis=0)
total = np.where(ok, stack, 0.0).sum(axis=0)
@@ -1018,8 +1172,17 @@ def _nanmean0(stack: np.ndarray) -> np.ndarray:
return np.where(count > 0, total / count, np.nan)
-def _wmf_plan_seeds(act_valid, p, soma, seed_info):
- """Seed the imaged trials with WMF or return None for the fallback."""
+def _wmf_plan_seeds(
+ act_valid: np.ndarray, p: PlanParams, soma: np.ndarray, seed_info: dict | None
+) -> np.ndarray | None:
+ """Seed the imaged trials with WMF or return None for the fallback.
+
+ Returns
+ -------
+ np.ndarray or None
+ The seeds, of shape (n, 4): [value, row, col, NaN]; None when fewer than four
+ trials are imaged (the fallback).
+ """
imaged = np.isfinite(act_valid).any(axis=(1, 2))
fallback = np.count_nonzero(imaged) < 4
if seed_info is not None:
@@ -1045,7 +1208,7 @@ def _wmf_plan_seeds(act_valid, p, soma, seed_info):
return np.column_stack((info["value"], rc, np.full(len(rc), np.nan)))
-def plan_path( # noqa: C901
+def plan_path(
trials: Sequence[TrialImages | None],
soma_mask: np.ndarray | None = None,
params: PlanParams | None = None,
@@ -1058,11 +1221,11 @@ def plan_path( # noqa: C901
) -> ExtractionPlan:
"""Plan the extraction of one imaging path (the path stage of SiLo).
- ``frame_origins`` (:func:`read_frame_origins`) places the trials where
+ frame_origins (:func:`read_frame_origins`) places the trials where
their registered images start on the raster: for the template and the
rigid alignment each trial is moved by its start relative to the
earliest of the path, and that offset becomes part of the trial's map
- from the consensus frame (``shifts``, ``warp``), so that ROI masks,
+ from the consensus frame (shifts, warp), so that ROI masks,
per-trial peaks and extraction follow it. Without it, or when every
trial starts at the same place, trials share their top left corner.
@@ -1073,7 +1236,7 @@ def plan_path( # noqa: C901
localization (one that failed file verification).
soma_mask : ndarray of bool, optional
Pixels in which no source is seeded (the user's soma ROIs): in the
- consensus frame, or with ``soma_mask_trial`` in that trial's
+ consensus frame, or with soma_mask_trial in that trial's
registered image.
params : PlanParams, optional
Parameters (defaults: GIAnT-MATLAB's SLAP2 SiLo).
@@ -1081,21 +1244,21 @@ def plan_path( # noqa: C901
Trials to use among those given (default: all).
details : dict, optional
If given, it receives the intermediates that the plan does not
- keep: ``med_im``, ``nan_frac``, the sources before pruning
- (``rows``, ``cols``, ``values``, ``pixels``, ``keep_sources``), the
- seeding diagnostics (``seed_info``; WMF records ``wmf_fallback`` and
+ keep: med_im, nan_frac, the sources before pruning
+ (rows, cols, values, pixels, keep_sources), the
+ seeding diagnostics (seed_info; WMF records wmf_fallback and
the images and per-seed diagnostics of :func:`find_sources_wmf`
- when used), the combined null (``null_im``) when used, and, for a
+ when used), the combined null (null_im) when used, and, for a
refined alignment,
- ``alignment_info``
+ alignment_info
(:class:`~giant_python.extraction.raster.alignment.AlignmentInfo`).
seeds : ndarray of shape (n, 4), optional
- ``[amplitude, row, col, sigma]`` (zero-based) of seeds to use
+ [amplitude, row, col, sigma] (zero-based) of seeds to use
instead of seeding the combined activity image.
soma_mask_trial : int, optional
- Zero-based trial on whose registered image ``soma_mask`` was drawn;
+ Zero-based trial on whose registered image soma_mask was drawn;
the mask is moved into the consensus frame through that trial's
- map (MATLAB's ``roisToConsensusFrame``). A trial that was not aligned
+ map (MATLAB's roisToConsensusFrame). A trial that was not aligned
leaves the mask where it is, with a warning.
workers : int
Worker processes for the patchwise alignment's per-trial refits
@@ -1140,23 +1303,15 @@ def plan_path( # noqa: C901
act_aligned = np.full(act_ims.shape, np.nan)
mean_aligned = np.full(mean_ims.shape, np.nan)
for t in aligned:
- act_aligned[t] = warp_trial_image(
- act_ims[t], warp, t, method=p.warp_interp
- )
- valid, corr_thresh, covered = _valid_trials(
- ali.corr, act_aligned, p.max_corr_thresh
- )
+ act_aligned[t] = warp_trial_image(act_ims[t], warp, t, method=p.warp_interp)
+ valid, corr_thresh, covered = _valid_trials(ali.corr, act_aligned, p.max_corr_thresh)
# the valid trials stay those of the rigid alignment, as in MATLAB
refined = False
if p.inter_trial_alignment != "rigid" and valid.size > 1:
halves = (
- _canvas_halves(trials, keep, shape)
- if p.inter_trial_alignment == "patchwise"
- else None
- )
- warp, shifts, refine_info = refine_alignment(
- warp, mean_sum, valid, p, halves, workers
+ _canvas_halves(trials, keep, shape) if p.inter_trial_alignment == "patchwise" else None
)
+ warp, shifts, refine_info = refine_alignment(warp, mean_sum, valid, p, halves, workers)
if details is not None:
details["alignment_info"] = refine_info
refined = True
@@ -1168,9 +1323,7 @@ def plan_path( # noqa: C901
act_aligned[t] = warp_trial_image(
act_ims[t], warp, t, method=p.warp_interp, coords=grid
)
- mean_aligned[t] = warp_trial_image(
- mean_ims[t], warp, t, method=p.warp_interp, coords=grid
- )
+ mean_aligned[t] = warp_trial_image(mean_ims[t], warp, t, method=p.warp_interp, coords=grid)
del grid
act_valid = act_aligned[valid]
@@ -1216,9 +1369,7 @@ def plan_path( # noqa: C901
if valid.size
else np.zeros(shape, bool)
)
- selection = select_source_pixels(
- rows, cols, px_always_valid, p.sel_radius, p.min_source_pixels
- )
+ selection = select_source_pixels(rows, cols, px_always_valid, p.sel_radius, p.min_source_pixels)
if details is not None:
details.update(
med_im=med_im,
@@ -1233,9 +1384,7 @@ def plan_path( # noqa: C901
kept = np.flatnonzero(selection.keep)
rows, cols, values = rows[kept], cols[kept], values[kept]
lists = [selection.pixels[k] for k in kept]
- union = (
- np.unique(np.concatenate(lists)) if lists else np.zeros(0, np.int64)
- )
+ union = np.unique(np.concatenate(lists)) if lists else np.zeros(0, np.int64)
sel = np.zeros(shape, bool)
sel[union % shape[0], union // shape[0]] = True
return ExtractionPlan(
@@ -1264,34 +1413,40 @@ def plan_path( # noqa: C901
sel=sel,
source_pixels=[np.searchsorted(union, x) for x in lists],
groups=group_sources(rows, cols, sel, p.zone_radius, p.sel_radius),
- trial_peaks=[
- None if t is None or t.peaks is None else np.asarray(t.peaks)
- for t in trials
- ],
+ trial_peaks=[None if t is None or t.peaks is None else np.asarray(t.peaks) for t in trials],
trial_discard=[
- None if t is None or t.discard is None else np.asarray(t.discard)
- for t in trials
+ None if t is None or t.discard is None else np.asarray(t.discard) for t in trials
],
frame_offset=offset,
)
def _ragged(lists: Sequence[np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
- """Index lists as one array and the offsets of each list in it."""
+ """Return index lists as one array and the offsets of each list in it.
+
+ Returns
+ -------
+ flat : np.ndarray
+ The lists concatenated, as int32.
+ ptr : np.ndarray
+ The offset of each list in flat, with the total length last.
+ """
ptr = np.zeros(len(lists) + 1, dtype=np.int64)
ptr[1:] = np.cumsum([len(x) for x in lists])
- flat = (
- np.concatenate(lists).astype(np.int32)
- if len(lists)
- else np.zeros(0, np.int32)
- )
+ flat = np.concatenate(lists).astype(np.int32) if len(lists) else np.zeros(0, np.int32)
return flat, ptr
def _unragged(flat: np.ndarray, ptr: np.ndarray) -> list:
- """The lists of :func:`_ragged`."""
+ """Return the lists of :func:`_ragged`.
+
+ Returns
+ -------
+ list
+ The index lists that flat and ptr hold.
+ """
flat = np.asarray(flat, dtype=np.int64)
- return [flat[a:b] for a, b in zip(ptr[:-1], ptr[1:])]
+ return [flat[a:b] for a, b in itertools.pairwise(ptr)]
def _write_images(g: h5py.Group, name: str, data: np.ndarray) -> None:
@@ -1301,39 +1456,37 @@ def _write_images(g: h5py.Group, name: str, data: np.ndarray) -> None:
data = data.astype(np.uint8)
kwargs = {}
if data.size:
- kwargs = dict(compression="gzip", compression_opts=4, shuffle=True)
+ kwargs = {"compression": "gzip", "compression_opts": 4, "shuffle": True}
g.create_dataset(name, data=data, **kwargs)
-def write_plan(
- path: str | Path, plan: ExtractionPlan, group: str = "/"
-) -> None:
- """Write a plan to an HDF5 file (``extraction_plan.h5``).
+def write_plan(path: str | Path, plan: ExtractionPlan, group: str = "/") -> None:
+ """Write a plan to an HDF5 file (extraction_plan.h5).
Arrays are stored as numpy holds them (MATLAB's row and column
- orientation, zero-based indices). Layout, under ``group``:
-
- * attributes ``format``, ``version``, ``params`` (JSON), ``corr_thresh``;
- * ``alignment/``: ``keep_trials``, ``template``, ``template_trials``,
- ``shifts``, ``frame_offset``, ``corr``, ``act_valid_pix``,
- ``valid_trials`` and
- ``warp/`` (``affine``, ``nodes``, ``disp``, attribute ``sigma``, and
- for a patchwise field ``patch``);
- * ``images/``: ``mean_ims``, ``act_ims``, ``mean_aligned``,
- ``act_aligned``, ``mean_im``, ``act_im``, ``soma_mask``,
- ``px_always_valid``;
- * ``sources/``: ``seeds``, ``rows``, ``cols``, ``values``, ``sel`` and
- each source's pixels as ``pixel_index`` with offsets ``pixel_ptr``;
- * ``groups/``: ``origin`` (row0, col0) and ``shape`` of each crop, and
- the groups' sources and pixels as ``source_index`` / ``source_ptr``
- and ``pixel_index`` / ``pixel_ptr``;
- * ``trials//``: ``peaks`` and ``discard`` of the trials that have
+ orientation, zero-based indices). Layout, under group:
+
+ * attributes format, version, params (JSON), corr_thresh;
+ * alignment/: keep_trials, template, template_trials,
+ shifts, frame_offset, corr, act_valid_pix,
+ valid_trials and
+ warp/ (affine, nodes, disp, attribute sigma, and
+ for a patchwise field patch);
+ * images/: mean_ims, act_ims, mean_aligned,
+ act_aligned, mean_im, act_im, soma_mask,
+ px_always_valid;
+ * sources/: seeds, rows, cols, values, sel and
+ each source's pixels as pixel_index with offsets pixel_ptr;
+ * groups/: origin (row0, col0) and shape of each crop, and
+ the groups' sources and pixels as source_index / source_ptr
+ and pixel_index / pixel_ptr;
+ * trials//: peaks and discard of the trials that have
them.
Parameters
----------
path : str or Path
- The file; an existing file is replaced unless ``group`` names a
+ The file; an existing file is replaced unless group names a
group inside it.
plan : ExtractionPlan
The plan.
@@ -1391,18 +1544,12 @@ def write_plan(
_write_images(s, "sel", plan.sel)
s["pixel_index"], s["pixel_ptr"] = _ragged(plan.source_pixels)
gr = g.create_group("groups")
- gr["origin"] = np.array(
- [[x.row0, x.col0] for x in plan.groups], dtype=np.int32
- ).reshape(-1, 2)
- gr["shape"] = np.array(
- [x.sel.shape for x in plan.groups], dtype=np.int32
- ).reshape(-1, 2)
- gr["source_index"], gr["source_ptr"] = _ragged(
- [x.sources for x in plan.groups]
- )
- gr["pixel_index"], gr["pixel_ptr"] = _ragged(
- [x.pixels for x in plan.groups]
+ gr["origin"] = np.array([[x.row0, x.col0] for x in plan.groups], dtype=np.int32).reshape(
+ -1, 2
)
+ gr["shape"] = np.array([x.sel.shape for x in plan.groups], dtype=np.int32).reshape(-1, 2)
+ gr["source_index"], gr["source_ptr"] = _ragged([x.sources for x in plan.groups])
+ gr["pixel_index"], gr["pixel_ptr"] = _ragged([x.pixels for x in plan.groups])
tr = g.create_group("trials")
for t in range(plan.n_trials):
for name, values in (
@@ -1416,14 +1563,24 @@ def write_plan(
tr.create_dataset(f"{t}/{name}", data=data)
-def _read_groups(gr, rows, cols, src_rows, src_cols) -> list:
- """The subproblem groups of a plan file."""
+def _read_groups(
+ gr: h5py.Group,
+ rows: np.ndarray,
+ cols: np.ndarray,
+ src_rows: np.ndarray,
+ src_cols: np.ndarray,
+) -> list:
+ """Return the subproblem groups of a plan file.
+
+ Returns
+ -------
+ list
+ The :class:`SubproblemGroup` of each group in the file.
+ """
sources = _unragged(gr["source_index"][()], gr["source_ptr"][()])
pixels = _unragged(gr["pixel_index"][()], gr["pixel_ptr"][()])
groups = []
- for src, pix, origin, shape in zip(
- sources, pixels, gr["origin"][()], gr["shape"][()]
- ):
+ for src, pix, origin, shape in zip(sources, pixels, gr["origin"][()], gr["shape"][()]):
row0, col0 = int(origin[0]), int(origin[1])
crop = np.zeros(tuple(int(x) for x in shape), bool)
crop[rows[pix] - row0, cols[pix] - col0] = True
@@ -1434,9 +1591,7 @@ def _read_groups(gr, rows, cols, src_rows, src_cols) -> list:
row0=row0,
col0=col0,
sel=crop,
- sources_rc=np.column_stack(
- [src_rows[src] - row0, src_cols[src] - col0]
- ),
+ sources_rc=np.column_stack([src_rows[src] - row0, src_cols[src] - col0]),
)
)
return groups
@@ -1445,32 +1600,42 @@ def _read_groups(gr, rows, cols, src_rows, src_cols) -> list:
class TrialStack:
"""A per-trial image stack of a plan file, read one trial at a time.
- ``stack[t]`` is trial ``t``'s image as the whole array's ``[t]`` would
- be (same values and type), read from the file when asked for; ``shape``
+ stack[t] is trial t's image as the whole array's [t] would
+ be (same values and type), read from the file when asked for; shape
is the whole stack's. For readers that need single trials of a plan
(the prepare stage), so that a session's stack (trials x rows x cols x
channels of float64: gigabytes) is not held in memory.
"""
- def __init__(self, path, name: str) -> None:
- """The stack ``name`` (a dataset's full name) of the file."""
+ def __init__(self, path: str | Path, name: str) -> None:
+ """Open the stack name (a dataset's full name) of the file."""
self.path, self.name = Path(path), name
with h5py.File(self.path, "r") as f:
self.shape = tuple(f[name].shape)
def __len__(self) -> int:
- """The number of trials."""
+ """Return the number of trials.
+
+ Returns
+ -------
+ int
+ The number of trials (the first dimension of shape).
+ """
return self.shape[0]
- def __getitem__(self, t):
- """Trial ``t``'s image (an integer index)."""
+ def __getitem__(self, t: int) -> np.ndarray:
+ """Return trial t's image (an integer index).
+
+ Returns
+ -------
+ np.ndarray
+ Trial t's image, read from the file.
+ """
with h5py.File(self.path, "r") as f:
return f[self.name][int(t)]
-def read_plan(
- path: str | Path, group: str = "/", trial_images: bool = True
-) -> ExtractionPlan:
+def read_plan(path: str | Path, group: str = "/", trial_images: bool = True) -> ExtractionPlan:
"""Read a plan written by :func:`write_plan`.
Parameters
@@ -1481,8 +1646,8 @@ def read_plan(
Group the plan was written into.
trial_images : bool
False: leave the per-trial image stacks in the file. The plan's
- ``mean_aligned`` is then a :class:`TrialStack` (``[t]`` reads one
- trial) and ``mean_ims``, ``act_ims`` and ``act_aligned`` are None.
+ mean_aligned is then a :class:`TrialStack` ([t] reads one
+ trial) and mean_ims, act_ims and act_aligned are None.
For the prepare stage, which needs one trial's aligned mean image
at a time: a long session's stacks are gigabytes per path.
@@ -1520,8 +1685,14 @@ def read_plan(
n_trials = a["shifts"].shape[0]
tr = g["trials"]
- def trial_data(name, as_bool=False):
- """One optional array per trial."""
+ def trial_data(name: str, as_bool: bool = False) -> list:
+ """Read one optional array per trial.
+
+ Returns
+ -------
+ list
+ The array of each trial; None for a trial without one.
+ """
out = []
for t in range(n_trials):
key = f"{t}/{name}"
@@ -1560,14 +1731,8 @@ def trial_data(name, as_bool=False):
source_values=s["values"][()],
sel=sel,
source_pixels=_unragged(s["pixel_index"][()], s["pixel_ptr"][()]),
- groups=_read_groups(
- g["groups"], sel_rows, sel_cols, src_rows, src_cols
- ),
+ groups=_read_groups(g["groups"], sel_rows, sel_cols, src_rows, src_cols),
trial_peaks=trial_data("peaks"),
trial_discard=trial_data("discard", as_bool=True),
- frame_offset=(
- a["frame_offset"][()].astype(np.int64)
- if "frame_offset" in a
- else None
- ),
+ frame_offset=(a["frame_offset"][()].astype(np.int64) if "frame_offset" in a else None),
)
diff --git a/src/giant_python/extraction/raster/refit_test.py b/src/giant_python/extraction/raster/refit_test.py
index 97627758..d45c575a 100644
--- a/src/giant_python/extraction/raster/refit_test.py
+++ b/src/giant_python/extraction/raster/refit_test.py
@@ -1,13 +1,13 @@
"""Ground-truth refit test of the subproblem solver on real subproblems.
-Port of the core of GIAnT-MATLAB's ``utils/subproblemRefitTest.m``. For
+Port of the core of GIAnT-MATLAB's utils/subproblemRefitTest.m. For
each subproblem:
1. Fit it and take the fit as the truth: baseline B, footprints H and
activity X = S * k (the activity channel only).
2. Draw new data from the truth under the fit's own noise model, with the
subproblem's variance multiplier F:
- ``Z = F * Poisson(T / F)``, ``T = max(B + H X, 0)``, so that Z has mean
+ Z = F * Poisson(T / F), T = max(B + H X, 0), so that Z has mean
T and variance F T.
3. Fit Z again and compare the refit with the truth.
@@ -21,19 +21,21 @@
drawn independently per sample. MATLAB's event injection is not ported.
**Baseline sensitivity** (the WP6 test of the SILo port). The refit can be
-given an external baseline (``Subproblem.baseline``, for
-``SolverParams.baseline_mode`` other than 'fit'): the true baseline with
-an error of known type and size (``given_baseline``; :func:`scale_error`,
+given an external baseline (Subproblem.baseline, for
+SolverParams.baseline_mode other than 'fit'): the true baseline with
+an error of known type and size (given_baseline; :func:`scale_error`,
:func:`drift_error`, :func:`blur_error`, :func:`edge_error`), or the
fit's baseline while the truth carries a fast component shared by the
-pixels that the given baseline lacks (``truth_baseline``:
+pixels that the given baseline lacks (truth_baseline:
:func:`shared_component`). That gives the event-amplitude and detection
error per unit of baseline error, for each type.
"""
from __future__ import annotations
+import itertools
import math
+from collections.abc import Callable, Sequence
from dataclasses import dataclass, replace
import numpy as np
@@ -55,9 +57,14 @@ def find_events(x0: np.ndarray, lag: int) -> np.ndarray:
"""Event peaks of one source's true activity (zero-based frames).
Local maxima above 2% of the largest, with no other such maximum in
- the ``lag`` frames before them (a maximum that follows a skipped one
+ the lag frames before them (a maximum that follows a skipped one
closely is skipped too), not within 5 frames of the start or
- ``lag + 3`` of the end.
+ lag + 3 of the end.
+
+ Returns
+ -------
+ np.ndarray
+ Zero-based frame index of each event peak.
"""
n = x0.size
if n < 3 or not np.any(x0 > 0):
@@ -86,7 +93,7 @@ class RefitTruth:
The redrawn data.
b_fit : ndarray of shape (pixels, frames) or None
The fit's baseline, when the truth's was changed from it
- (``truth_baseline``).
+ (truth_baseline).
"""
h: np.ndarray
@@ -97,28 +104,42 @@ class RefitTruth:
b_fit: np.ndarray | None = None
+# `truth_baseline(b, sub, rng) -> b'` and `given_baseline(truth, sub, rng) -> b`.
+TruthBaseline = Callable[[np.ndarray, Subproblem, np.random.Generator], np.ndarray]
+GivenBaseline = Callable[[RefitTruth, Subproblem, np.random.Generator], np.ndarray]
+
+
def draw_refit_data(
sub: Subproblem,
truth: SubproblemResult,
params: SolverParams,
rng: np.random.Generator,
truth_scale: float = 1.0,
- truth_baseline=None,
+ truth_baseline: TruthBaseline | None = None,
baseline_rng: np.random.Generator | None = None,
) -> RefitTruth:
"""Redraw a subproblem's data from a fit of it (steps 1 and 2).
- ``truth`` must hold its baseline (``SolverOptions.keep_baseline``).
- ``truth_scale`` multiplies the true activity, to map the detection
- threshold. ``truth_baseline(b, sub, rng)``, if given, changes the true
- baseline before the data are drawn (with ``baseline_rng``, so that the
- data's draws stay those of ``rng``); it gets a copy of the fit's
- baseline, which stays in ``b_fit``. The true F0 follows it.
+ truth must hold its baseline (SolverOptions.keep_baseline).
+ truth_scale multiplies the true activity, to map the detection
+ threshold. truth_baseline(b, sub, rng), if given, changes the true
+ baseline before the data are drawn (with baseline_rng, so that the
+ data's draws stay those of rng); it gets a copy of the fit's
+ baseline, which stays in b_fit. The true F0 follows it.
+
+ Returns
+ -------
+ RefitTruth
+ The truth (footprints, true activity, baseline and F0) and the redrawn data.
+
+ Raises
+ ------
+ ValueError
+ If truth holds no baseline, or if truth_baseline changes the baseline's shape.
"""
if truth.baseline is None:
raise ValueError(
- "the truth needs its baseline: fit it with "
- "SolverOptions(keep_baseline=True)"
+ "the truth needs its baseline: fit it with SolverOptions(keep_baseline=True)"
)
f = np.asarray(sub.finv, dtype=np.float64)
x = conv_same(truth_scale * truth.events[0], params.k)
@@ -128,9 +149,7 @@ def draw_refit_data(
if truth_baseline is not None:
b_fit = b
b = np.asarray(
- truth_baseline(
- b.copy(), sub, baseline_rng or np.random.default_rng()
- ),
+ truth_baseline(b.copy(), sub, baseline_rng or np.random.default_rng()),
dtype=np.float64,
)
if b.shape != b_fit.shape:
@@ -157,20 +176,20 @@ def score_refit(
The refit's denoised activity, F0 and least-squares activity.
tau_frames : float
Decay time constant; event windows run from 2 frames before the
- peak to ``ceil(2.5 tau)`` after.
+ peak to ceil(2.5 tau) after.
Returns
-------
sources : list of dict
- ``true_mass``, ``recovered`` (refit / true activity mass),
- ``slope`` (of the refit on the truth, through 0), ``r`` (their
- correlation; NaN if either is flat), ``f0_ratio``,
- ``f0_ratio_active`` (where the truth is above 20% of its
- largest), ``ls_recovered``, ``peak_h`` and ``baseline`` (the true
+ true_mass, recovered (refit / true activity mass),
+ slope (of the refit on the truth, through 0), r (their
+ correlation; NaN if either is flat), f0_ratio,
+ f0_ratio_active (where the truth is above 20% of its
+ largest), ls_recovered, peak_h and baseline (the true
baseline under the footprint, per pixel and frame).
events : list of dict
- ``source``, ``size`` (peak-pixel amplitude), ``true_mass``,
- ``refit_mass`` and ``found``.
+ source, size (peak-pixel amplitude), true_mass,
+ refit_mass and found.
"""
lag = math.ceil(2.5 * tau_frames)
peak_h = truth.h.max(0)
@@ -181,18 +200,18 @@ def score_refit(
x0, xr = truth.x[s], x1[s]
active = x0 > 0.2 * x0.max()
mass = float(x0.sum())
- row = dict(
- source=s,
- true_mass=mass,
- recovered=nan,
- slope=nan,
- ls_recovered=nan,
- f0_ratio=float(f01[s].mean() / truth.f0[s].mean()),
- f0_ratio_active=nan,
- r=nan,
- peak_h=float(peak_h[s]),
- baseline=float(truth.h[:, s] @ b_mean / truth.h[:, s].sum()),
- )
+ row = {
+ "source": s,
+ "true_mass": mass,
+ "recovered": nan,
+ "slope": nan,
+ "ls_recovered": nan,
+ "f0_ratio": float(f01[s].mean() / truth.f0[s].mean()),
+ "f0_ratio_active": nan,
+ "r": nan,
+ "peak_h": float(peak_h[s]),
+ "baseline": float(truth.h[:, s] @ b_mean / truth.h[:, s].sum()),
+ }
if mass > 0:
row["recovered"] = float(xr.sum() / mass)
row["slope"] = float((xr * x0).sum() / (x0 * x0).sum())
@@ -200,89 +219,106 @@ def score_refit(
if xr.std() > 0 and x0.std() > 0:
row["r"] = float(np.corrcoef(xr, x0)[0, 1])
if active.any():
- row["f0_ratio_active"] = float(
- f01[s][active].mean() / truth.f0[s][active].mean()
- )
+ row["f0_ratio_active"] = float(f01[s][active].mean() / truth.f0[s][active].mean())
sources.append(row)
for e in find_events(x0, lag):
win = slice(e - 2, e + lag + 1)
m0, m1 = float(x0[win].sum()), float(xr[win].sum())
- events.append(
- dict(
- source=s,
- size=float(x0[e] * peak_h[s]),
- true_mass=m0,
- refit_mass=m1,
- found=bool(m1 > 0.25 * m0),
- )
- )
+ events.append({
+ "source": s,
+ "size": float(x0[e] * peak_h[s]),
+ "true_mass": m0,
+ "refit_mass": m1,
+ "found": bool(m1 > 0.25 * m0),
+ })
return sources, events
-def by_size(events: list[dict], edges=SIZE_EDGES) -> list[dict]:
+def by_size(events: list[dict], edges: Sequence[float] = SIZE_EDGES) -> list[dict]:
"""Recovery by true event size.
- One row per size bin with events: ``n``, ``share_found``,
- ``recovered_all`` (refit / true mass over the bin's events) and
- ``recovered_found`` (over its found events; NaN if none is found).
+ One row per size bin with events: n, share_found,
+ recovered_all (refit / true mass over the bin's events) and
+ recovered_found (over its found events; NaN if none is found).
+
+ Returns
+ -------
+ list of dict
+ One row per size bin with events: size_from, size_to, n, share_found,
+ recovered_all and recovered_found.
"""
size = np.array([e["size"] for e in events])
m0 = np.array([e["true_mass"] for e in events])
m1 = np.array([e["refit_mass"] for e in events])
found = np.array([e["found"] for e in events], dtype=bool)
rows = []
- for lo, hi in zip(edges[:-1], edges[1:]):
+ for lo, hi in itertools.pairwise(edges):
m = (size >= lo) & (size < hi)
if not m.any():
continue
f = m & found
- rows.append(
- dict(
- size_from=lo,
- size_to=hi,
- n=int(m.sum()),
- share_found=float(f.sum() / m.sum()),
- recovered_all=float(m1[m].sum() / m0[m].sum()),
- recovered_found=(
- float(m1[f].sum() / m0[f].sum())
- if f.any()
- else float("nan")
- ),
- )
- )
+ rows.append({
+ "size_from": lo,
+ "size_to": hi,
+ "n": int(m.sum()),
+ "share_found": float(f.sum() / m.sum()),
+ "recovered_all": float(m1[m].sum() / m0[m].sum()),
+ "recovered_found": (float(m1[f].sum() / m0[f].sum()) if f.any() else float("nan")),
+ })
return rows
def summarize(sources: list[dict], events: list[dict]) -> dict:
- """Medians and quartiles over sources, and the pooled recovery."""
+ """Medians and quartiles over sources, and the pooled recovery.
+
+ Returns
+ -------
+ dict
+ n_sources and n_events; the median (and first and third quartile, _q1 and
+ _q3) over sources of recovered and slope; the medians of f0_ratio,
+ f0_ratio_active, r and ls_recovered; and pooled (the events' total refit
+ mass over their total true mass, NaN without mass).
+ """
+
+ def col(name: str) -> np.ndarray:
+ """Return a column of the sources' rows.
- def col(name):
- """A column of the sources' rows."""
+ Returns
+ -------
+ np.ndarray
+ The column name of the sources' rows, as float64.
+ """
return np.array([s[name] for s in sources], dtype=np.float64)
- def q(name, pct):
- """A percentile of a column, NaN left out."""
+ def q(name: str, pct: float) -> float:
+ """Compute a percentile of a column, NaN left out.
+
+ Returns
+ -------
+ float
+ The pct percentile of the column's finite values; NaN if there are none.
+ """
v = col(name)
v = v[np.isfinite(v)]
return float(np.percentile(v, pct)) if v.size else float("nan")
m0 = sum(e["true_mass"] for e in events)
m1 = sum(e["refit_mass"] for e in events)
- return dict(
- n_sources=len(sources),
- n_events=len(events),
- recovered=q("recovered", 50),
- recovered_q1=q("recovered", 25),
- recovered_q3=q("recovered", 75),
- pooled=float(m1 / m0) if m0 > 0 else float("nan"),
- slope=q("slope", 50),
- slope_q1=q("slope", 25),
- slope_q3=q("slope", 75),
- f0_ratio=q("f0_ratio", 50),
- f0_ratio_active=q("f0_ratio_active", 50),
- r=q("r", 50),
- ls_recovered=q("ls_recovered", 50),
- )
+ return {
+ "n_sources": len(sources),
+ "n_events": len(events),
+ "recovered": q("recovered", 50),
+ "recovered_q1": q("recovered", 25),
+ "recovered_q3": q("recovered", 75),
+ "pooled": float(m1 / m0) if m0 > 0 else float("nan"),
+ "slope": q("slope", 50),
+ "slope_q1": q("slope", 25),
+ "slope_q3": q("slope", 75),
+ "f0_ratio": q("f0_ratio", 50),
+ "f0_ratio_active": q("f0_ratio_active", 50),
+ "r": q("r", 50),
+ "ls_recovered": q("ls_recovered", 50),
+ }
@dataclass
@@ -318,8 +354,8 @@ def refit_test(
seed: int = 0,
keep_truths: bool = False,
fits: list[SubproblemResult] | None = None,
- truth_baseline=None,
- given_baseline=None,
+ truth_baseline: TruthBaseline | None = None,
+ given_baseline: GivenBaseline | None = None,
) -> RefitResult:
"""Run the refit test on subproblems.
@@ -335,24 +371,35 @@ def refit_test(
truth_scale : float
Multiplies the true activity.
seed : int
- Subproblem i is redrawn with ``numpy.random.default_rng(seed + i)``.
+ Subproblem i is redrawn with numpy.random.default_rng(seed + i).
keep_truths : bool
Return each subproblem's truth and redrawn data.
fits : list of SubproblemResult, optional
The truth fits (with their baselines), if already made with
- ``params``; they are not fitted again.
+ params; they are not fitted again.
truth_baseline : callable, optional
- ``truth_baseline(b, sub, rng) -> b'``: a change of the true
+ truth_baseline(b, sub, rng) -> b': a change of the true
baseline before the data are drawn (:func:`shared_component`); its
- generator is ``default_rng((seed + i, 1))``.
+ generator is default_rng((seed + i, 1)).
given_baseline : callable, optional
- ``given_baseline(truth, sub, rng) -> b``: the external baseline the
- refit gets (``Subproblem.baseline``, for a ``baseline_mode`` of
- ``refit_params`` that uses one), e.g. the true baseline with an
+ given_baseline(truth, sub, rng) -> b: the external baseline the
+ refit gets (Subproblem.baseline, for a baseline_mode of
+ refit_params that uses one), e.g. the true baseline with an
error (:func:`scale_error` etc.); its generator is
- ``default_rng((seed + i, 2))``. Default: each subproblem's own
- ``baseline`` (None if it has none); with ``truth_baseline``, the
+ default_rng((seed + i, 2)). Default: each subproblem's own
+ baseline (None if it has none); with truth_baseline, the
fit's baseline, without the change.
+
+ Returns
+ -------
+ RefitResult
+ The per-source and per-event rows, their summary and recovery by event size, and the
+ truths if keep_truths.
+
+ Raises
+ ------
+ ValueError
+ If fits is given with a different length than subs.
"""
opt = replace(options or SolverOptions(), keep_baseline=True)
refit_params = refit_params or params
@@ -386,8 +433,7 @@ def refit_test(
for i, (sb, tr) in enumerate(zip(one, truths))
]
again = [
- replace(sb, y=tr.z[None], baseline=g, _coords=None)
- for sb, tr, g in zip(one, truths, given)
+ replace(sb, y=tr.z[None], baseline=g, _coords=None) for sb, tr, g in zip(one, truths, given)
]
refits = solve_subproblems(again, refit_params, opt)
sources, events = [], []
@@ -405,29 +451,61 @@ def refit_test(
)
-def fit_baseline_given(truth: RefitTruth, sub: Subproblem, rng) -> np.ndarray:
- """``given_baseline``: the fit's baseline, before ``truth_baseline``
- changed it (the true baseline when nothing changed it)."""
+def fit_baseline_given(truth: RefitTruth, sub: Subproblem, rng: np.random.Generator) -> np.ndarray:
+ """given_baseline: the fit's baseline, before truth_baseline changed it.
+
+ It is the true baseline when nothing changed it.
+
+ Returns
+ -------
+ np.ndarray
+ The fit's baseline, or the truth's baseline when it was not changed.
+ """
return truth.b if truth.b_fit is None else truth.b_fit
-def scale_error(scale: float):
- """``given_baseline``: the true baseline times ``1 + scale``."""
+def scale_error(scale: float) -> GivenBaseline:
+ """given_baseline: the true baseline times 1 + scale.
+
+ Returns
+ -------
+ GivenBaseline
+ The given_baseline function.
+ """
+
+ def given(truth: RefitTruth, sub: Subproblem, rng: np.random.Generator) -> np.ndarray:
+ """Return the scaled true baseline.
- def given(truth, sub, rng):
- """The scaled true baseline."""
+ Returns
+ -------
+ np.ndarray
+ The true baseline times 1 + scale.
+ """
return truth.b * (1 + scale)
return given
-def drift_error(drift: float):
- """``given_baseline``: the true baseline times a linear drift from
- ``1 - drift / 2`` at the first frame to ``1 + drift / 2`` at the
- last."""
+def drift_error(drift: float) -> GivenBaseline:
+ """given_baseline: the true baseline times a linear drift.
- def given(truth, sub, rng):
- """The drifting true baseline."""
+ The drift goes from 1 - drift / 2 at the first frame to 1 + drift / 2
+ at the last.
+
+ Returns
+ -------
+ GivenBaseline
+ The given_baseline function.
+ """
+
+ def given(truth: RefitTruth, sub: Subproblem, rng: np.random.Generator) -> np.ndarray:
+ """Return the drifting true baseline.
+
+ Returns
+ -------
+ np.ndarray
+ The true baseline times the linear drift over frames.
+ """
n = truth.b.shape[1]
ramp = np.linspace(-0.5, 0.5, n) if n > 1 else np.zeros(1)
return truth.b * (1 + drift * ramp)[None, :]
@@ -435,13 +513,26 @@ def given(truth, sub, rng):
return given
-def edge_error(error: float, frames: int):
- """``given_baseline``: the true baseline times ``1 + error`` in the
- first and last ``frames`` frames (a trial-edge error; frames in both
- windows of a short trial are scaled once)."""
+def edge_error(error: float, frames: int) -> GivenBaseline:
+ """given_baseline: the true baseline times 1 + error at the trial's edges.
+
+ The edges are the first and last frames frames (a trial-edge error;
+ frames in both windows of a short trial are scaled once).
- def given(truth, sub, rng):
- """The true baseline with its ends scaled."""
+ Returns
+ -------
+ GivenBaseline
+ The given_baseline function.
+ """
+
+ def given(truth: RefitTruth, sub: Subproblem, rng: np.random.Generator) -> np.ndarray:
+ """Return the true baseline with its ends scaled.
+
+ Returns
+ -------
+ np.ndarray
+ A copy of the true baseline, times 1 + error at the first and last frames.
+ """
b = truth.b.copy()
n = b.shape[1]
ends = np.zeros(n, dtype=bool)
@@ -453,16 +544,27 @@ def given(truth, sub, rng):
return given
-def blur_error(sigma: float):
- """``given_baseline``: the true baseline blurred in space.
+def blur_error(sigma: float) -> GivenBaseline:
+ """given_baseline: the true baseline blurred in space.
- A Gaussian of ``sigma`` pixels over the subproblem's crop, divided by
+ A Gaussian of sigma pixels over the subproblem's crop, divided by
the blurred map of the selected pixels, so that a pixel near the edge
of the selection averages over selected pixels only.
+
+ Returns
+ -------
+ GivenBaseline
+ The given_baseline function.
"""
- def given(truth, sub, rng):
- """The blurred true baseline."""
+ def given(truth: RefitTruth, sub: Subproblem, rng: np.random.Generator) -> np.ndarray:
+ """Return the blurred true baseline.
+
+ Returns
+ -------
+ np.ndarray
+ The spatially blurred true baseline of the selected pixels, (pixels, frames).
+ """
rows, cols = sel_coords(sub.sel)
mask = np.zeros(sub.sel.shape)
mask[rows, cols] = 1
@@ -470,25 +572,34 @@ def given(truth, sub, rng):
norm = norm[rows, cols]
img = np.zeros(sub.sel.shape + (truth.b.shape[1],))
img[rows, cols] = truth.b
- blurred = ndimage.gaussian_filter(
- img, (sigma, sigma, 0), mode="constant"
- )
+ blurred = ndimage.gaussian_filter(img, (sigma, sigma, 0), mode="constant")
return blurred[rows, cols] / norm[:, None]
return given
-def shared_component(rms: float, smooth_frames: int = 5):
- """``truth_baseline``: a fast change shared by all pixels.
+def shared_component(rms: float, smooth_frames: int = 5) -> TruthBaseline:
+ """truth_baseline: a fast change shared by all pixels.
- The true baseline times ``1 + rms * n(t)``, ``n`` white noise smoothed
- by a moving mean of ``smooth_frames`` frames and scaled to a root mean
+ The true baseline times 1 + rms * n(t), n white noise smoothed
+ by a moving mean of smooth_frames frames and scaled to a root mean
square of 1 (25 ms at 200 Hz by default: faster than the network's 80 Hz
frames resolve).
+
+ Returns
+ -------
+ TruthBaseline
+ The truth_baseline function.
"""
- def changed(b, sub, rng):
- """The baseline with the shared component."""
+ def changed(b: np.ndarray, sub: Subproblem, rng: np.random.Generator) -> np.ndarray:
+ """Return the baseline with the shared component.
+
+ Returns
+ -------
+ np.ndarray
+ The baseline times 1 + rms * n(t), the same factor for every pixel.
+ """
n = b.shape[1]
noise = rng.standard_normal(n + smooth_frames - 1)
kern = np.ones(smooth_frames) / smooth_frames
diff --git a/src/giant_python/extraction/raster/results.py b/src/giant_python/extraction/raster/results.py
index 70b9b149..36e21ed1 100644
--- a/src/giant_python/extraction/raster/results.py
+++ b/src/giant_python/extraction/raster/results.py
@@ -30,10 +30,10 @@
/subproblems//snr (sources,)
/subproblems//f0_image (channels, pixels) the final baseline
averaged over the trial's kept frames, when
- the run makes F0 images (``f0_im_trim_s``)
+ the run makes F0 images (f0_im_trim_s)
/subproblems//f0_core (channels, sources, frames) each source's
core baseline in footprint units
- (``SubproblemResult.f0_core``); absent in
+ (SubproblemResult.f0_core); absent in
files written before it existed
/subproblems/ attribute info (JSON: each fit's iterations,
loss, convergence and seconds)
@@ -43,15 +43,17 @@
import json
import os
+from collections.abc import Iterable, Sequence
from contextlib import ExitStack
from dataclasses import dataclass
from pathlib import Path
-from typing import Optional, Sequence
import h5py
import numpy as np
+import numpy.typing as npt
from ... import __version__
+from .container import Container
from .solver import (
SubproblemResult,
TrialActivity,
@@ -62,6 +64,7 @@
process_result,
)
from .solver_setup import SolverParams, Subproblem
+from .trial_data import TrialData
FORMAT = "giant-silo-results"
FORMAT_VERSION = 1
@@ -76,9 +79,9 @@ class TrialRecord:
frame_lines : ndarray of int, shape (frames,)
discard : ndarray of bool, shape (frames,)
global_f : ndarray of shape (channels, frames)
- File channel order (MATLAB's ``CD.global.F``).
+ File channel order (MATLAB's CD.global.F).
roi_f, roi_fsvd : ndarray of shape (rois, channels, frames)
- Analysis channel order (``CD.ROIs.F``, ``Fsvd``).
+ Analysis channel order (CD.ROIs.F, Fsvd).
"""
frame_lines: np.ndarray
@@ -93,9 +96,17 @@ def n_frames(self) -> int:
return int(np.asarray(self.frame_lines).size)
@classmethod
- def from_trial(cls, trial) -> "TrialRecord":
- """From a loaded trial or a container (``TrialData``,
- ``Container``)."""
+ def from_trial(cls, trial: TrialData | Container) -> TrialRecord:
+ """Build the record from a loaded trial or a container.
+
+ The trial is a TrialData or a Container.
+
+ Returns
+ -------
+ TrialRecord
+ The trial's frame lines, discards, and global and user-ROI
+ traces.
+ """
return cls(
frame_lines=np.asarray(trial.frame_lines),
discard=np.asarray(trial.discard, dtype=bool),
@@ -107,7 +118,7 @@ def from_trial(cls, trial) -> "TrialRecord":
@dataclass
class TrialOutcome:
- """One trial-path's extraction (MATLAB's ``E{t}``).
+ """One trial-path's extraction (MATLAB's E{t}).
Attributes
----------
@@ -118,7 +129,7 @@ class TrialOutcome:
"""
record: TrialRecord
- activity: Optional[TrialActivity] = None
+ activity: TrialActivity | None = None
@dataclass
@@ -129,8 +140,8 @@ class ResultsFile:
----------
record : TrialRecord
results : dict
- Subproblem index (in its container) to ``(pixels, sources,
- SubproblemResult)``, or to None when read without data.
+ Subproblem index (in its container) to (pixels, sources,
+ SubproblemResult), or to None when read without data.
attrs : dict
The file's attributes.
"""
@@ -140,9 +151,21 @@ class ResultsFile:
attrs: dict
-def _json_default(value):
- """NumPy values in a solver's info as JSON types (the baseline modes'
- per-pixel gains are arrays)."""
+def _json_default(value: object) -> object:
+ """Convert NumPy values in a solver's info to JSON types.
+
+ The baseline modes' per-pixel gains are arrays.
+
+ Returns
+ -------
+ object
+ A list for an array, a Python scalar for a NumPy scalar.
+
+ Raises
+ ------
+ TypeError
+ If the value is neither.
+ """
if isinstance(value, np.ndarray):
return value.tolist()
if isinstance(value, np.generic):
@@ -151,7 +174,7 @@ def _json_default(value):
def write_results(
- path,
+ path: str | Path,
record: TrialRecord,
results: dict,
attrs: dict,
@@ -168,12 +191,12 @@ def write_results(
record : TrialRecord
The trial's record.
results : dict
- Subproblem index to ``(pixels, sources, SubproblemResult)``.
+ Subproblem index to (pixels, sources, SubproblemResult).
attrs : dict
- Attributes (``container``, ``path``, ``trial``, ``n_subproblems``,
- ``n_pixels``, ``n_sources``, ``photon_scale``, ``extracted``,
- ``settings_hash``, ...); ``format``, ``format_version`` and
- ``code_version`` are added.
+ Attributes (container, path, trial, n_subproblems,
+ n_pixels, n_sources, photon_scale, extracted,
+ settings_hash, ...); format, format_version and
+ code_version are added.
Returns
-------
@@ -211,9 +234,7 @@ def write_results(
g["f0_image"] = np.asarray(r.f0_image, np.float64)
if r.f0_core is not None:
g["f0_core"] = np.asarray(r.f0_core)
- g.attrs["info"] = json.dumps(
- r.info, sort_keys=True, default=_json_default
- )
+ g.attrs["info"] = json.dumps(r.info, sort_keys=True, default=_json_default)
os.replace(tmp, path)
except BaseException:
if tmp.exists():
@@ -222,8 +243,15 @@ def write_results(
return path
-def _attr(value):
- """An HDF5 attribute as a Python value."""
+def _attr(value: object) -> object:
+ """Convert an HDF5 attribute to a Python value.
+
+ Returns
+ -------
+ object
+ A str for bytes, a Python scalar for a NumPy scalar; anything else
+ unchanged.
+ """
if isinstance(value, bytes):
return value.decode()
if isinstance(value, np.generic):
@@ -231,9 +259,16 @@ def _attr(value):
return value
-def _check_format(path, f) -> None:
- """Raise ValueError unless the open file ``f`` is a results file of a
- version this code reads."""
+def _check_format(path: str | Path, f: h5py.File) -> None:
+ """Raise ValueError unless the open file f is a results file.
+
+ It must be of a version this code reads.
+
+ Raises
+ ------
+ ValueError
+ If f is not a SILo results file, or is of a newer version.
+ """
if _attr(f.attrs.get("format")) != FORMAT:
raise ValueError(f"{path} is not a SILo results file")
if int(f.attrs["format_version"]) > FORMAT_VERSION:
@@ -243,7 +278,7 @@ def _check_format(path, f) -> None:
)
-def read_results(path, data: bool = True) -> ResultsFile:
+def read_results(path: str | Path, data: bool = True) -> ResultsFile:
"""Read a results file.
Parameters
@@ -252,7 +287,7 @@ def read_results(path, data: bool = True) -> ResultsFile:
The file.
data : bool
Read the subproblems' results too (otherwise only the record,
- the attributes and the subproblems' indices: ``results`` maps each
+ the attributes and the subproblems' indices: results maps each
index to None).
Returns
@@ -263,7 +298,7 @@ def read_results(path, data: bool = True) -> ResultsFile:
------
ValueError
If the file is not a results file of a version this code reads.
- """
+ """ # noqa: DOC502
with h5py.File(path, "r") as f:
_check_format(path, f)
attrs = {k: _attr(v) for k, v in f.attrs.items()}
@@ -298,16 +333,14 @@ def read_results(path, data: bool = True) -> ResultsFile:
return ResultsFile(record=record, results=results, attrs=attrs)
-def trial_outcome(
- files: Sequence[ResultsFile], params: SolverParams
-) -> TrialOutcome:
+def trial_outcome(files: Sequence[ResultsFile], params: SolverParams) -> TrialOutcome:
"""Assemble one trial-path from the results files that cover it.
Each of the container's subproblems must be in exactly one file (or in
several with equal placement and results), and all files must have
- been solved with the same settings (``solve_settings``). Footprints
- and traces are assembled (``assembleResults``) and processed
- (``processResult``) as MATLAB does after the trial's subproblems are
+ been solved with the same settings (solve_settings). Footprints
+ and traces are assembled (assembleResults) and processed
+ (processResult) as MATLAB does after the trial's subproblems are
solved.
Parameters
@@ -356,7 +389,19 @@ def trial_outcome(
def _merge(files: Sequence[ResultsFile]) -> dict:
- """The subproblems of one container's results files, checked."""
+ """Check and merge the subproblems of one container's results files.
+
+ Returns
+ -------
+ dict
+ Subproblem index to (pixels, sources, result).
+
+ Raises
+ ------
+ ValueError
+ If a subproblem has two different results, or from
+ :func:`_check_one_container` and :func:`_check_complete`.
+ """
_check_one_container([f.attrs for f in files])
merged: dict = {}
for f in files:
@@ -369,26 +414,41 @@ def _merge(files: Sequence[ResultsFile]) -> dict:
def _check_one_container(attrs: Sequence[dict]) -> None:
- """Raise ValueError unless results files (their attributes ``attrs``)
- are of one container and were solved with the same settings."""
+ """Raise ValueError unless results files are of one container.
+
+ The files (their attributes attrs) must also have been solved with
+ the same settings.
+
+ Raises
+ ------
+ ValueError
+ If the files are of different containers or were solved with
+ different settings.
+ """
first = attrs[0]
for a in attrs[1:]:
for key in ("container", "container_hash", "n_subproblems"):
if a.get(key) != first.get(key):
raise ValueError(
- f"results of different containers ({key}): "
- f"{first.get(key)} and {a.get(key)}"
+ f"results of different containers ({key}): {first.get(key)} and {a.get(key)}"
)
if _solve_settings(a) != _solve_settings(first):
raise ValueError(
- f"results of {first.get('container')} were solved with "
- "different settings"
+ f"results of {first.get('container')} were solved with different settings"
)
-def _check_complete(first: dict, present) -> None:
- """Raise ValueError if a subproblem of an extracted container (its
- first file's attributes ``first``) is not among ``present``."""
+def _check_complete(first: dict, present: Iterable[int]) -> None:
+ """Raise ValueError if a subproblem of an extracted container is missing.
+
+ The container's first file's attributes are first; a subproblem is
+ missing if it is not among present.
+
+ Raises
+ ------
+ ValueError
+ If a subproblem of an extracted container is not among present.
+ """
n_sub = int(first["n_subproblems"])
missing = sorted(set(range(n_sub)) - set(present))
if missing and int(first.get("extracted", 1)):
@@ -400,90 +460,102 @@ def _check_complete(first: dict, present) -> None:
@dataclass
class TrialShape:
- """A trial's sizes, as the summaries need them before they write any
- trial (:func:`trial_shape`, :meth:`of`).
+ """A trial's sizes, as the summaries need them before they write any trial.
+
+ See :func:`trial_shape` and :meth:`of`.
Attributes
----------
n_frames : int
Frames of the trial's record.
n_global : int
- Rows of its global traces (``global_f``).
+ Rows of its global traces (global_f).
trace_shape : tuple or None
- ``(channels, frames)`` of its sources' traces; None when the trial
+ (channels, frames) of its sources' traces; None when the trial
has no activity (not extracted, or no subproblems), as
- :func:`trial_outcome`'s ``activity``.
+ :func:`trial_outcome`'s activity.
has_core : bool
- Whether its activity has core baselines (``f0_core``; results
+ Whether its activity has core baselines (f0_core; results
written before they existed have none).
"""
n_frames: int
n_global: int
- trace_shape: Optional[tuple] = None
+ trace_shape: tuple | None = None
has_core: bool = False
@classmethod
- def of(cls, outcome: TrialOutcome) -> "TrialShape":
- """The sizes of an assembled trial."""
+ def of(cls, outcome: TrialOutcome) -> TrialShape:
+ """Return the sizes of an assembled trial.
+
+ Returns
+ -------
+ TrialShape
+ The frames, global rows, trace shape and core baselines of the
+ outcome.
+ """
act = outcome.activity
return cls(
n_frames=outcome.record.n_frames,
n_global=int(np.shape(outcome.record.global_f)[0]),
- trace_shape=(
- None
- if act is None
- else (int(act.ls.shape[0]), int(act.ls.shape[-1]))
- ),
+ trace_shape=(None if act is None else (int(act.ls.shape[0]), int(act.ls.shape[-1]))),
has_core=act is not None and act.f0_core is not None,
)
_RECORD = ("frame_lines", "discard", "global_f", "roi_f", "roi_fsvd")
-"""The record's datasets (``/trial``) that :func:`read_results` reads."""
+"""The record's datasets (/trial) that :func:`read_results` reads."""
_RESULT = ("footprints", "events", "ls", "f0", "snr")
"""A subproblem's datasets that :func:`read_results` reads, besides its
-placement and its optional ``f0_image`` and ``f0_core``."""
+placement and its optional f0_image and f0_core."""
@dataclass
class _Layout:
- """A trial's results files as far as :func:`trial_shape` and
- :func:`trial_ls` need them, checked (:func:`_layout`).
+ """A trial's results files as far as :func:`trial_shape` and :func:`trial_ls` need them.
+
+ The files are checked (:func:`_layout`).
Attributes
----------
attrs : dict
The first file's attributes.
record : dict
- The shapes of the first file's record datasets (``_RECORD``).
+ The shapes of the first file's record datasets (_RECORD).
files : list
- ``(file, indices)``: each file, open (the handle that was
- checked), and the subproblems ``0 .. n_subproblems - 1`` it holds
+ (file, indices): each file, open (the handle that was
+ checked), and the subproblems 0 .. n_subproblems - 1 it holds
(each in one file).
sources : dict
Subproblem index to its sources.
channels_frames : tuple or None
- ``(channels, frames)`` of the trial's traces; None when the trial
+ (channels, frames) of the trial's traces; None when the trial
has no activity.
has_core : bool
- Whether every subproblem has core baselines (``f0_core``).
+ Whether every subproblem has core baselines (f0_core).
"""
attrs: dict
record: dict
files: list
sources: dict
- channels_frames: Optional[tuple] = None
+ channels_frames: tuple | None = None
has_core: bool = False
-def _scan_file(f) -> Optional[tuple]:
- """``(attrs, record shapes, {index: (pixels, sources, shapes)})`` of
- an open results file: what :func:`read_results` reads, but of the
- datasets other than the placement only the shapes. None when a
- dataset or attribute that :func:`read_results` reads is missing or
- its ``info`` is not JSON."""
+def _scan_file(f: h5py.File) -> tuple | None:
+ """Scan an open results file.
+
+ The result is (attrs, record shapes, {index: (pixels, sources,
+ shapes)}) of the file: what :func:`read_results` reads, but of the
+ datasets other than the placement only the shapes.
+
+ Returns
+ -------
+ tuple or None
+ The scan; None when a dataset or attribute that
+ :func:`read_results` reads is missing or its info is not JSON.
+ """
try:
attrs = {k: _attr(v) for k, v in f.attrs.items()}
t = f["trial"]
@@ -501,19 +573,26 @@ def _scan_file(f) -> Optional[tuple]:
return attrs, record, subs
-def _integers(index) -> bool:
- """Whether placement indices are integers (as written)."""
+def _integers(index: npt.ArrayLike) -> bool:
+ """Whether placement indices are integers (as written).
+
+ Returns
+ -------
+ bool
+ True if the indices have an integer dtype.
+ """
return np.issubdtype(np.asarray(index).dtype, np.integer)
-def _layout(paths: Sequence, stack: ExitStack) -> Optional[_Layout]:
- """A trial's results files checked as :func:`trial_outcome` checks
- them, in the same order and with the same errors, without reading
- their traces: format and version, one container and one setting,
- every subproblem present, each subproblem's placement and the shapes
- of its datasets, the discard mask's length.
+def _layout(paths: Sequence, stack: ExitStack) -> _Layout | None:
+ """Check a trial's results files as :func:`trial_outcome` checks them.
+
+ The checks are in the same order and with the same errors, without
+ reading their traces: format and version, one container and one
+ setting, every subproblem present, each subproblem's placement and the
+ shapes of its datasets, the discard mask's length.
- The files are opened in ``stack`` and stay open in the layout, so that
+ The files are opened in stack and stay open in the layout, so that
what is read of them afterwards is of the versions checked (a shard
the solve stage replaces meanwhile is not mixed in).
@@ -522,7 +601,7 @@ def _layout(paths: Sequence, stack: ExitStack) -> Optional[_Layout]:
_Layout or None
None where the files cannot be judged without their data: a
subproblem in more than one file (:func:`trial_outcome` compares
- the results), a dataset or attribute missing, an ``info`` that is
+ the results), a dataset or attribute missing, an info that is
not JSON, a layout that the solve stage does not write
(:func:`_check_entries`). The caller then assembles the trial,
which raises what it raises.
@@ -568,10 +647,15 @@ def _layout(paths: Sequence, stack: ExitStack) -> Optional[_Layout]:
return out
-def _owners(held: list) -> Optional[dict]:
- """Each subproblem's file (its index in ``held``, the files'
- subproblems); None when one is in several files (:func:`trial_outcome`
- compares their results)."""
+def _owners(held: list) -> dict | None:
+ """Return each subproblem's file, from the files' subproblems held.
+
+ Returns
+ -------
+ dict or None
+ Subproblem index to its file's index in held; None when one is
+ in several files (:func:`trial_outcome` compares their results).
+ """
where: dict = {}
for i, subs in enumerate(held):
for k in subs:
@@ -581,17 +665,23 @@ def _owners(held: list) -> Optional[dict]:
return where
-def _check_entries(first: dict, entries: list, record: dict):
- """``(channels, frames)`` of a trial whose subproblems ``entries``
- (``(pixels, sources, shapes)`` of each, in order) and record (its
- datasets' shapes) pass the checks of :func:`assemble_results` and
- :func:`process_result`, which raise what they raise.
+def _check_entries(first: dict, entries: list, record: dict) -> tuple[int, int] | None:
+ """Check a trial's subproblems and record and return its (channels, frames).
+
+ The trial's subproblems entries ((pixels, sources, shapes) of
+ each, in order) and record (its datasets' shapes) pass the checks of
+ :func:`assemble_results` and :func:`process_result`, which raise what
+ they raise.
- None, to leave them to the assembly, for layouts that the solve stage
- does not write and where the assembly fails elsewhere than in its
- checks: no channels, no frames or no sources, a negative count of
- pixels, footprints that are not two-dimensional, placement indices
- that are not integers."""
+ Returns
+ -------
+ tuple of int or None
+ (channels, frames); None, to leave them to the assembly, for
+ layouts that the solve stage does not write and where the assembly
+ fails elsewhere than in its checks: no channels, no frames or no
+ sources, a negative count of pixels, footprints that are not
+ two-dimensional, placement indices that are not integers.
+ """
# in trial_outcome's order: its arguments, then subproblem by
# subproblem, then the discard mask
n_pixels, n_sources = int(first["n_pixels"]), int(first["n_sources"])
@@ -615,27 +705,34 @@ def _check_entries(first: dict, entries: list, record: dict):
return int(n_ch), int(n_t)
-def _assembled(paths: Sequence, params: Optional[SolverParams]):
- """The trial assembled from its results files (:func:`trial_outcome`;
- default solver parameters, which only the denoised traces depend
- on)."""
+def _assembled(paths: Sequence, params: SolverParams | None) -> TrialOutcome:
+ """Assemble the trial from its results files (:func:`trial_outcome`).
+
+ The solver parameters are the defaults, which only the denoised traces
+ depend on.
+
+ Returns
+ -------
+ TrialOutcome
+ The assembled trial.
+ """
return trial_outcome(
[read_results(p) for p in paths],
params if params is not None else SolverParams(),
)
-def trial_shape(
- paths: Sequence, params: Optional[SolverParams] = None
-) -> TrialShape:
- """A trial's sizes from its results files, without assembling it: the
- :class:`TrialShape` of :func:`trial_outcome`'s result, or its error.
+def trial_shape(paths: Sequence, params: SolverParams | None = None) -> TrialShape:
+ """Return a trial's sizes from its results files, without assembling it.
+
+ The result is the :class:`TrialShape` of :func:`trial_outcome`'s
+ result, or its error.
Read are the files' attributes, the subproblems' indices, pixels,
- sources and ``info``, and the other datasets' shapes; no traces, no
+ sources and info, and the other datasets' shapes; no traces, no
footprints and none of the record's data. The files are checked as
:func:`trial_outcome` checks them, and raise what it raises, for
- results files as ``silo-solve`` writes them. Where the check needs
+ results files as silo-solve writes them. Where the check needs
the data (a subproblem in several files, whose results must be
equal), a file lacks a dataset, or the layout is one the solve stage
does not write (no channels, frames or sources, footprints that are
@@ -658,7 +755,7 @@ def trial_shape(
------
ValueError
Where :func:`trial_outcome` raises it.
- """
+ """ # noqa: DOC502
with ExitStack() as stack:
layout = _layout(paths, stack)
if layout is None:
@@ -673,19 +770,20 @@ def trial_shape(
def trial_ls(
- paths: Sequence, channel: int = 0, params: Optional[SolverParams] = None
-):
- """A trial's least-squares traces of one channel and its SNR, without
- assembling the rest of it.
+ paths: Sequence, channel: int = 0, params: SolverParams | None = None
+) -> tuple[np.ndarray, np.ndarray] | None:
+ """Return a trial's least-squares traces of one channel and its SNR.
+
+ The rest of the trial is not assembled.
The values are, bit for bit, :func:`trial_outcome`'s
- ``activity.ls[channel]`` (placed, in movie units, NaN at the discarded
- frames) and ``activity.snr``. Read are what :func:`trial_shape` reads,
- the first file's discard mask, and of each subproblem its ``ls`` of
- ``channel`` and its ``snr``, from the same open files that were
+ activity.ls[channel] (placed, in movie units, NaN at the discarded
+ frames) and activity.snr. Read are what :func:`trial_shape` reads,
+ the first file's discard mask, and of each subproblem its ls of
+ channel and its snr, from the same open files that were
checked (a shard replaced meanwhile is not mixed in). The files are
checked as :func:`trial_shape` says, with the same errors as
- :func:`trial_outcome` for results files as ``silo-solve`` writes them;
+ :func:`trial_outcome` for results files as silo-solve writes them;
where it assembles the trial, the traces are taken from it.
Parameters
@@ -701,14 +799,14 @@ def trial_ls(
Returns
-------
tuple or None
- ``(ls, snr)``: ``ls`` of shape (sources, frames), float64, and
- ``snr`` of shape (sources,); None when the trial has no activity.
+ (ls, snr): ls of shape (sources, frames), float64, and
+ snr of shape (sources,); None when the trial has no activity.
Raises
------
ValueError
Where :func:`trial_outcome` raises it.
- """
+ """ # noqa: DOC502
with ExitStack() as stack:
layout = _layout(paths, stack)
if layout is not None and layout.channels_frames is not None:
@@ -723,8 +821,14 @@ def trial_ls(
def _read_ls(layout: _Layout, channel: int) -> tuple:
- """:func:`trial_ls` of a checked trial with activity, from its open
- files."""
+ """Return :func:`trial_ls` of a checked trial with activity, from its open files.
+
+ Returns
+ -------
+ tuple
+ (ls, snr): ls of shape (sources, frames), placed, in movie
+ units, NaN at the discarded frames, and snr of shape (sources,).
+ """
n_ch, n_t = layout.channels_frames
channel = range(n_ch)[channel] # numpy's indexing of the channels
attrs = layout.attrs
@@ -751,22 +855,39 @@ def _read_ls(layout: _Layout, channel: int) -> tuple:
@dataclass
class _Placement:
- """Where a subproblem's results go (what ``assemble_results`` reads of
- a :class:`Subproblem`)."""
+ """Where a subproblem's results go.
+
+ This is what assemble_results reads of a :class:`Subproblem`.
+ """
pixels: np.ndarray
sources: np.ndarray
-def _solve_settings(attrs: dict):
- """The hash of how a results file was solved, without its subproblem
- range (``solve_settings``; None if the file does not record it)."""
+def _solve_settings(attrs: dict) -> object:
+ """Return the hash of how a results file was solved.
+
+ The hash is without its subproblem range (solve_settings).
+
+ Returns
+ -------
+ object
+ The solve_settings attribute; None if the file does not record
+ it.
+ """
return attrs.get("solve_settings")
def _same(a: tuple, b: tuple) -> bool:
- """Whether two entries ``(pixels, sources, result)`` of one subproblem
- are equal: placement and results (NaN equal)."""
+ """Whether two entries (pixels, sources, result) of one subproblem are equal.
+
+ The placement and the results (NaN equal) are compared.
+
+ Returns
+ -------
+ bool
+ True if the entries are equal.
+ """
if not (np.array_equal(a[0], b[0]) and np.array_equal(a[1], b[1])):
return False
for name in ("f0_image", "f0_core"):
@@ -784,14 +905,14 @@ def _same(a: tuple, b: tuple) -> bool:
def subproblem_results(
subs: Sequence[Subproblem],
results: Sequence[SubproblemResult],
- indices: Optional[Sequence[int]] = None,
+ indices: Sequence[int] | None = None,
) -> dict:
"""Solved subproblems in the form :func:`write_results` takes.
Parameters
----------
subs : sequence of Subproblem
- The subproblems (with ``pixels`` and ``sources``).
+ The subproblems (with pixels and sources).
results : sequence of SubproblemResult
Their results.
indices : sequence of int, optional
@@ -800,13 +921,15 @@ def subproblem_results(
Returns
-------
dict
- Index to ``(pixels, sources, result)``.
+ Index to (pixels, sources, result).
+
+ Raises
+ ------
+ ValueError
+ If there is not one result and one index per subproblem.
"""
if indices is None:
indices = range(len(subs))
if not len(subs) == len(results) == len(indices):
raise ValueError("one result and one index are needed per subproblem")
- return {
- int(k): (s.pixels, s.sources, r)
- for k, s, r in zip(indices, subs, results)
- }
+ return {int(k): (s.pixels, s.sources, r) for k, s, r in zip(indices, subs, results)}
diff --git a/src/giant_python/extraction/raster/seeding.py b/src/giant_python/extraction/raster/seeding.py
index d3c8babf..e8a0ddd8 100644
--- a/src/giant_python/extraction/raster/seeding.py
+++ b/src/giant_python/extraction/raster/seeding.py
@@ -1,27 +1,27 @@
"""Source seeds and their selected pixels in SiLo's consensus frame.
-Port of the seeding part of GIAnT-MATLAB's ``SILo.m`` (main at 5a0673b):
+Port of the seeding part of GIAnT-MATLAB's SILo.m (main at 5a0673b):
1. seeds in the combined activity image (:func:`seed_sources`, the default
:func:`~giant_python.extraction.raster.peaks.get_act_im_peaks` path); the
threshold counts in robust SDs of the image itself (MATLAB's), or, with
- ``acceptance="null"`` (not in MATLAB), is set from the null of the
+ acceptance="null" (not in MATLAB), is set from the null of the
combined image so that it admits a chosen expected number of false seeds
per field (:func:`null_threshold`);
2. sources at the seeds' rounded positions, duplicates removed
(:func:`sources_from_seeds`);
-3. each source's selected pixels: a disk of ``selRadius`` around it
- (MATLAB's ``strel('disk', r)``, :func:`disk_strel`) within the pixels
+3. each source's selected pixels: a disk of selRadius around it
+ (MATLAB's strel('disk', r), :func:`disk_strel`) within the pixels
imaged in enough trials, and the pruning of sources that this clips
(:func:`select_source_pixels`).
-For ``peak_method="wmf"``, the plan seeds the aligned per-trial images with
+For peak_method="wmf", the plan seeds the aligned per-trial images with
:func:`~giant_python.extraction.raster.wmf.find_sources_wmf` before using
the same source rounding, pixel selection and pruning.
-Positions are zero-based ``(row, col)`` in MATLAB's orientation. Pixel lists
-are linear indices in MATLAB's column-major order, ``row + col * rows``, so
-that a sorted list is in the order of MATLAB's ``find``.
+Positions are zero-based (row, col) in MATLAB's orientation. Pixel lists
+are linear indices in MATLAB's column-major order, row + col * rows, so
+that a sorted list is in the order of MATLAB's find.
"""
from __future__ import annotations
@@ -62,14 +62,28 @@
def _dilate_full(a: np.ndarray, b: np.ndarray) -> np.ndarray:
- """Dilation of one binary shape by another, grown to hold the result
- (MATLAB's ``imdilate(..., 'full')``)."""
+ """Dilate one binary shape by another, grown to hold the result.
+
+ This is MATLAB's imdilate(..., 'full').
+
+ Returns
+ -------
+ np.ndarray
+ The boolean dilation of a by b.
+ """
return convolve2d(a.astype(np.int64), b.astype(np.int64)) > 0
def _periodic_line(reps: int, offset: tuple[int, int]) -> np.ndarray:
- """MATLAB's ``strel('periodicline', reps, offset)``: the points
- ``k * offset`` for ``k`` in ``-reps .. reps``."""
+ """Build MATLAB's strel('periodicline', reps, offset).
+
+ The shape holds the points k * offset for k in -reps .. reps.
+
+ Returns
+ -------
+ np.ndarray
+ The boolean line neighbourhood.
+ """
dr, dc = offset
line = np.zeros((2 * reps * abs(dr) + 1, 2 * reps * abs(dc) + 1), bool)
for k in range(-reps, reps + 1):
@@ -78,13 +92,13 @@ def _periodic_line(reps: int, offset: tuple[int, int]) -> np.ndarray:
def disk_strel(radius: int, n: int = 4) -> np.ndarray:
- """Neighbourhood of MATLAB's ``strel('disk', radius, n)``.
+ """Neighbourhood of MATLAB's strel('disk', radius, n).
- MATLAB approximates the disk by dilating ``n`` periodic lines (Adams
+ MATLAB approximates the disk by dilating n periodic lines (Adams
1993; Jones and Soille 1996) and then lines along the rows and columns
- that make up the missing radius. The result is an octagon for ``n = 4``
+ that make up the missing radius. The result is an octagon for n = 4
and is smaller than the Euclidean disk: 11 x 11 for radius 6, and a full
- 5 x 5 square for radius 3. Radii under 3 (or ``n = 0``) give the
+ 5 x 5 square for radius 3. Radii under 3 (or n = 0) give the
Euclidean disk.
Parameters
@@ -98,6 +112,11 @@ def disk_strel(radius: int, n: int = 4) -> np.ndarray:
-------
ndarray of bool
The square, symmetric neighbourhood with its origin in the centre.
+
+ Raises
+ ------
+ ValueError
+ If radius is negative or n is not 0, 4, 6 or 8.
"""
radius = int(radius)
if radius < 0:
@@ -124,13 +143,13 @@ def disk_strel(radius: int, n: int = 4) -> np.ndarray:
def candidate_statistic(
act_im: np.ndarray, exclusion: np.ndarray | None = None
) -> tuple[np.ndarray, np.ndarray]:
- """The seeding's candidate statistic at an image's local maxima.
+ """Return the seeding's candidate statistic at an image's local maxima.
A pixel is a candidate of
:func:`~giant_python.extraction.raster.peaks.get_act_im_peaks` when it
is the maximum of its 3 x 3 neighbourhood and the second-largest value
there exceeds the threshold; this returns, for every 3 x 3 maximum
- outside ``exclusion`` (and away from NaN), that second-largest value.
+ outside exclusion (and away from NaN), that second-largest value.
Returns
-------
@@ -151,9 +170,7 @@ def candidate_statistic(
return rc, second[is_max]
-def seed_heights(
- act_im: np.ndarray, rows: np.ndarray, cols: np.ndarray
-) -> np.ndarray:
+def seed_heights(act_im: np.ndarray, rows: np.ndarray, cols: np.ndarray) -> np.ndarray:
"""Each source's seed height, as the seed threshold measures it.
The second-largest value of the 3 x 3 neighbourhood of the source's
@@ -161,13 +178,13 @@ def seed_heights(
:func:`candidate_statistic`; NaN pixels and pixels outside the image
left out), in robust SDs above the image's median: the background of
:func:`~giant_python.extraction.raster.peaks.get_act_im_peaks` (median
- and MAD-SD of the finite pixels). A first-pass seed at ``peak_th`` has
- a height above ``peak_th``.
+ and MAD-SD of the finite pixels). A first-pass seed at peak_th has
+ a height above peak_th.
Parameters
----------
act_im : ndarray of shape (H, W)
- The image the sources were seeded in (``ExtractionPlan.act_im``).
+ The image the sources were seeded in (ExtractionPlan.act_im).
rows, cols : ndarray of int, shape (N,)
The sources' pixels (zero-based).
@@ -186,7 +203,7 @@ def seed_heights(
sigma = float(np.median(np.abs(vals - mu))) / _MAD_SCALE
if not sigma > 0:
return out
- h, w = act.shape
+ _h, _w = act.shape
for i, (r, c) in enumerate(zip(np.ravel(rows), np.ravel(cols))):
r, c = int(r), int(c)
win = act[max(r - 1, 0) : r + 2, max(c - 1, 0) : c + 2].ravel()
@@ -197,8 +214,20 @@ def seed_heights(
def null_background(null_ims: np.ndarray) -> tuple[float, float]:
- """Median and robust SD (MATLAB's MAD scale) of null images' finite
- pixels."""
+ """Compute the median and robust SD (MATLAB's MAD scale) of null images' finite pixels.
+
+ Returns
+ -------
+ mu : float
+ The median of the finite pixels.
+ sigma : float
+ Their robust SD (MATLAB's MAD scale).
+
+ Raises
+ ------
+ ValueError
+ If the images have fewer than 10 finite pixels or no spread.
+ """
vals = np.asarray(null_ims, dtype=np.float64)
vals = vals[np.isfinite(vals)]
if vals.size < 10:
@@ -218,17 +247,17 @@ def null_threshold(
) -> tuple[tuple[float, float], float, dict]:
"""Seed threshold from the null of a combined activity image.
- ``null_ims`` holds one or more images of what the combined activity
+ null_ims holds one or more images of what the combined activity
image would be if every trial held only noise (the bootstrap null's
images, combined as the data:
:func:`~giant_python.extraction.raster.plan.combined_null_image`). The
threshold's centre and scale are the null's median and robust SD (in
place of the image's own, which rise with the density of real
sources), and its level is where the null's candidates
- (:func:`candidate_statistic`) exceed it ``false_per_field`` times per
- image: read off the null where it has at least ``tail_k`` candidates
+ (:func:`candidate_statistic`) exceed it false_per_field times per
+ image: read off the null where it has at least tail_k candidates
per image above it, else extrapolated with an exponential tail fitted
- to the ``tail_k`` largest candidates per image.
+ to the tail_k largest candidates per image.
Parameters
----------
@@ -246,10 +275,16 @@ def null_threshold(
background : (float, float)
The null's median and robust SD (MATLAB's MAD scale).
peak_th : float
- The threshold in units of ``background``.
+ The threshold in units of background.
info : dict
- ``draws``, ``candidates`` (per image), ``tail_start`` and
- ``tail_scale`` (in units of the background) and ``extrapolated``.
+ draws, candidates (per image), tail_start and
+ tail_scale (in units of the background) and extrapolated.
+
+ Raises
+ ------
+ ValueError
+ If false_per_field is not positive or the null has too few
+ local maxima (or too few pixels or no spread).
"""
if not false_per_field > 0:
raise ValueError("false_per_field must be positive")
@@ -257,9 +292,7 @@ def null_threshold(
if null.ndim == 2:
null = null[None]
mu, sigma = null_background(null)
- z = np.concatenate(
- [(candidate_statistic(im, exclusion)[1] - mu) / sigma for im in null]
- )
+ z = np.concatenate([(candidate_statistic(im, exclusion)[1] - mu) / sigma for im in null])
z = np.sort(z)[::-1]
draws = null.shape[0]
k = int(min(tail_k * draws, z.size))
@@ -273,13 +306,13 @@ def null_threshold(
else:
th = u + max(beta, 1e-12) * float(np.log(k / want))
extrapolated = True
- info = dict(
- draws=draws,
- candidates=z.size / draws,
- tail_start=u,
- tail_scale=beta,
- extrapolated=extrapolated,
- )
+ info = {
+ "draws": draws,
+ "candidates": z.size / draws,
+ "tail_start": u,
+ "tail_scale": beta,
+ "extrapolated": extrapolated,
+ }
return (mu, sigma), th, info
@@ -306,13 +339,13 @@ def seed_sources(
The combined activity image (NaN where not imaged in every valid
trial).
peak_th : float
- Threshold in robust SDs of the image (``peakth``).
+ Threshold in robust SDs of the image (peakth).
soma_mask : ndarray of bool, optional
Pixels where no source may be seeded.
min_peak_distance : int
- ``minPeakDistance``.
+ minPeakDistance.
method : str
- ``"getactimpeaks"`` (maxima fitted with Gaussians). WMF requires
+ "getactimpeaks" (maxima fitted with Gaussians). WMF requires
the aligned trials, passed to
:func:`~giant_python.extraction.raster.wmf.find_sources_wmf`.
fit : {'matlab', 'local'}
@@ -322,39 +355,42 @@ def seed_sources(
Reject a residual peak that ends closer than this to another peak
(0: MATLAB's rule only).
acceptance : {'image', 'null', 'null_sd'}
- ``'image'``: ``peak_th`` robust SDs above the image's median
- (MATLAB's). ``'null'``: the threshold that ``null_im`` crosses
- ``false_per_field`` times per field (:func:`null_threshold`);
- ``peak_th`` is then not used. ``'null_sd'``: ``peak_th`` robust SDs
- above the median of ``null_im`` (a scale that does not grow with
+ 'image': peak_th robust SDs above the image's median
+ (MATLAB's). 'null': the threshold that null_im crosses
+ false_per_field times per field (:func:`null_threshold`);
+ peak_th is then not used. 'null_sd': peak_th robust SDs
+ above the median of null_im (a scale that does not grow with
the density of real sources; no tail is extrapolated).
null_im : ndarray of shape (draws, rows, cols), optional
- The combined image's null (needed with ``acceptance='null'``).
+ The combined image's null (needed with acceptance='null').
false_per_field : float
- Expected false seeds per field with ``acceptance='null'``.
+ Expected false seeds per field with acceptance='null'.
amplitude_rule : {'matlab', 'pixel'}
The final test of every fitted peak (see
:func:`~giant_python.extraction.raster.peaks.get_act_im_peaks`).
info : dict, optional
- Receives the threshold used (``peak_th``, ``background``: None for
- the image's own) and, with ``acceptance='null'``, the null's tail
+ Receives the threshold used (peak_th, background: None for
+ the image's own) and, with acceptance='null', the null's tail
(:func:`null_threshold`).
Returns
-------
ndarray of shape (n, 4)
- ``[amplitude, row, col, sigma]`` of each seed (zero-based, subpixel;
- MATLAB's ``thetaf``).
+ [amplitude, row, col, sigma] of each seed (zero-based, subpixel;
+ MATLAB's thetaf).
+
+ Raises
+ ------
+ ValueError
+ If method is unknown or "wmf" (which needs the aligned
+ trials), or acceptance is invalid.
"""
method = str(method).lower()
if method not in SEEDING_METHODS:
- raise ValueError(
- f"method must be one of {SEEDING_METHODS}, not {method!r}"
- )
+ raise ValueError(f"method must be one of {SEEDING_METHODS}, not {method!r}")
if method == "wmf":
raise ValueError(
- "WMF needs aligned per-trial activity images; "
- "use find_sources_wmf or plan_path"
+ "WMF needs aligned per-trial activity images; use find_sources_wmf or plan_path"
)
_check_acceptance(acceptance, null_im)
act_im = np.asarray(act_im, dtype=np.float64)
@@ -364,9 +400,7 @@ def seed_sources(
usable = ~np.isnan(act_im) if mask is None else ~np.isnan(act_im) & ~mask
if not usable.any(): # SILo.m: no sources without a pixel to seed in
return np.zeros((0, 4))
- background, peak_th = _threshold(
- acceptance, peak_th, null_im, false_per_field, mask, info
- )
+ background, peak_th = _threshold(acceptance, peak_th, null_im, false_per_field, mask, info)
return get_act_im_peaks(
act_im,
peak_th,
@@ -379,27 +413,42 @@ def seed_sources(
)
-def _check_acceptance(acceptance: str, null_im) -> None:
- """Reject an unknown acceptance, or a null one without the null."""
+def _check_acceptance(acceptance: str, null_im: np.ndarray | None) -> None:
+ """Reject an unknown acceptance, or a null one without the null.
+
+ Raises
+ ------
+ ValueError
+ If acceptance is unknown, or needs null_im and it is None.
+ """
if acceptance not in SEED_ACCEPTANCE:
- raise ValueError(
- f"acceptance must be one of {SEED_ACCEPTANCE}, "
- f"not {acceptance!r}"
- )
+ raise ValueError(f"acceptance must be one of {SEED_ACCEPTANCE}, not {acceptance!r}")
if acceptance != "image" and null_im is None:
- raise ValueError(
- f"acceptance={acceptance!r} needs the null image (null_im)"
- )
+ raise ValueError(f"acceptance={acceptance!r} needs the null image (null_im)")
-def _threshold(acceptance, peak_th, null_im, false_per_field, mask, info):
- """The background (None: the image's own) and threshold of a seeding;
- recorded in ``info`` when given."""
+def _threshold(
+ acceptance: str,
+ peak_th: float,
+ null_im: np.ndarray | None,
+ false_per_field: float,
+ mask: np.ndarray | None,
+ info: dict | None,
+) -> tuple[tuple[float, float] | None, float]:
+ """Return the background and threshold of a seeding.
+
+ They are recorded in info when given.
+
+ Returns
+ -------
+ background : tuple of float or None
+ The background (median, robust SD); None for the image's own.
+ peak_th : float
+ The threshold.
+ """
background = None
if acceptance == "null":
- background, peak_th, tail = null_threshold(
- null_im, false_per_field, mask
- )
+ background, peak_th, tail = null_threshold(null_im, false_per_field, mask)
if info is not None:
info.update(tail)
elif acceptance == "null_sd":
@@ -412,28 +461,28 @@ def _threshold(acceptance, peak_th, null_im, false_per_field, mask, info):
def sources_from_seeds(
seeds: np.ndarray, shape: tuple[int, int]
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- """Sources at the seeds' rounded positions, without duplicates.
+ """Return sources at the seeds' rounded positions, without duplicates.
- Positions are rounded as MATLAB's ``round`` (halves up) and the first
- seed of each pixel is kept, in the seeds' order (``unique(..., 'rows',
- 'stable')``). Positions are clamped to the image (a fit that ends on the
+ Positions are rounded as MATLAB's round (halves up) and the first
+ seed of each pixel is kept, in the seeds' order (unique(..., 'rows',
+ 'stable')). Positions are clamped to the image (a fit that ends on the
image's last half pixel rounds to the row or column after it, which
MATLAB would index out of bounds).
Parameters
----------
seeds : ndarray of shape (n, 4)
- ``[amplitude, row, col, sigma]`` (zero-based); for WMF seeds the
+ [amplitude, row, col, sigma] (zero-based); for WMF seeds the
first column is the matched-filter score and the last is NaN.
shape : tuple of int
- ``(rows, cols)`` of the consensus frame.
+ (rows, cols) of the consensus frame.
Returns
-------
rows, cols : ndarray of int
The sources' pixels.
values : ndarray of float
- The seeds' amplitudes (MATLAB's ``sources.V``).
+ The seeds' amplitudes (MATLAB's sources.V).
"""
seeds = np.asarray(seeds, dtype=np.float64).reshape(-1, 4)
# round in MATLAB's one-based coordinates, where every position is > 0
@@ -454,10 +503,10 @@ class SourceSelection:
----------
pixels : list of ndarray of int
For each source, its selected pixels as sorted column-major linear
- indices (``row + col * rows``) into the consensus frame.
+ indices (row + col * rows) into the consensus frame.
keep : ndarray of bool
- Sources that keep more than ``min_pixels`` pixels and whose own
- pixel is always valid (MATLAB's ``keepSources``).
+ Sources that keep more than min_pixels pixels and whose own
+ pixel is always valid (MATLAB's keepSources).
"""
pixels: list
@@ -473,9 +522,9 @@ def select_source_pixels(
) -> SourceSelection:
"""Each source's selected pixels and which sources survive.
- A source's pixels are MATLAB's ``strel('disk', sel_radius)`` around it,
- within the image and within ``px_always_valid``. A source is kept if it
- has more than ``min_pixels`` pixels and its own pixel is valid.
+ A source's pixels are MATLAB's strel('disk', sel_radius) around it,
+ within the image and within px_always_valid. A source is kept if it
+ has more than min_pixels pixels and its own pixel is valid.
Parameters
----------
@@ -484,7 +533,7 @@ def select_source_pixels(
px_always_valid : ndarray of bool, shape (rows, cols)
Pixels imaged in enough of the valid trials.
sel_radius : int
- ``selRadius`` (``ceil(2 * dXY)``).
+ selRadius (ceil(2 * dXY)).
min_pixels : int
A source needs more selected pixels than this.
diff --git a/src/giant_python/extraction/raster/solver.py b/src/giant_python/extraction/raster/solver.py
index 82694892..95cf89e9 100644
--- a/src/giant_python/extraction/raster/solver.py
+++ b/src/giant_python/extraction/raster/solver.py
@@ -1,7 +1,7 @@
"""SiLo's subproblem solver: sources' footprints, activity and baseline.
-Port of ``extractSources`` in GIAnT-MATLAB's ``extractTrial.m`` (main
-5a0673b): starting footprints and baseline, then ``nmf_iter`` rounds of
+Port of extractSources in GIAnT-MATLAB's extractTrial.m (main
+5a0673b): starting footprints and baseline, then nmf_iter rounds of
the activity fit, the baseline fit and the footprint fit, the debias
refit of the events found, least squares, channel 2 on the same
footprints, and each source's baseline F0.
@@ -12,49 +12,49 @@
caps; here the activity and footprint fits, which are convex, are
solved to convergence
(:mod:`~giant_python.extraction.raster.solver_fits`).
- ``SolverOptions.max_iter`` and ``fit_max_iter`` cap them, for
+ SolverOptions.max_iter and fit_max_iter cap them, for
diagnosing differences.
- The footprint fit's variance term is held at its value at the fit's
- start (``SolverParams.footprint_variance='fixed'``, the default). With
+ start (SolverParams.footprint_variance='fixed', the default). With
MATLAB's loss, whose variance follows the model, the converged
footprints are too spread out; MATLAB's early stop hides that.
- ``footprint_variance='model'`` gives MATLAB's loss.
+ footprint_variance='model' gives MATLAB's loss.
-**The baseline** of the activity channel (``SolverParams.baseline_mode``;
-the variants of the SILo port's baseline test, WP6). ``b_ext`` is
-``Subproblem.baseline``, an external baseline (the F0 network's, mapped
+**The baseline** of the activity channel (SolverParams.baseline_mode;
+the variants of the SILo port's baseline test, WP6). b_ext is
+Subproblem.baseline, an external baseline (the F0 network's, mapped
to the data by :mod:`~giant_python.extraction.raster.baseline_map`),
-bounded below by ``min_baseline``. The baseline enters every fit: the
+bounded below by min_baseline. The baseline enters every fit: the
starting activity (least squares of the data minus the baseline), the
first activity fit, the noise estimate that thresholds the activity for
the baseline step and the footprint fit, then (after the baseline step)
the footprint fit, the second activity fit, the debias refit, least
-squares and F0. With ``nmf_iter`` 2 the baseline step runs once, after
+squares and F0. With nmf_iter 2 the baseline step runs once, after
the first activity fit.
================= ==== ========================= =======================
mode test baseline of the first fit baseline step
================= ==== ========================= =======================
-'fit' (default) R0 ``splitFreq`` of the data ``fitB``: surround and
+'fit' (default) R0 splitFreq of the data fitB: surround and
spline per pixel
-'fixed' N0 ``b_ext`` none: ``b_ext`` held
-'gain' N1 ``b_ext`` ``g_p b_ext``: one gain
+'fixed' N0 b_ext none: b_ext held
+'gain' N1 b_ext g_p b_ext: one gain
per pixel
-'gain_shared' N2 ``b_ext`` ``g_p b_ext c_t``: c
+'gain_shared' N2 b_ext g_p b_ext c_t: c
from the pixels outside
the footprints
-'fit_from' N3 ``b_ext`` ``b_ext`` plus ``fitB``
+'fit_from' N3 b_ext b_ext plus fitB
of the correction
================= ==== ========================= =======================
-In 'gain' and 'gain_shared' each pixel's gain is fitted as ``fitB`` fits
+In 'gain' and 'gain_shared' each pixel's gain is fitted as fitB fits
its predictors, jointly with the pixel's sources' contributions (see
:func:`~giant_python.extraction.raster.solver_baseline.fit_network_gain`).
-'fit_from' runs ``fitB`` on the data minus ``b_ext`` (surround predictors
+'fit_from' runs fitB on the data minus b_ext (surround predictors
from its high-pass, the spline, the sources' contributions) and adds
-``b_ext`` back; its weights come from the baseline of the first fit,
-``b_ext``. Channel 2 keeps MATLAB's treatment in every mode (its
-``splitFreq`` baseline, held).
+b_ext back; its weights come from the baseline of the first fit,
+b_ext. Channel 2 keeps MATLAB's treatment in every mode (its
+splitFreq baseline, held).
Subproblems with the same number of frames are fitted together, padded to
a common size, on the CPU or a GPU.
@@ -81,7 +81,7 @@
source_f0,
surround_operators,
)
-from .solver_fits import TimeKernel, fit_activity, fit_footprints
+from .solver_fits import FitInfo, TimeKernel, fit_activity, fit_footprints
from .solver_setup import (
SolverParams,
Subproblem,
@@ -92,9 +92,7 @@
# events below this are dropped before the debias refit (MATLAB: 1e-1)
_EVENT_FLOOR = 0.1
# the fits that SolverOptions.fit_max_iter can name
-_FIT_NAME = re.compile(
- r"(activity|footprints)[1-9]\d*|(activity|debias)_ch2|debias"
-)
+_FIT_NAME = re.compile(r"(activity|footprints)[1-9]\d*|(activity|debias)_ch2|debias")
@dataclass(frozen=True)
@@ -145,11 +143,15 @@ class SolverOptions:
keep_baseline: bool = False
def __post_init__(self) -> None:
- """Reject options the fits cannot run with."""
+ """Reject options the fits cannot run with.
+
+ Raises
+ ------
+ ValueError
+ If an option is out of range or fit_max_iter names no fit of the solver.
+ """
if self.dtype not in ("float64", "float32"):
- raise ValueError(
- f"dtype must be 'float64' or 'float32', not {self.dtype!r}"
- )
+ raise ValueError(f"dtype must be 'float64' or 'float32', not {self.dtype!r}")
if self.max_iter < 0 or self.cg_iter < 1:
raise ValueError("max_iter must be >= 0 and cg_iter >= 1")
if self.ftol is not None and not self.ftol >= 0:
@@ -158,21 +160,23 @@ def __post_init__(self) -> None:
raise ValueError("batch_bytes must not be negative")
for name, cap in self.fit_max_iter.items():
if not _FIT_NAME.fullmatch(name):
- raise ValueError(
- f"fit_max_iter names no fit of the solver: {name!r}"
- )
+ raise ValueError(f"fit_max_iter names no fit of the solver: {name!r}")
if isinstance(cap, bool) or not isinstance(cap, int) or cap < 0:
- raise ValueError(
- f"the cap of {name} must be a whole number >= 0"
- )
+ raise ValueError(f"the cap of {name} must be a whole number >= 0")
def fit_options(self, name: str) -> dict:
- """Keyword arguments of the fit called ``name``."""
- return dict(
- max_iter=self.fit_max_iter.get(name, self.max_iter),
- ftol=self.ftol,
- cg_iter=self.cg_iter,
- )
+ """Return the keyword arguments of the fit called name.
+
+ Returns
+ -------
+ dict
+ max_iter, ftol and cg_iter of the fit.
+ """
+ return {
+ "max_iter": self.fit_max_iter.get(name, self.max_iter),
+ "ftol": self.ftol,
+ "cg_iter": self.cg_iter,
+ }
@dataclass
@@ -195,7 +199,7 @@ class SubproblemResult:
Per fit: iterations, loss, convergence and seconds.
f0_image : ndarray of shape (channels, pixels) or None
Each pixel's final baseline averaged over the subproblem's
- ``f0_frames`` (None without them).
+ f0_frames (None without them).
f0_core : ndarray of shape (channels, sources, frames) or None
Baseline of each source's core (the 3 x 3 pixels around its
footprint's peak pixel) in footprint units
@@ -223,16 +227,22 @@ def estimate_photon_scale(
kernel_scale: float = 1.0,
deattenuate: bool = False,
) -> float:
- """``extractTrial``'s photon scale for recordings without one.
+ """Estimate extractTrial's photon scale for recordings without one.
From the freshness-weighted variance and mean of each pixel of the
activity channel (pixels x frames): the 10th percentile, over pixels
of middling brightness, of the variance above that of dim pixels per
- unit of mean. When ``deattenuate`` is True (or ``q_spatial`` is given),
+ unit of mean. When deattenuate is True (or q_spatial is given),
divides each observed pixel's squared fluctuations by
- ``(finv / kernel_scale) * q_spatial`` so both subpixel bilinear
- attenuation ``Q_r Q_c`` and exponential temporal-kernel calibration
- ``kappa_dt = sum(w) / sum(w^2)`` are removed.
+ (finv / kernel_scale) * q_spatial so both subpixel bilinear
+ attenuation Q_r Q_c and exponential temporal-kernel calibration
+ kappa_dt = sum(w) / sum(w^2) are removed.
+
+ Returns
+ -------
+ float
+ The photon scale: the 10th percentile of the variance above that of dim pixels
+ per unit of mean.
"""
y = np.asarray(y, dtype=np.float64)
finv_a = np.asarray(finv, dtype=np.float64)
@@ -252,28 +262,21 @@ def estimate_photon_scale(
# Exclude filled frames (finv ~ 1000x median) and non-finite voxels
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
- ref_f = np.nanpercentile(
- np.where(fin_ok, finv_a, np.nan), 25, axis=1, keepdims=True
- )
+ ref_f = np.nanpercentile(np.where(fin_ok, finv_a, np.nan), 25, axis=1, keepdims=True)
obs = fin_ok & (finv_a <= 50.0 * ref_f)
w_obs = np.where(obs, w, 0.0)
- eff_mult = np.where(
- obs, (finv_a / float(kernel_scale)) * q[:, None], 1.0
- )
+ eff_mult = np.where(obs, (finv_a / float(kernel_scale)) * q[:, None], 1.0)
den_sum = w_obs.sum(1)
var = np.where(
den_sum > 0,
- np.where(obs, w_obs * sq / eff_mult, 0.0).sum(1)
- / np.maximum(den_sum, 1e-12),
+ np.where(obs, w_obs * sq / eff_mult, 0.0).sum(1) / np.maximum(den_sum, 1e-12),
np.nan,
)
else:
with np.errstate(invalid="ignore", divide="ignore"):
var = (w * sq).sum(1) / wsum
vb = matlab_prctile(var, 5)
- bright = (mean > matlab_prctile(mean, 40)) & (
- mean < matlab_prctile(mean, 90)
- )
+ bright = (mean > matlab_prctile(mean, 40)) & (mean < matlab_prctile(mean, 90))
return matlab_prctile((var[bright] - vb) / mean[bright], 10)
@@ -283,6 +286,12 @@ def _check_data(sub: Subproblem, mode: str = "fit") -> None:
The trial loader fills missing samples and gives them a large variance
multiplier, as MATLAB's does; a NaN that reaches the solver would
spread through the loss even at zero weight.
+
+ Raises
+ ------
+ ValueError
+ If the subproblem has no source, its data or variance multiplier are not
+ finite (or the multiplier not positive), or mode needs a baseline it lacks.
"""
if sub.n_sources == 0:
raise ValueError("a subproblem has no source")
@@ -292,25 +301,28 @@ def _check_data(sub: Subproblem, mode: str = "fit") -> None:
"samples and give them a large variance multiplier"
)
if not (np.isfinite(sub.finv).all() and (sub.finv > 0).all()):
- raise ValueError(
- "a subproblem's variance multiplier must be positive and finite"
- )
+ raise ValueError("a subproblem's variance multiplier must be positive and finite")
if mode != "fit" and sub.baseline is None:
raise ValueError(
- f"baseline_mode {mode!r} needs each subproblem's baseline "
- "(Subproblem.baseline)"
+ f"baseline_mode {mode!r} needs each subproblem's baseline (Subproblem.baseline)"
)
def _lstsq(h: np.ndarray, r: np.ndarray) -> np.ndarray:
- """MATLAB ``h \\ r`` for a tall full-rank h."""
+ r"""Solve MATLAB ``h \ r`` for a tall full-rank h.
+
+ Returns
+ -------
+ np.ndarray
+ The least-squares solution.
+ """
return np.linalg.lstsq(h, r, rcond=None)[0]
class _Batch:
"""Subproblems padded to a common size, as torch tensors."""
- def __init__(self, subs, params: SolverParams, opt: SolverOptions):
+ def __init__(self, subs: list[Subproblem], params: SolverParams, opt: SolverOptions) -> None:
"""Sizes, the sources' mask and the weights 1 / F."""
self.subs, self.params, self.opt = subs, params, opt
self.n = len(subs)
@@ -320,21 +332,29 @@ def __init__(self, subs, params: SolverParams, opt: SolverOptions):
self.n_src = [s.n_sources for s in subs]
self.p_max, self.s_max = max(self.n_px), max(self.n_src)
self.n_t = subs[0].n_frames
- self.src_ok = torch.zeros(
- (self.n, self.s_max, 1), dtype=torch.bool, device=self.dev
- )
+ self.src_ok = torch.zeros((self.n, self.s_max, 1), dtype=torch.bool, device=self.dev)
for i, n in enumerate(self.n_src):
self.src_ok[i, :n] = True
- self.w = self.pixels_frames(
- [1.0 / np.asarray(s.finv, np.float64) for s in subs], 0.0
- )
+ self.w = self.pixels_frames([1.0 / np.asarray(s.finv, np.float64) for s in subs], 0.0)
def tensor(self, a: np.ndarray) -> torch.Tensor:
- """An array on the fits' device, in their precision."""
+ """Put an array on the fits' device, in their precision.
+
+ Returns
+ -------
+ torch.Tensor
+ The array as a tensor.
+ """
return torch.as_tensor(a, dtype=self.dt, device=self.dev)
- def pixels_frames(self, arrays, fill: float) -> torch.Tensor:
- """(batch, pixels, frames) from per-member pixels x frames."""
+ def pixels_frames(self, arrays: list[np.ndarray], fill: float) -> torch.Tensor:
+ """Pad per-member pixels x frames into (batch, pixels, frames).
+
+ Returns
+ -------
+ torch.Tensor
+ The padded tensor, fill where a member has no pixel.
+ """
out = torch.full(
(self.n, self.p_max, self.n_t),
fill,
@@ -345,8 +365,16 @@ def pixels_frames(self, arrays, fill: float) -> torch.Tensor:
out[i, : a.shape[0]] = self.tensor(a)
return out
- def pixels_sources(self, arrays, dtype=None) -> torch.Tensor:
- """(batch, pixels, sources) from per-member pixels x sources."""
+ def pixels_sources(
+ self, arrays: list[np.ndarray], dtype: torch.dtype | None = None
+ ) -> torch.Tensor:
+ """Pad per-member pixels x sources into (batch, pixels, sources).
+
+ Returns
+ -------
+ torch.Tensor
+ The padded tensor, zero where a member has no pixel or source.
+ """
out = torch.zeros(
(self.n, self.p_max, self.s_max),
dtype=dtype or self.dt,
@@ -358,35 +386,60 @@ def pixels_sources(self, arrays, dtype=None) -> torch.Tensor:
)
return out
- def sources_frames(self, arrays) -> torch.Tensor:
- """(batch, sources, frames) from per-member sources x frames."""
- out = torch.zeros(
- (self.n, self.s_max, self.n_t), dtype=self.dt, device=self.dev
- )
+ def sources_frames(self, arrays: list[np.ndarray]) -> torch.Tensor:
+ """Pad per-member sources x frames into (batch, sources, frames).
+
+ Returns
+ -------
+ torch.Tensor
+ The padded tensor, zero where a member has no source.
+ """
+ out = torch.zeros((self.n, self.s_max, self.n_t), dtype=self.dt, device=self.dev)
for i, a in enumerate(arrays):
out[i, : a.shape[0]] = self.tensor(a)
return out
- def member(self, t: torch.Tensor, i: int, rows: int, cols=None):
- """Member i of a padded tensor, unpadded, as float64 numpy."""
+ def member(self, t: torch.Tensor, i: int, rows: int, cols: int | None = None) -> np.ndarray:
+ """Unpad member i of a padded tensor, as float64 numpy.
+
+ Returns
+ -------
+ np.ndarray
+ The member's first rows rows (and cols columns, if given).
+ """
a = t[i, :rows] if cols is None else t[i, :rows, :cols]
return a.detach().to("cpu", torch.float64).numpy()
-def _note(info, name, fit, seconds):
+def _note(info: list[dict], name: str, fit: FitInfo, seconds: float) -> None:
"""Record how a fit ended, per member."""
for i, d in enumerate(info):
- d[name] = dict(
- iterations=int(fit.iterations[i]),
- loss=float(fit.loss[i]),
- optimality=float(fit.optimality[i]),
- converged=bool(fit.converged[i]),
- seconds=seconds / len(info),
- )
+ d[name] = {
+ "iterations": int(fit.iterations[i]),
+ "loss": float(fit.loss[i]),
+ "optimality": float(fit.optimality[i]),
+ "converged": bool(fit.converged[i]),
+ "seconds": seconds / len(info),
+ }
-def _debias(bt, z, h, b, k, s, info, name):
- """The debias refit: the events found, refitted without their L1."""
+def _debias(
+ bt: _Batch,
+ z: torch.Tensor,
+ h: torch.Tensor,
+ b: torch.Tensor,
+ k: torch.Tensor,
+ s: torch.Tensor,
+ info: list[dict],
+ name: str,
+) -> torch.Tensor:
+ """Refit the events found, without their L1 (the debias refit).
+
+ Returns
+ -------
+ torch.Tensor
+ The events, with those below the floor set to zero and the rest refitted.
+ """
p = bt.params
free = s >= _EVENT_FLOOR
s = torch.where(free, s, torch.zeros_like(s))
@@ -412,11 +465,24 @@ def _debias(bt, z, h, b, k, s, info, name):
return s
-def _baseline_step(b, b_ext, data, sel, p, operators, info):
- """The baseline after an activity fit, by ``p.baseline_mode``.
-
- ``data`` is ``(y, x_thr, h, finv)`` of one subproblem; ``b`` the
- current baseline, ``b_ext`` the external one (None in 'fit').
+def _baseline_step(
+ b: np.ndarray,
+ b_ext: np.ndarray | None,
+ data: tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray],
+ sel: np.ndarray,
+ p: SolverParams,
+ operators: list | None,
+ info: dict,
+) -> np.ndarray:
+ """Find the baseline after an activity fit, by p.baseline_mode.
+
+ data is (y, x_thr, h, finv) of one subproblem; b the
+ current baseline, b_ext the external one (None in 'fit').
+
+ Returns
+ -------
+ np.ndarray
+ The new baseline (pixels x frames).
"""
y, xt, h, finv = data
mode = p.baseline_mode
@@ -424,17 +490,28 @@ def _baseline_step(b, b_ext, data, sel, p, operators, info):
return b
if mode in ("fit", "fit_from"):
offset = b_ext if mode == "fit_from" else None
- return fit_baseline(
- b, y, xt, h, finv, sel, p, operators, False, offset
- )
+ return fit_baseline(b, y, xt, h, finv, sel, p, operators, False, offset)
shared = mode == "gain_shared"
b, step = fit_network_gain(b, b_ext, y, xt, h, finv, p, shared, sel)
info["baseline_step"] = step
return b
-def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901
- """``extractSources`` for subproblems with equal frames and channels."""
+def _solve_batch(
+ subs: list[Subproblem], params: SolverParams, opt: SolverOptions
+) -> list[SubproblemResult]:
+ """Run extractSources for subproblems with equal frames and channels.
+
+ Returns
+ -------
+ list of SubproblemResult
+ One result per subproblem, in order.
+
+ Raises
+ ------
+ ValueError
+ If a subproblem has other than one or two channels or data the fits cannot weigh.
+ """
n_ch = subs[0].y.shape[0]
if n_ch not in (1, 2):
raise ValueError(
@@ -446,7 +523,7 @@ def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901
for sb in subs:
_check_data(sb, mode)
bt = _Batch(subs, params, opt)
- info = [dict() for _ in subs]
+ info = [{} for _ in subs]
y1 = [np.asarray(s.y[0], np.float64) for s in subs]
finv = [np.asarray(s.finv, np.float64) for s in subs]
k = bt.tensor(p.k)
@@ -454,18 +531,12 @@ def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901
# starting values
t0 = time.perf_counter()
- init = [
- initial_footprints(s.sel, s.sources_rc, p.sigma_px, p.valid_kernel)
- for s in subs
- ]
+ init = [initial_footprints(s.sel, s.sources_rc, p.sigma_px, p.valid_kernel) for s in subs]
b_ext = None
if mode == "fit":
b_np = [initial_baseline(y, p) for y in y1]
else:
- b_ext = [
- np.fmax(p.min_baseline, np.asarray(s.baseline, np.float64))
- for s in subs
- ]
+ b_ext = [np.fmax(p.min_baseline, np.asarray(s.baseline, np.float64)) for s in subs]
b_np = [b.copy() for b in b_ext]
k_peak = p.k[p.k.size // 2]
s_np = []
@@ -484,8 +555,7 @@ def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901
for i, gi in enumerate(g_np):
g[i, : gi.shape[0], : gi.shape[0]] = bt.tensor(gi.toarray())
operators = [
- surround_operators(sb.sel, p) if mode in ("fit", "fit_from") else None
- for sb in subs
+ surround_operators(sb.sel, p) if mode in ("fit", "fit_from") else None for sb in subs
]
for d in info:
d["init_seconds"] = (time.perf_counter() - t0) / bt.n
@@ -507,9 +577,7 @@ def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901
npx, nsrc = bt.n_px[i], bt.n_src[i]
xi = bt.member(x, i, nsrc)
hi = bt.member(h, i, npx, nsrc)
- _, noise, _ = activity_noise(
- y1[i], finv[i], b_np[i], hi, xi, p.tau_frames, p.snr_mode
- )
+ _, noise, _ = activity_noise(y1[i], finv[i], b_np[i], hi, xi, p.tau_frames, p.snr_mode)
floor = compute_floor(xi, p.denoise_window, p.baseline_window)
xt = np.fmax(0, xi - floor - noise[:, None])
b_np[i] = _baseline_step(
@@ -570,9 +638,7 @@ def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901
t0 = time.perf_counter()
free2 = bt.src_ok.expand_as(start)
opts = opt.fit_options("activity_ch2")
- s2, fit = fit_activity(
- z2, h, b2, k2, bt.w, p.lam, start, free=free2, **opts
- )
+ s2, fit = fit_activity(z2, h, b2, k2, bt.w, p.lam, start, free=free2, **opts)
_note(info, "activity_ch2", fit, time.perf_counter() - t0)
s2 = _debias(bt, z2, h, b2, k2, s2, info, "debias_ch2")
@@ -595,33 +661,37 @@ def _solve_batch(subs, params: SolverParams, opt: SolverOptions): # noqa: C901
baseline=np.stack(base) if opt.keep_baseline else None,
info=info[i],
f0_image=_f0_image(base, subs[i].f0_frames),
- f0_core=np.stack(
- [
- source_core_f0(h_np[i], bb, *subs[i].coords)
- for bb in base
- ]
- ),
+ f0_core=np.stack([source_core_f0(h_np[i], bb, *subs[i].coords) for bb in base]),
)
)
return results
-def _f0_image(base: list, frames) -> np.ndarray | None:
- """Each channel's final baseline (pixels x frames) averaged over
- ``frames`` (channels x pixels); None without frames."""
+def _f0_image(base: list, frames: np.ndarray | None) -> np.ndarray | None:
+ """Average each channel's final baseline over frames.
+
+ Averages each channel's final baseline (pixels x frames) over
+ frames (channels x pixels); None without frames.
+
+ Returns
+ -------
+ np.ndarray or None
+ The channels x pixels image, NaN where no frame is kept; None if frames is None.
+
+ Raises
+ ------
+ ValueError
+ If frames does not have one entry per frame of the baseline.
+ """
if frames is None:
return None
frames = np.asarray(frames, dtype=bool).ravel()
n_t = np.asarray(base[0]).shape[1]
if frames.size != n_t:
- raise ValueError(
- f"f0_frames has {frames.size} frames; the subproblem has {n_t}"
- )
+ raise ValueError(f"f0_frames has {frames.size} frames; the subproblem has {n_t}")
if not frames.any():
return np.full((len(base), np.asarray(base[0]).shape[0]), np.nan)
- return np.stack(
- [np.asarray(b, dtype=np.float64)[:, frames].mean(axis=1) for b in base]
- )
+ return np.stack([np.asarray(b, dtype=np.float64)[:, frames].mean(axis=1) for b in base])
def solve_subproblems(
@@ -633,9 +703,14 @@ def solve_subproblems(
Subproblems with the same number of frames and channels are padded to
a common number of pixels and sources and fitted together, in batches
- of at most ``options.batch_bytes`` of padded data, formed in order of
+ of at most options.batch_bytes of padded data, formed in order of
size so that little is padded. Results agree with those of single
solves within the fits' tolerance, not bit for bit.
+
+ Returns
+ -------
+ list of SubproblemResult
+ One result per subproblem, in the order of subs.
"""
opt = options or SolverOptions()
itemsize = 8 if opt.dtype == "float64" else 4
@@ -671,7 +746,13 @@ def solve_subproblem(
params: SolverParams,
options: SolverOptions | None = None,
) -> SubproblemResult:
- """Solve one subproblem (MATLAB's ``extractSubproblem``)."""
+ """Solve one subproblem (MATLAB's extractSubproblem).
+
+ Returns
+ -------
+ SubproblemResult
+ The subproblem's result.
+ """
return solve_subproblems([sub], params, options)[0]
@@ -680,7 +761,7 @@ class TrialResult:
"""A trial's sources, assembled from its subproblems.
In movie units (the solver's outputs times the photon scale), as
- MATLAB's ``assembleResults`` returns them. NaN where no subproblem
+ MATLAB's assembleResults returns them. NaN where no subproblem
covers a pixel or source.
Attributes
@@ -709,14 +790,17 @@ class TrialResult:
f0_core: np.ndarray | None = None
-def _check_placement(index, count: int, size: int, what: str) -> None:
- """Reject indices that would put results in the wrong place."""
+def _check_placement(index: np.ndarray, count: int, size: int, what: str) -> None:
+ """Reject indices that would put results in the wrong place.
+
+ Raises
+ ------
+ ValueError
+ If index does not hold count unique values in 0..size - 1.
+ """
index = np.asarray(index)
if index.shape != (count,):
- raise ValueError(
- f"a subproblem has {count} {what} and {index.size} indices "
- "for them"
- )
+ raise ValueError(f"a subproblem has {count} {what} and {index.size} indices for them")
if index.size and (index.min() < 0 or index.max() >= size):
raise ValueError(
f"a subproblem's {what} indices must lie in 0..{size - 1}; "
@@ -727,24 +811,28 @@ def _check_placement(index, count: int, size: int, what: str) -> None:
def check_result(
- pixels, sources, shapes: dict, n_pixels: int, n_sources: int, want_ct
+ pixels: np.ndarray | None,
+ sources: np.ndarray | None,
+ shapes: dict,
+ n_pixels: int,
+ n_sources: int,
+ want_ct: tuple,
) -> None:
- """Reject a subproblem's result that :func:`assemble_results` cannot
- put in place.
+ """Reject a subproblem's result that :func:`assemble_results` cannot put in place.
Parameters
----------
pixels, sources : ndarray or None
The subproblem's placement.
shapes : dict
- The shapes of the result's ``footprints``, ``events``, ``ls``,
- ``f0`` and ``snr`` (the shapes only, so that a results file can be
- checked without reading its traces), and optionally ``f0_core``
+ The shapes of the result's footprints, events, ls,
+ f0 and snr (the shapes only, so that a results file can be
+ checked without reading its traces), and optionally f0_core
(missing or None: the result has none).
n_pixels, n_sources : int
The trial's pixels and sources.
want_ct : tuple
- The trial's ``(channels, frames)``.
+ The trial's (channels, frames).
Raises
------
@@ -752,9 +840,7 @@ def check_result(
As :func:`assemble_results` does.
"""
if pixels is None or sources is None:
- raise ValueError(
- "a subproblem needs its pixels and sources to be assembled"
- )
+ raise ValueError("a subproblem needs its pixels and sources to be assembled")
_check_placement(pixels, shapes["footprints"][0], n_pixels, "pixels")
n_src = shapes["footprints"][1]
_check_placement(sources, n_src, n_sources, "sources")
@@ -772,22 +858,33 @@ def check_result(
def check_f0_image(shape: tuple, n_ch: int, n_px: int) -> None:
- """Reject a subproblem's F0 image of ``shape`` that is not its
- channels by its pixels (as :func:`assemble_results` does)."""
+ """Reject a subproblem's F0 image of shape that is not its channels by its pixels.
+
+ As :func:`assemble_results` does.
+
+ Raises
+ ------
+ ValueError
+ If shape is not (n_ch, n_px).
+ """
if shape != (n_ch, n_px):
raise ValueError(
- f"a result's f0_image is {shape}; its channels and "
- f"pixels give {(n_ch, n_px)}"
+ f"a result's f0_image is {shape}; its channels and pixels give {(n_ch, n_px)}"
)
def check_discard(n_discard: int, n_frames: int) -> None:
- """Reject a discard mask of ``n_discard`` frames for a trial of
- ``n_frames`` (as :func:`process_result` does)."""
+ """Reject a discard mask of n_discard frames for a trial of n_frames.
+
+ As :func:`process_result` does.
+
+ Raises
+ ------
+ ValueError
+ If n_discard is not n_frames.
+ """
if n_discard != n_frames:
- raise ValueError(
- f"discard has {n_discard} frames; the trial has {n_frames}"
- )
+ raise ValueError(f"discard has {n_discard} frames; the trial has {n_frames}")
def assemble_results(
@@ -797,15 +894,25 @@ def assemble_results(
n_sources: int,
photon_scale: float,
) -> TrialResult:
- """Put a trial's subproblem results together (``assembleResults``).
+ """Put a trial's subproblem results together (assembleResults).
- Each subproblem's ``pixels`` and ``sources`` say where its footprints
+ Each subproblem's pixels and sources say where its footprints
and traces go. Footprints and SNR do not depend on the scale; events,
least squares and F0 go back to movie units. The F0 images of
subproblems that share a pixel are averaged (in network gain modes
each has its own gain there); there is a trial F0 image only when
- every subproblem has one, and core baselines (``f0_core``) only when
+ every subproblem has one, and core baselines (f0_core) only when
every subproblem has them.
+
+ Returns
+ -------
+ TrialResult
+ The trial's footprints, events, least squares, F0 and SNR, in movie units.
+
+ Raises
+ ------
+ ValueError
+ If the subproblems and results do not pair up, or a result cannot be placed.
"""
if len(subs) != len(results) or not results:
raise ValueError(
@@ -823,16 +930,11 @@ def assemble_results(
img_sum = np.zeros((n_ch, n_pixels))
img_n = np.zeros(n_pixels)
for sb, r in zip(subs, results):
- shapes = {
- name: getattr(r, name).shape
- for name in ("footprints", "events", "ls", "f0")
- }
+ shapes = {name: getattr(r, name).shape for name in ("footprints", "events", "ls", "f0")}
shapes["snr"] = np.shape(r.snr)
if with_core:
shapes["f0_core"] = np.shape(r.f0_core)
- check_result(
- sb.pixels, sb.sources, shapes, n_pixels, n_sources, (n_ch, n_t)
- )
+ check_result(sb.pixels, sb.sources, shapes, n_pixels, n_sources, (n_ch, n_t))
h[np.ix_(sb.pixels, sb.sources)] = r.footprints
ev[:, sb.sources] = r.events
ls[:, sb.sources] = r.ls
@@ -862,7 +964,7 @@ def assemble_results(
@dataclass
class TrialActivity:
- """A trial's outputs as SILo stores them (MATLAB's ``processResult``).
+ """A trial's outputs as SILo stores them (MATLAB's processResult).
Attributes
----------
@@ -875,7 +977,7 @@ class TrialActivity:
f0_image : ndarray of shape (channels, pixels) or None
As :attr:`TrialResult.f0_image`.
f0_core : ndarray of shape (channels, sources, frames) or None
- As :attr:`TrialResult.f0_core` (not blanked, as ``f0``).
+ As :attr:`TrialResult.f0_core` (not blanked, as f0).
"""
footprints: np.ndarray
@@ -889,7 +991,13 @@ class TrialActivity:
def conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray:
- """MATLAB ``convn(x, k, 'same')`` along the last axis (k of odd length)."""
+ """Apply MATLAB convn(x, k, 'same') along the last axis (k of odd length).
+
+ Returns
+ -------
+ np.ndarray
+ The convolution, of the shape of x.
+ """
x = np.asarray(x, dtype=np.float64)
c, n = len(k) // 2, x.shape[-1]
rows = x.reshape(-1, n)
@@ -897,16 +1005,19 @@ def conv_same(x: np.ndarray, k: np.ndarray) -> np.ndarray:
return out.reshape(x.shape)
-def process_result(
- trial: TrialResult, params: SolverParams, discard: np.ndarray
-) -> TrialActivity:
- """A trial's activity traces (``processResult``).
+def process_result(trial: TrialResult, params: SolverParams, discard: np.ndarray) -> TrialActivity:
+ """Compute a trial's activity traces (processResult).
The denoised activity is the events convolved with the kernel (channel
2 with its own); events, denoised activity and least squares are NaN
at the discarded frames. MATLAB blanks the events with
- ``events(:, discard) = nan``, which reaches channel 1 only; channel
+ events(:, discard) = nan, which reaches channel 1 only; channel
2's events keep their values here too, so that the outputs agree.
+
+ Returns
+ -------
+ TrialActivity
+ The trial's outputs as SILo stores them.
"""
discard = np.asarray(discard, dtype=bool).ravel()
check_discard(discard.size, trial.events.shape[2])
diff --git a/src/giant_python/extraction/raster/solver_baseline.py b/src/giant_python/extraction/raster/solver_baseline.py
index 533ecc2b..8612068d 100644
--- a/src/giant_python/extraction/raster/solver_baseline.py
+++ b/src/giant_python/extraction/raster/solver_baseline.py
@@ -1,8 +1,8 @@
"""Deterministic parts of SiLo's subproblem solver: baseline and noise.
-Ports of the local functions of GIAnT-MATLAB's ``extractTrial.m`` that do
-not iterate to a tolerance: ``splitFreq`` (the baseline's starting value),
-``computeFloor``, ``getSurround``, ``bsplineBasis``, ``fitB`` (one bounded
+Ports of the local functions of GIAnT-MATLAB's extractTrial.m that do
+not iterate to a tolerance: splitFreq (the baseline's starting value),
+computeFloor, getSurround, bsplineBasis, fitB (one bounded
quadratic program per pixel, solved here to machine precision) and the
noise and SNR estimate. Arrays are pixels x frames or sources x frames,
float64.
@@ -23,14 +23,19 @@
def smooth_lowess(a: np.ndarray, window: int) -> np.ndarray:
- """MATLAB ``smoothdata(a, 2, 'lowess', window, 'omitmissing')``.
+ """MATLAB smoothdata(a, 2, 'lowess', window, 'omitmissing').
- Each value is replaced by a local linear fit over its ``window``
+ Each value is replaced by a local linear fit over its window
nearest samples (the window is shifted at the ends to keep its
length), with tricube weights that reach zero at the farthest of
them. NaN samples are left out of the fit. Where the weights leave
fewer than two samples, the result is their weighted mean, or the
mean of the window's samples if all weights are zero.
+
+ Returns
+ -------
+ np.ndarray
+ The smoothed array, same shape as a (pixels x frames).
"""
a = np.asarray(a, dtype=np.float64)
n = a.shape[1]
@@ -64,40 +69,52 @@ def smooth_lowess(a: np.ndarray, window: int) -> np.ndarray:
return out
-def ordfilt_rows(
- a: np.ndarray, order: int, n: int, pad: str = "zeros"
-) -> np.ndarray:
- """MATLAB ``ordfilt2(a, order, ones(1, n), pad)`` along the rows.
+def ordfilt_rows(a: np.ndarray, order: int, n: int, pad: str = "zeros") -> np.ndarray:
+ """MATLAB ordfilt2(a, order, ones(1, n), pad) along the rows.
- The ``order``-th smallest (1-based) of each window of ``n`` samples;
- an even window reaches ``n/2 - 1`` samples back and ``n/2`` ahead.
- ``pad`` is 'zeros' or 'symmetric'.
+ The order-th smallest (1-based) of each window of n samples;
+ an even window reaches n/2 - 1 samples back and n/2 ahead.
+ pad is 'zeros' or 'symmetric'.
+
+ Returns
+ -------
+ np.ndarray
+ The filtered rows, same shape as a (at least two-dimensional).
"""
a = np.atleast_2d(np.asarray(a, dtype=np.float64))
mode = {"zeros": "constant", "symmetric": "reflect"}[pad]
origin = -1 if n % 2 == 0 else 0
out = np.empty_like(a)
for i, row in enumerate(a):
- out[i] = ndimage.rank_filter(
- row, order - 1, size=n, mode=mode, cval=0.0, origin=origin
- )
+ out[i] = ndimage.rank_filter(row, order - 1, size=n, mode=mode, cval=0.0, origin=origin)
return out
def interp1_extrap(x: np.ndarray, y: np.ndarray, xq: np.ndarray) -> np.ndarray:
- """MATLAB ``interp1(x, y', xq, 'linear', 'extrap')`` for rows of y."""
+ """MATLAB interp1(x, y', xq, 'linear', 'extrap') for rows of y.
+
+ Returns
+ -------
+ np.ndarray
+ The rows of y interpolated (and extrapolated) at xq.
+ """
j = np.clip(np.searchsorted(x, xq, side="right") - 1, 0, x.size - 2)
frac = (xq - x[j]) / (x[j + 1] - x[j])
return y[:, j] + (y[:, j + 1] - y[:, j]) * frac
def split_freq_pages(ma: np.ndarray, lp_factor: int) -> np.ndarray:
- """Low-pass of the page means in ``splitFreq`` (pixels x pages).
+ """Low-pass of the page means in splitFreq (pixels x pages).
A lowess fit marks the pages that lie low (at or below a low order
statistic of their window's residuals); the others are dropped and the
rest averaged in a moving window, with up to three more passes to fill
windows that held no low page.
+
+ Returns
+ -------
+ np.ndarray
+ The low-passed page means (pixels x pages).
"""
ma = np.array(ma, dtype=np.float64)
resid = ma - smooth_lowess(ma, lp_factor)
@@ -114,20 +131,18 @@ def split_freq_pages(ma: np.ndarray, lp_factor: int) -> np.ndarray:
return sma
-def split_freq(
- a: np.ndarray, denoise_window: int, lp_factor: int
-) -> tuple[np.ndarray, np.ndarray]:
- """MATLAB's ``splitFreq``: a slow lower envelope of ``a`` and the rest.
+def split_freq(a: np.ndarray, denoise_window: int, lp_factor: int) -> tuple[np.ndarray, np.ndarray]:
+ """MATLAB's splitFreq: a slow lower envelope of a and the rest.
- ``a`` (pixels x frames) is averaged in pages of ``denoise_window``
- frames, the page means are low-passed over ``lp_factor`` pages keeping
+ a (pixels x frames) is averaged in pages of denoise_window
+ frames, the page means are low-passed over lp_factor pages keeping
the low ones (:func:`split_freq_pages`), and the result is
interpolated linearly back to the frames.
Returns
-------
lp, hp : ndarray
- The low-pass component and ``a - lp``.
+ The low-pass component and a - lp.
"""
a = np.asarray(a, dtype=np.float64)
n_px, n_t = a.shape
@@ -136,9 +151,7 @@ def split_freq(
with np.errstate(invalid="ignore"):
lp = np.repeat(np.nanmean(a, axis=1)[:, None], n_t, axis=1)
return lp, a - lp
- pages = a[:, : n_pages * denoise_window].reshape(
- n_px, n_pages, denoise_window
- )
+ pages = a[:, : n_pages * denoise_window].reshape(n_px, n_pages, denoise_window)
with np.errstate(invalid="ignore"):
ma = np.nanmean(pages, axis=2)
sma = split_freq_pages(ma, lp_factor)
@@ -148,24 +161,32 @@ def split_freq(
def initial_baseline(y: np.ndarray, params: SolverParams) -> np.ndarray:
- """Starting baseline of a channel: ``splitFreq``'s low-pass, bounded.
+ """Return the starting baseline of a channel: splitFreq's low-pass, bounded.
Where the low-pass is NaN (a pixel with no low page for longer than
the fill passes of :func:`split_freq_pages` reach), the baseline is
- ``params.min_baseline``, as MATLAB's ``max`` returns it.
+ params.min_baseline, as MATLAB's max returns it.
+
+ Returns
+ -------
+ np.ndarray
+ The baseline, same shape as y (pixels x frames).
"""
lp, _ = split_freq(y, params.denoise_window, params.lp_factor)
return np.fmax(params.min_baseline, lp)
-def compute_floor(
- x: np.ndarray, denoise_window: float, baseline_window: float
-) -> np.ndarray:
- """MATLAB's ``computeFloor`` of the activity (sources x frames).
+def compute_floor(x: np.ndarray, denoise_window: float, baseline_window: float) -> np.ndarray:
+ """MATLAB's computeFloor of the activity (sources x frames).
- A running median over ``2 ceil(denoise_window) + 1`` frames, then the
+ A running median over 2 ceil(denoise_window) + 1 frames, then the
10th-percentile order statistic over a baseline window, then a moving
mean over a baseline window (symmetric padding for the first two).
+
+ Returns
+ -------
+ np.ndarray
+ The floor (sources x frames).
"""
x = np.atleast_2d(np.asarray(x, dtype=np.float64))
order = math.ceil(0.1 * baseline_window)
@@ -177,7 +198,14 @@ def compute_floor(
def _shorth_center(vals: np.ndarray) -> float | None:
- """Mode center from shortest half of ``vals`` (1-D)."""
+ """Mode center from shortest half of vals (1-D).
+
+ Returns
+ -------
+ float or None
+ The median of the shortest half, or None if there are fewer than 16
+ values.
+ """
n = vals.size
if n < 16:
return None
@@ -190,8 +218,20 @@ def _shorth_center(vals: np.ndarray) -> float | None:
def _solve_wls_block(
nt_blk: np.ndarray, rhs_blk: np.ndarray, obs_blk: np.ndarray
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- """Solve one ``(B, K, K)`` WLS block; fall back per frame if a frame's
- observed footprints become collinear."""
+ """Solve one (B, K, K) WLS block.
+
+ Fall back per frame if a frame's observed footprints become collinear.
+
+ Returns
+ -------
+ z_b : np.ndarray
+ The solution of each frame, shape (B, K).
+ c_b : np.ndarray
+ The diagonal of the inverse normal matrix of each frame, shape (B, K).
+ obs : np.ndarray
+ Boolean mask (B, K) of the observed footprints; frames that could
+ not be solved are all False.
+ """
b_len, n_src = rhs_blk.shape
idx_k = np.arange(n_src)
unobs = ~obs_blk
@@ -219,10 +259,18 @@ def _solve_wls_block(
_BLOCK_POOLS: dict = {}
-def _block_pool():
- """Threads for independent blocks of numpy work: as many as the
- solver's (torch's) thread count, or None for one. Kept per process (a
- forked child gets its own: the parent's threads do not exist there)."""
+def _block_pool() -> ThreadPoolExecutor | None:
+ """Return threads for independent blocks of numpy work.
+
+ As many as the solver's (torch's) thread count, or None for one. Kept
+ per process (a forked child gets its own: the parent's threads do not
+ exist there).
+
+ Returns
+ -------
+ ThreadPoolExecutor or None
+ The pool of this process, or None if the solver uses one thread.
+ """
import torch
n = torch.get_num_threads()
@@ -240,18 +288,23 @@ def _per_frame_wls_traces(
h: np.ndarray,
resid_var: np.ndarray,
block_frames: int = 256,
-):
- """Per-frame WLS projection of ``y - b`` onto ``h`` in bounded frame
- blocks excluding synthetic samples: ``(z_all, cov_t, obs_src)`` or ``None``
- if insufficient."""
+) -> tuple[np.ndarray, np.ndarray, np.ndarray] | None:
+ """Per-frame WLS projection of y - b onto h.
+
+ The projection is done in bounded frame blocks excluding synthetic
+ samples.
+
+ Returns
+ -------
+ tuple or None
+ (z_all, cov_t, obs_src), or None if insufficient.
+ """
fin_f = np.isfinite(finv_a) & (finv_a > 0)
if not fin_f.any():
return None
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
- ref_f = np.nanpercentile(
- np.where(fin_f, finv_a, np.nan), 25, axis=1, keepdims=True
- )
+ ref_f = np.nanpercentile(np.where(fin_f, finv_a, np.nan), 25, axis=1, keepdims=True)
obs_pf = np.isfinite(yb) & fin_f & (finv_a <= 50.0 * ref_f)
if obs_pf.any(axis=0).sum() < 16:
return None
@@ -267,8 +320,14 @@ def _per_frame_wls_traces(
cov_t = np.ones((n_src, n_f), dtype=np.float64)
obs_src = np.zeros((n_src, n_f), dtype=bool)
- def block(t0):
- """One block of frames: its traces, variances and coverage."""
+ def block(t0: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Solve one block of frames: its traces, variances and coverage.
+
+ Returns
+ -------
+ tuple
+ The block's (z, cov, obs) from :func:`_solve_wls_block`.
+ """
t1 = min(t0 + block_frames, n_f)
obs_b = obs_pf[:, t0:t1]
den_b = np.where(obs_b, rv_scale[:, None] * finv_a[:, t0:t1], 1.0)
@@ -290,8 +349,14 @@ def block(t0):
else:
err, err_call = np.geterr(), np.geterrcall()
- def worker(t0):
- """Solve a block with the caller's NumPy error settings."""
+ def worker(t0: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Solve a block with the caller's NumPy error settings.
+
+ Returns
+ -------
+ tuple
+ The block's (z, cov, obs).
+ """
with np.errstate(call=err_call, **err):
return block(t0)
@@ -304,10 +369,14 @@ def worker(t0):
return z_all, cov_t, obs_src
-def _source_lag_factor(
- zc: np.ndarray, quiet: np.ndarray, tau: float, max_lag: int
-) -> float:
- """Short-lag correlation factor ``1 + 2 * sum((1 - l/tau) * rho_l)``."""
+def _source_lag_factor(zc: np.ndarray, quiet: np.ndarray, tau: float, max_lag: int) -> float:
+ """Short-lag correlation factor 1 + 2 * sum((1 - l/tau) * rho_l).
+
+ Returns
+ -------
+ float
+ The factor.
+ """
n_f = zc.size
c_temp = 1.0
for lag in range(1, max_lag + 1):
@@ -334,9 +403,17 @@ def _projected_trace_noise(
cov: np.ndarray,
tau: float,
) -> np.ndarray:
- """WLS-projected trace noise SD from ``y - b`` (avoiding fitted-activity
- noise absorption), with per-pixel/per-frame synthetic-sample exclusion,
- footprint renormalization, and short-lag temporal correlation."""
+ """Compute the WLS-projected trace noise SD from y - b.
+
+ This avoids fitted-activity noise absorption, with per-pixel/per-frame
+ synthetic-sample exclusion, footprint renormalization, and short-lag
+ temporal correlation.
+
+ Returns
+ -------
+ np.ndarray
+ The noise SD of each source (sources,).
+ """
diag_var = np.diag(cov)
if not np.isfinite(diag_var).all():
return np.sqrt(diag_var / tau)
@@ -347,12 +424,7 @@ def _projected_trace_noise(
z_all, cov_t, obs_src = wls
out = np.empty(h.shape[1], dtype=np.float64)
for k in range(h.shape[1]):
- ok_k = (
- obs_src[k]
- & np.isfinite(z_all[k])
- & np.isfinite(cov_t[k])
- & (cov_t[k] > 0)
- )
+ ok_k = obs_src[k] & np.isfinite(z_all[k]) & np.isfinite(cov_t[k]) & (cov_t[k] > 0)
if ok_k.sum() < 16 or not (diag_var[k] > 0):
out[k] = math.sqrt(max(0.0, float(diag_var[k])) / tau)
continue
@@ -363,8 +435,7 @@ def _projected_trace_noise(
var_ref_k = float(np.mean(cov_t[k, ok_k]))
zc = np.where(
ok_k,
- (z_all[k] - mu0)
- * np.sqrt(var_ref_k / np.where(ok_k, cov_t[k], 1.0)),
+ (z_all[k] - mu0) * np.sqrt(var_ref_k / np.where(ok_k, cov_t[k], 1.0)),
0.0,
)
neg = ok_k & (zc < 0.0)
@@ -373,7 +444,7 @@ def _projected_trace_noise(
continue
g0 = float((zc[neg] ** 2).mean())
quiet = ok_k & (np.abs(zc) <= 2.5 * math.sqrt(g0))
- max_lag = min(max(int(math.floor(tau)), 0), 6, int(ok_k.sum()) // 4)
+ max_lag = min(max(math.floor(tau), 0), 6, int(ok_k.sum()) // 4)
c_temp = _source_lag_factor(zc, quiet, tau, max_lag)
out[k] = math.sqrt(g0 * c_temp / float(tau))
return out
@@ -388,18 +459,18 @@ def activity_noise(
tau: float,
snr_mode: str = "diagonal",
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- """Noise and SNR of the activity, as ``extractSources`` estimates them.
+ """Noise and SNR of the activity, as extractSources estimates them.
The variance of each pixel's residual is taken from its negative
residuals, weighted by the freshness; the activity's noise follows
- from the footprints by weighted least squares, over ``tau`` frames
- (``snr_mode='diagonal'``), or directly from the WLS-projected negative
+ from the footprints by weighted least squares, over tau frames
+ (snr_mode='diagonal'), or directly from the WLS-projected negative
and quiet residuals so spatial bilinear covariance and short-lag
- temporal correlation enter (``snr_mode='projected'``).
+ temporal correlation enter (snr_mode='projected').
When the weighted footprints' normal matrix is exactly singular (for
- example a source whose fitted footprint is all zero), MATLAB's ``inv``
+ example a source whose fitted footprint is all zero), MATLAB's inv
warns and returns Inf everywhere; so does this: every source's noise
- is then Inf and its SNR 0 (numpy would raise ``LinAlgError``).
+ is then Inf and its SNR 0 (numpy would raise LinAlgError).
Returns
-------
@@ -422,19 +493,27 @@ def activity_noise(
)
cov = np.full(normal.shape, np.inf)
if snr_mode == "projected":
- x_noise = _projected_trace_noise(
- y, b, finv, h, resid_var, cov, tau
- )
+ x_noise = _projected_trace_noise(y, b, finv, h, resid_var, cov, tau)
else:
x_noise = np.sqrt(np.diag(cov) / tau)
x_snr = np.std(x, axis=1, ddof=1) / x_noise
return resid_var, x_noise, x_snr
-def _bspline_parts(n_t: int, delta: float):
- """Values and first column of the four splines at each frame."""
+def _bspline_parts(n_t: int, delta: float) -> tuple[np.ndarray, np.ndarray, int]:
+ """Values and first column of the four splines at each frame.
+
+ Returns
+ -------
+ vals : np.ndarray
+ The four splines' values at each frame, shape (frames, 4).
+ first : np.ndarray
+ Index of each frame's first spline coefficient.
+ n_coef : int
+ Number of coefficients (intervals + 3).
+ """
t = np.arange(n_t, dtype=np.float64)
- n = max(1, int(math.floor((n_t - 1) / delta + 0.5)))
+ n = max(1, math.floor((n_t - 1) / delta + 0.5))
delta = max(n_t - 1, 1) / n
u = t / delta
i = np.minimum(np.floor(u), n - 1)
@@ -455,21 +534,30 @@ def _bspline_parts(n_t: int, delta: float):
def bspline_basis(n_t: int, delta: float) -> sparse.csr_matrix:
- """MATLAB's ``bsplineBasis``: uniform cubic B-splines on 0..n_t-1.
+ """MATLAB's bsplineBasis: uniform cubic B-splines on 0..n_t-1.
- The knot spacing is adjusted from ``delta`` so that whole knot
+ The knot spacing is adjusted from delta so that whole knot
intervals tile the trial. Sparse, frames x (intervals + 3).
+
+ Returns
+ -------
+ sparse.csr_matrix
+ The basis, frames x (intervals + 3).
"""
vals, first, n_coef = _bspline_parts(n_t, delta)
cols = first[:, None] + np.arange(4)[None, :]
rows = np.broadcast_to(np.arange(n_t)[:, None], cols.shape)
- return sparse.csr_matrix(
- (vals.ravel(), (rows.ravel(), cols.ravel())), shape=(n_t, n_coef)
- )
+ return sparse.csr_matrix((vals.ravel(), (rows.ravel(), cols.ravel())), shape=(n_t, n_coef))
def _bspline_products(n_t: int, delta: float) -> sparse.csr_matrix:
- """Products of the splines at each frame: frames x (coef * coef)."""
+ """Products of the splines at each frame: frames x (coef * coef).
+
+ Returns
+ -------
+ sparse.csr_matrix
+ The products, frames x (coef * coef).
+ """
vals, first, n_coef = _bspline_parts(n_t, delta)
cols = first[:, None] + np.arange(4)[None, :]
prod = vals[:, :, None] * vals[:, None, :]
@@ -482,15 +570,21 @@ def _bspline_products(n_t: int, delta: float) -> sparse.csr_matrix:
def curvature_penalty(n_coef: int) -> np.ndarray:
- """Squared second differences of the spline coefficients, per interval."""
+ """Squared second differences of the spline coefficients, per interval.
+
+ Returns
+ -------
+ np.ndarray
+ The penalty matrix, n_coef x n_coef.
+ """
d = np.zeros((n_coef - 2, n_coef))
i = np.arange(n_coef - 2)
d[i, i], d[i, i + 1], d[i, i + 2] = 1, -2, 1
return d.T @ d / (n_coef - 3)
-def _bvls_fallback(g, c, lb, ub):
- """One bounded QP by scipy, with the objective as given.
+def _bvls_fallback(g: np.ndarray, c: np.ndarray, lb: np.ndarray, ub: np.ndarray) -> np.ndarray:
+ """Solve one bounded QP by scipy, with the objective as given.
Variables whose bounds coincide are set to them first, and the others
solved with their contribution moved into the linear term: by
@@ -498,6 +592,11 @@ def _bvls_fallback(g, c, lb, ub):
positive definite, and otherwise (G singular, so that the linear term
may act alone along some direction) by L-BFGS-B on the objective
itself. No ridge is added.
+
+ Returns
+ -------
+ np.ndarray
+ The solution (n,).
"""
fixed = lb >= ub
x = np.where(fixed, lb, 0.0)
@@ -525,8 +624,14 @@ def _bvls_fallback(g, c, lb, ub):
if scale == 0:
scale = 1.0 # no linear term: G's unit diagonal sets the scale
- def objective(v):
- """The objective and its gradient, over the linear term's scale."""
+ def objective(v: np.ndarray) -> tuple[float, np.ndarray]:
+ """Evaluate the objective and its gradient, over the linear term's scale.
+
+ Returns
+ -------
+ tuple
+ The objective value and its gradient.
+ """
gv = gf @ v
return (0.5 * v @ gv - cf @ v) / scale, (gv - cf) / scale
@@ -536,21 +641,40 @@ def objective(v):
jac=True,
method="L-BFGS-B",
bounds=list(zip(lo, hi)),
- options=dict(maxiter=20000, ftol=0.0, gtol=1e-12),
+ options={"maxiter": 20000, "ftol": 0.0, "gtol": 1e-12},
).x
return x
-def _qp_objective(g, c, x):
- """``x'Gx/2 - c'x`` of each problem of a stack."""
+def _qp_objective(g: np.ndarray, c: np.ndarray, x: np.ndarray) -> np.ndarray:
+ """Compute x'Gx/2 - c'x of each problem of a stack.
+
+ Returns
+ -------
+ np.ndarray
+ The objective of each problem (m,).
+ """
return 0.5 * np.einsum("mi,mij,mj->m", x, g, x) - (c * x).sum(1)
-def _qp_backtrack(g, c, x, target, grad, lo, hi):
- """Projected steps from x towards target that lower the objective.
+def _qp_backtrack(
+ g: np.ndarray,
+ c: np.ndarray,
+ x: np.ndarray,
+ target: np.ndarray,
+ grad: np.ndarray,
+ lo: np.ndarray,
+ hi: np.ndarray,
+) -> np.ndarray:
+ """Take projected steps from x towards target that lower the objective.
The step of each problem is halved until its objective decreases
enough; a problem that finds no such step stays at x.
+
+ Returns
+ -------
+ np.ndarray
+ The new points, same shape as x.
"""
f0 = _qp_objective(g, c, x)
alpha = np.ones(x.shape[0])
@@ -576,15 +700,15 @@ def solve_box_qp(
max_iter: int = 100,
tol: float = 1e-10,
) -> tuple[np.ndarray, dict]:
- """Minimize ``x'Gx/2 - c'x`` within bounds, for a stack of problems.
+ """Minimize x'Gx/2 - c'x within bounds, for a stack of problems.
A projected Newton method on the free variables (exact for a
quadratic once the active bounds are identified), run for all problems
at once; a problem it does not finish goes to scipy's bounded-variable
least squares. A variable whose row of G is zero enters the objective
- through ``c`` alone: it goes to its upper bound where ``c`` is
- positive, to its lower bound where ``c`` is negative, and to its
- bound nearest zero where ``c`` is zero.
+ through c alone: it goes to its upper bound where c is
+ positive, to its lower bound where c is negative, and to its
+ bound nearest zero where c is zero.
Parameters
----------
@@ -597,9 +721,9 @@ def solve_box_qp(
-------
x : ndarray of shape (m, n)
info : dict
- ``converged`` (per problem; False where the fallback was used) and
- ``kkt``, the largest gradient component among the variables that
- no bound holds, relative to the largest of ``c`` (both with G
+ converged (per problem; False where the fallback was used) and
+ kkt, the largest gradient component among the variables that
+ no bound holds, relative to the largest of c (both with G
scaled to a unit diagonal). It is computed on the objective as
given, also for the fallback's solutions; a warning is given if
one of those is above 1e-6.
@@ -614,8 +738,16 @@ def solve_box_qp(
lo, hi = lb / scale, ub / scale
eye = np.eye(n)
- def newton_point(gk, x, grad, active):
- """Minimum over the free variables, the active ones held."""
+ def newton_point(
+ gk: np.ndarray, x: np.ndarray, grad: np.ndarray, active: np.ndarray
+ ) -> np.ndarray:
+ """Compute the minimum over the free variables, the active ones held.
+
+ Returns
+ -------
+ np.ndarray
+ The new points, same shape as x.
+ """
free = ~active
gm = gk * (free[:, :, None] & free[:, None, :])
gm = gm + eye[None] * active[:, :, None]
@@ -627,8 +759,15 @@ def newton_point(gk, x, grad, active):
step = np.linalg.solve(gm + 1e-12 * eye[None], rhs)
return x + step[..., 0]
- def kkt_residual(x):
- """Gradient, active bounds and the largest free gradient."""
+ def kkt_residual(x: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Compute the gradient, active bounds and the largest free gradient.
+
+ Returns
+ -------
+ tuple
+ (grad, active, kkt): the gradient, the mask of variables a
+ bound holds, and the largest gradient among the others.
+ """
grad = np.einsum("mij,mj->mi", gs, x) - cs
active = ((x <= lo) & (grad > 0)) | ((x >= hi) & (grad < 0)) | dead
return grad, active, np.where(active, 0.0, np.abs(grad)).max(1)
@@ -644,15 +783,11 @@ def kkt_residual(x):
todo = ~done
gk, xt, gt = gs[todo], x[todo], grad[todo]
target = newton_point(gk, xt, gt, active[todo])
- x[todo] = _qp_backtrack(
- gk, cs[todo], xt, target, gt, lo[todo], hi[todo]
- )
+ x[todo] = _qp_backtrack(gk, cs[todo], xt, target, gt, lo[todo], hi[todo])
for i in np.nonzero(~done)[0]:
keep = ~dead[i]
xi = np.zeros(n)
- xi[keep] = _bvls_fallback(
- gs[i][np.ix_(keep, keep)], cs[i][keep], lo[i][keep], hi[i][keep]
- )
+ xi[keep] = _bvls_fallback(gs[i][np.ix_(keep, keep)], cs[i][keep], lo[i][keep], hi[i][keep])
x[i] = xi
kkt = kkt_residual(x)[2] / grad_scale
if np.any(kkt[~done] > 1e-6):
@@ -669,20 +804,28 @@ def kkt_residual(x):
def surround_operators(sel: np.ndarray, params: SolverParams) -> list:
- """The three surround filters as pixels x pixels matrices.
+ """Return the three surround filters as pixels x pixels matrices.
Dense where the filter reaches a good share of the pixels (a small
subproblem), sparse otherwise.
+
+ Returns
+ -------
+ list
+ One matrix per filter of params.bfilter, dense or sparse.
"""
ops = [conv_operator(sel, f) for f in params.bfilter]
- return [
- op.toarray() if op.nnz > 0.05 * op.shape[0] * op.shape[1] else op
- for op in ops
- ]
+ return [op.toarray() if op.nnz > 0.05 * op.shape[0] * op.shape[1] else op for op in ops]
def get_surround(hp: np.ndarray, operators: list) -> np.ndarray:
- """MATLAB's ``getSurround``: ``(filters, pixels, frames)``."""
+ """MATLAB's getSurround: (filters, pixels, frames).
+
+ Returns
+ -------
+ np.ndarray
+ The surround predictors, shape (filters, pixels, frames).
+ """
return np.stack([op @ hp for op in operators])
@@ -697,31 +840,29 @@ def baseline_programs(
operators: list | None = None,
offset: np.ndarray | None = None,
) -> dict:
- """The per-pixel quadratic programs of ``fitB``.
+ """Build the per-pixel quadratic programs of fitB.
Each pixel's coefficients are those of its sources' contributions,
the three surround predictors and the baseline spline, in that order.
- With ``offset`` (pixels x frames), the programs fit ``y - offset``:
+ With offset (pixels x frames), the programs fit y - offset:
the baseline is then the offset plus the surround and spline parts
- (``SolverParams.baseline_mode`` 'fit_from'). The coefficients' bounds
- still scale with the mean of ``y``.
+ (SolverParams.baseline_mode 'fit_from'). The coefficients' bounds
+ still scale with the mean of y.
Returns
-------
dict
- ``g`` (pixels x n x n) and ``c`` (pixels x n): the normal
+ g (pixels x n x n) and c (pixels x n): the normal
equations, with the curvature penalty on the spline block;
- ``lb``, ``ub``: the bounds; ``surround`` (3 x pixels x frames) and
- ``spline`` (frames x coefficients, sparse): the baseline's
- predictors; ``n_sources``.
+ lb, ub: the bounds; surround (3 x pixels x frames) and
+ spline (frames x coefficients, sparse): the baseline's
+ predictors; n_sources.
"""
n_px, n_t = y.shape
n_src = h.shape[1]
hx = h @ x
target = y if offset is None else y - offset
- _, hp = split_freq(
- target - hx, 2 * params.denoise_window, params.lp_factor
- )
+ _, hp = split_freq(target - hx, 2 * params.denoise_window, params.lp_factor)
hp[np.isnan(hp)] = 0
if operators is None:
operators = surround_operators(sel, params)
@@ -777,9 +918,7 @@ def baseline_programs(
wide = 10 * scale[:, None] * np.ones((1, n))
lb = -wide
lb[:, :n_src] = 0
- return dict(
- g=g, c=c, lb=lb, ub=wide, surround=sur, spline=bs, n_sources=n_src
- )
+ return {"g": g, "c": c, "lb": lb, "ub": wide, "surround": sur, "spline": bs, "n_sources": n_src}
def baseline_from_coef(
@@ -788,8 +927,16 @@ def baseline_from_coef(
min_baseline: float,
offset: np.ndarray | None = None,
) -> np.ndarray:
- """The baseline of ``fitB`` from its coefficients: surround + spline
- (plus the offset the programs were formed with, if any)."""
+ """Compute the baseline of fitB from its coefficients.
+
+ The baseline is surround + spline (plus the offset the programs were
+ formed with, if any).
+
+ Returns
+ -------
+ np.ndarray
+ The baseline (pixels x frames), bounded below by min_baseline.
+ """
n_src = programs["n_sources"]
sur, bs = programs["surround"], programs["spline"]
d = n_src + sur.shape[0]
@@ -811,14 +958,14 @@ def fit_baseline(
operators: list | None = None,
return_info: bool = False,
offset: np.ndarray | None = None,
-):
- """MATLAB's ``fitB``: the baseline given the activity, per pixel.
+) -> np.ndarray | tuple[np.ndarray, dict]:
+ """MATLAB's fitB: the baseline given the activity, per pixel.
- For each pixel, a bounded weighted least-squares fit of ``y`` to the
+ For each pixel, a bounded weighted least-squares fit of y to the
sources' contributions (>= 0), three fast predictors from the
surrounding pixels and a slow cubic B-spline with a curvature penalty.
The baseline is the fit without the sources' part, bounded below by
- ``params.min_baseline``.
+ params.min_baseline.
Parameters
----------
@@ -833,7 +980,7 @@ def fit_baseline(
sel : ndarray of bool
The crop of selected pixels.
operators : list, optional
- :func:`surround_operators` of ``sel``, to reuse them.
+ :func:`surround_operators` of sel, to reuse them.
return_info : bool
Also return the coefficients and the programs' convergence.
offset : ndarray of shape (pixels, frames), optional
@@ -844,16 +991,12 @@ def fit_baseline(
Returns
-------
b : ndarray of shape (pixels, frames)
- info : dict, if ``return_info``
- ``coef`` (pixels x (sources + 3 + spline coefficients)), and
- ``converged`` and ``kkt`` of :func:`solve_box_qp`.
+ info : dict, if return_info
+ coef (pixels x (sources + 3 + spline coefficients)), and
+ converged and kkt of :func:`solve_box_qp`.
"""
- programs = baseline_programs(
- b0, y, x, h, finv, sel, params, operators, offset
- )
- coef, info = solve_box_qp(
- programs["g"], programs["c"], programs["lb"], programs["ub"]
- )
+ programs = baseline_programs(b0, y, x, h, finv, sel, params, operators, offset)
+ coef, info = solve_box_qp(programs["g"], programs["c"], programs["lb"], programs["ub"])
b = baseline_from_coef(coef, programs, params.min_baseline, offset)
if return_info:
return b, dict(coef=coef, **info)
@@ -884,20 +1027,20 @@ def gain_programs(
finv: np.ndarray,
predictor: np.ndarray,
) -> dict:
- """Per-pixel programs of the gain fit, ``fitB``'s with one predictor.
+ """Per-pixel programs of the gain fit, fitB's with one predictor.
Each pixel's data are fitted by its sources' contributions (each with
a coefficient >= 0, as in :func:`baseline_programs`) and a gain times
- ``predictor`` (pixels x frames; an external baseline), with ``fitB``'s
- weights ``(1 / F) (b0 / (b0 + H x))^2`` and no penalty. The sources'
- coefficients are bounded as in ``fitB``, the gain to
- ``[0, GAIN_MAX]``.
+ predictor (pixels x frames; an external baseline), with fitB's
+ weights (1 / F) (b0 / (b0 + H x))^2 and no penalty. The sources'
+ coefficients are bounded as in fitB, the gain to
+ [0, GAIN_MAX].
Returns
-------
dict
- ``g`` (pixels x n x n), ``c`` (pixels x n), ``lb``, ``ub`` with
- ``n = sources + 1`` (the gain last), and ``n_sources``.
+ g (pixels x n x n), c (pixels x n), lb, ub with
+ n = sources + 1 (the gain last), and n_sources.
"""
n_px, _ = y.shape
n_src = h.shape[1]
@@ -923,7 +1066,7 @@ def gain_programs(
lb = np.zeros((n_px, n))
ub = 10 * scale[:, None] * np.ones((1, n))
ub[:, n_src] = GAIN_MAX
- return dict(g=g, c=c, lb=lb, ub=ub, n_sources=n_src)
+ return {"g": g, "c": c, "lb": lb, "ub": ub, "n_sources": n_src}
def fit_gain(
@@ -935,7 +1078,7 @@ def fit_gain(
predictor: np.ndarray,
min_baseline: float,
) -> tuple[np.ndarray, np.ndarray]:
- """The baseline ``max(min_baseline, gain * predictor)`` per pixel.
+ """Return the baseline max(min_baseline, gain * predictor) per pixel.
The gains come from :func:`gain_programs`, solved by
:func:`solve_box_qp`.
@@ -947,9 +1090,7 @@ def fit_gain(
The sources' coefficients and the gain (last).
"""
programs = gain_programs(b0, y, x, h, finv, predictor)
- coef, _ = solve_box_qp(
- programs["g"], programs["c"], programs["lb"], programs["ub"]
- )
+ coef, _ = solve_box_qp(programs["g"], programs["c"], programs["lb"], programs["ub"])
b = np.fmax(min_baseline, coef[:, -1:] * predictor)
return b, coef
@@ -961,49 +1102,49 @@ def shared_time_course(
finv: np.ndarray,
halves: tuple | None = None,
) -> tuple[np.ndarray, dict]:
- """A factor per frame shared by pixels, and how it was shrunk.
+ """Estimate a factor per frame shared by pixels, and how it was shrunk.
- From pixels (outside the footprints) with data ``y``, predicted
- baseline ``q`` and sources' part ``src`` (all pixels x frames): per
- frame, the weighted least-squares factor of ``q`` in ``y - src``,
+ From pixels (outside the footprints) with data y, predicted
+ baseline q and sources' part src (all pixels x frames): per
+ frame, the weighted least-squares factor of q in y - src,
c_t = sum_p w r q / sum_p w q^2, r = y - src,
w = 1 / (F (q + src + 1)) (the solver's loss weights),
- whose sampling variance is ``alpha / sum_p w q^2``, with ``alpha`` the
+ whose sampling variance is alpha / sum_p w q^2, with alpha the
mean weighted squared residual of the observed samples (not filled in)
of the reliable frames (1 if the loss's variance model holds).
Each frame's factor is then shrunk towards their precision-weighted
- mean ``m`` by the empirical-Bayes weight ``s2 / (s2 + var_t)``, where
- ``s2`` is the variance of the factors about ``m`` beyond their
+ mean m by the empirical-Bayes weight s2 / (s2 + var_t), where
+ s2 is the variance of the factors about m beyond their
sampling variance (at least 0), estimated from the reliable frames
- (sampling variance at most ``RELIABLE_FACTOR`` times its median, or
+ (sampling variance at most RELIABLE_FACTOR times its median, or
times ten times its 10th percentile if that is lower; this leaves out
filled-in frames, also where they are most of the trial). Without a
- shared change the factor is ``m`` throughout.
+ shared change the factor is m throughout.
- How ``s2`` is estimated:
+ How s2 is estimated:
- - with ``halves`` (two boolean masks over the pixels, spatially apart:
+ - with halves (two boolean masks over the pixels, spatially apart:
the solver splits the outside pixels at their median column or row
- with a gap): ``s2`` is the covariance over the reliable frames of
+ with a gap): s2 is the covariance over the reliable frames of
the factors estimated from each half alone. A change shared by the
pixels appears in both halves; noise shared only by neighbouring
pixels (the 200 Hz frames are resampled, so neighbours share
photons) does not. The sampling variance of each frame is then the
- factors' remaining variance, ``var(c) - s2``, apportioned by the
- frame's precision. With fewer than ``MIN_HALF`` pixels in a half,
- ``s2`` is 0.
- - without: ``s2`` is the factors' variance beyond the sampling
+ factors' remaining variance, var(c) - s2, apportioned by the
+ frame's precision. With fewer than MIN_HALF pixels in a half,
+ s2 is 0.
+ - without: s2 is the factors' variance beyond the sampling
variance that independent pixel noise would give. This holds only
- for independent noise (it over-estimates ``s2`` on resampled
+ for independent noise (it over-estimates s2 on resampled
frames).
Returns
-------
c : ndarray of shape (frames,)
info : dict
- ``raw`` (the unshrunk factors), ``mean`` (m), ``alpha``, ``s2``.
+ raw (the unshrunk factors), mean (m), alpha, s2.
"""
y, q, src = (np.asarray(a, np.float64) for a in (y, q, src))
w = 1.0 / (np.asarray(finv, np.float64) * (q + src + 1))
@@ -1015,7 +1156,7 @@ def shared_time_course(
raw = np.ones(n_t)
raw[ok] = num[ok] / den[ok]
if not ok.any():
- return raw, dict(raw=raw, mean=1.0, alpha=float("nan"), s2=0.0)
+ return raw, {"raw": raw, "mean": 1.0, "alpha": float("nan"), "s2": 0.0}
m = float(num[ok].sum() / den[ok].sum())
raw[~ok] = m
# reliable frames: sampling variance (proportional to 1 / den) at most
@@ -1035,7 +1176,7 @@ def shared_time_course(
alpha = float((w * (r - raw * q) ** 2)[seen].sum() / dof)
var_t = alpha * inv
spread = float(((raw[rel] - m) ** 2).sum() / max(int(rel.sum()) - 1, 1))
- record = dict(raw=raw, mean=m, alpha=alpha, var_raw=spread)
+ record = {"raw": raw, "mean": m, "alpha": alpha, "var_raw": spread}
if halves is None:
s2 = max(0.0, spread - float(var_t[rel].mean()))
else:
@@ -1057,13 +1198,22 @@ def shared_time_course(
return c, record
-def _shared_variance_halves(w, r, q, rel, halves):
- """Covariance of two halves' factors over the reliable frames (>= 0).
+def _shared_variance_halves(
+ w: np.ndarray, r: np.ndarray, q: np.ndarray, rel: np.ndarray, halves: tuple
+) -> tuple[float, float, np.ndarray]:
+ """Compute the covariance of two halves' factors over the reliable frames (>= 0).
- Returns ``(s2, cov, both)``: ``both`` are the frames reliable for the
- whole set and for each half, over which the covariance is taken.
- ``s2`` is 0 when a half has fewer than ``MIN_HALF`` pixels or fewer
- than two frames are reliable in both.
+ Returns
+ -------
+ s2 : float
+ The covariance, at least 0. It is 0 when a half has fewer than
+ MIN_HALF pixels or fewer than two frames are reliable in both.
+ cov : float
+ The covariance before it is bounded below by 0 (NaN where s2 is
+ 0 for lack of pixels or frames).
+ both : np.ndarray
+ The frames reliable for the whole set and for each half, over which
+ the covariance is taken.
"""
a, b = (np.asarray(x, dtype=bool) for x in halves)
if a.sum() < MIN_HALF or b.sum() < MIN_HALF:
@@ -1087,12 +1237,17 @@ def _shared_variance_halves(w, r, q, rel, halves):
def reliable_frames(den: np.ndarray) -> np.ndarray:
- """Frames whose factor is reliable, from its precision ``den``.
+ """Frames whose factor is reliable, from its precision den.
- A frame is reliable if ``den`` is positive and its sampling variance
- (proportional to ``1 / den``) is at most ``RELIABLE_FACTOR`` times its
+ A frame is reliable if den is positive and its sampling variance
+ (proportional to 1 / den) is at most RELIABLE_FACTOR times its
median over those frames, or times ten times its 10th percentile if
that is lower (for trials where most frames are filled in).
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask of the reliable frames, same shape as den.
"""
den = np.asarray(den, dtype=np.float64)
ok = den > 0
@@ -1105,12 +1260,14 @@ def reliable_frames(den: np.ndarray) -> np.ndarray:
return out
-def outside_halves(sel: np.ndarray, outside: np.ndarray, gap: float = 1.0):
+def outside_halves(
+ sel: np.ndarray, outside: np.ndarray, gap: float = 1.0
+) -> tuple[np.ndarray, np.ndarray]:
"""Two spatially separate halves of the outside pixels.
The outside pixels (a boolean mask over the subproblem's pixels, in
- ``sel``'s column-major order) are split at their median column, or
- row if they extend further in rows; pixels within ``gap`` of the
+ sel's column-major order) are split at their median column, or
+ row if they extend further in rows; pixels within gap of the
median are left out, so that the halves share no neighbours.
Returns
@@ -1136,26 +1293,26 @@ def fit_network_gain(
shared: bool = False,
sel: np.ndarray | None = None,
) -> tuple[np.ndarray, dict]:
- """The baseline step of the 'gain' and 'gain_shared' modes.
+ """Fit the baseline step of the 'gain' and 'gain_shared' modes.
- 'gain': ``B = g_p * b_ext`` with one gain per pixel
- (:func:`fit_gain`). 'gain_shared' (``shared``): ``B = g_p * b_ext *
- c_t``. The gains are fitted first with ``c = 1``; ``c`` is then
+ 'gain': B = g_p * b_ext with one gain per pixel
+ (:func:`fit_gain`). 'gain_shared' (shared): B = g_p * b_ext *
+ c_t. The gains are fitted first with c = 1; c is then
estimated from the pixels where every footprint is below
- ``params.outside_footprint`` of its largest value
+ params.outside_footprint of its largest value
(:func:`shared_time_course`; held at 1 with fewer than
- ``MIN_OUTSIDE`` such pixels), and the gains are fitted again with
- ``b_ext * c`` as the predictor.
+ MIN_OUTSIDE such pixels), and the gains are fitted again with
+ b_ext * c as the predictor.
Parameters
----------
b0 : ndarray of shape (pixels, frames)
- Current baseline (sets ``fitB``'s weights).
+ Current baseline (sets fitB's weights).
b_ext : ndarray of shape (pixels, frames)
The external baseline.
y, finv : ndarray of shape (pixels, frames)
x : ndarray of shape (sources, frames)
- Activity (thresholded, as for ``fitB``).
+ Activity (thresholded, as for fitB).
h : ndarray of shape (pixels, sources)
params : SolverParams
shared : bool
@@ -1170,11 +1327,11 @@ def fit_network_gain(
-------
b : ndarray of shape (pixels, frames)
info : dict
- ``gain`` (pixels); with ``shared``: ``shared`` (frames, c),
- ``n_outside``, and the :func:`shared_time_course` record.
+ gain (pixels); with shared: shared (frames, c),
+ n_outside, and the :func:`shared_time_course` record.
"""
b, coef = fit_gain(b0, y, x, h, finv, b_ext, params.min_baseline)
- info = dict(gain=coef[:, -1].copy())
+ info = {"gain": coef[:, -1].copy()}
if not shared:
return b, info
n_src = h.shape[1]
@@ -1188,18 +1345,21 @@ def fit_network_gain(
src = (coef[:, :n_src] * h) @ x
q = coef[:, -1:] * b_ext
halves = None if sel is None else outside_halves(sel, outside)
- c, record = shared_time_course(
- y[outside], q[outside], src[outside], finv[outside], halves
- )
- b, coef = fit_gain(
- b0, y, x, h, finv, b_ext * c[None, :], params.min_baseline
- )
+ c, record = shared_time_course(y[outside], q[outside], src[outside], finv[outside], halves)
+ b, coef = fit_gain(b0, y, x, h, finv, b_ext * c[None, :], params.min_baseline)
info.update(gain=coef[:, -1].copy(), shared=c, **record)
return b, info
def source_f0(h: np.ndarray, b: np.ndarray) -> np.ndarray:
- """Footprint-weighted baseline of each source (sources x frames)."""
+ """Footprint-weighted baseline of each source (sources x frames).
+
+ Returns
+ -------
+ np.ndarray
+ The baseline of each source, shape (sources, frames): the footprint-weighted
+ average of the baseline b over the pixels.
+ """
return (h.T @ b) / (h * h).sum(0)[:, None]
@@ -1211,7 +1371,9 @@ def source_f0(h: np.ndarray, b: np.ndarray) -> np.ndarray:
def core_mask(
h: np.ndarray, rows: np.ndarray, cols: np.ndarray, half: int = CORE_HALF
) -> np.ndarray:
- """Each source's core: the pixels within ``half`` pixels (in row and in
+ """Return each source's core.
+
+ The core is the pixels within half pixels (in row and in
column) of its footprint's peak pixel.
Parameters
@@ -1222,22 +1384,25 @@ def core_mask(
The pixels' positions (any common frame).
half : int
Half-width of the core: 0 is the peak pixel alone, 1 the 3 x 3
- around it (pixels that are not among ``rows``, ``cols`` are not in
+ around it (pixels that are not among rows, cols are not in
it).
Returns
-------
ndarray of bool, shape (pixels, sources)
No pixel for a source whose footprint is 0 everywhere.
+
+ Raises
+ ------
+ ValueError
+ If h, rows and cols disagree in the number of pixels, or half is
+ negative.
"""
h = np.asarray(h, dtype=np.float64)
rows = np.asarray(rows).ravel()
cols = np.asarray(cols).ravel()
if h.shape[0] != rows.size or rows.size != cols.size:
- raise ValueError(
- f"{h.shape[0]} footprint pixels and {rows.size} rows, "
- f"{cols.size} columns"
- )
+ raise ValueError(f"{h.shape[0]} footprint pixels and {rows.size} rows, {cols.size} columns")
if half < 0:
raise ValueError("half must not be negative")
if h.shape[0] == 0:
@@ -1260,9 +1425,9 @@ def source_core_f0(
"""Baseline of each source's core in footprint units (sources x frames).
The baseline summed over the core (:func:`core_mask`) divided by the
- share of the footprint in it, ``sum_C b / sum_C h``. A source's dF in
- footprint units divided by this is the dF/F of its core, ``sum_C (h dF)
- / sum_C b``: the flux of the source's activity in the core over the
+ share of the footprint in it, sum_C b / sum_C h. A source's dF in
+ footprint units divided by this is the dF/F of its core, sum_C (h dF)
+ / sum_C b: the flux of the source's activity in the core over the
baseline there. Unlike :func:`source_f0`, whose weights are the
footprint itself, it does not depend on how far the footprint reaches
beyond the core. NaN for a source without a footprint.
diff --git a/src/giant_python/extraction/raster/solver_fits.py b/src/giant_python/extraction/raster/solver_fits.py
index 7413a502..564ab83e 100644
--- a/src/giant_python/extraction/raster/solver_fits.py
+++ b/src/giant_python/extraction/raster/solver_fits.py
@@ -1,12 +1,12 @@
"""The iterative fits of SiLo's subproblem solver, on one loss, in torch.
-GIAnT-MATLAB's ``extractSources`` fits the activity (``fitS``), the
-footprints (``objfun_Hs``) and the debias refit on one loss,
+GIAnT-MATLAB's extractSources fits the activity (fitS), the
+footprints (objfun_Hs) and the debias refit on one loss,
sum((Z - T)^2 / (F (T + 1))), T = H (S * k) + B,
the squared residual over a variance that follows the model (or, in the
-debias refit, a variance held at ``F s0``). :func:`variance_loss` is that
+debias refit, a variance held at F s0). :func:`variance_loss` is that
loss with its first and second derivatives in T; the activity and the
footprint problems put their own linear maps around it, and
:func:`projected_newton` minimizes either within bounds.
@@ -21,15 +21,23 @@
from __future__ import annotations
import math
+from collections.abc import Callable
from dataclasses import dataclass, field
from threading import get_ident
+from typing import Any
import torch
import torch.nn.functional as tnf
-def variance_loss(z, t, w, s0=None, order: int = 2):
- """The solver's loss and its derivatives in the model T.
+def variance_loss(
+ z: torch.Tensor,
+ t: torch.Tensor,
+ w: torch.Tensor,
+ s0: torch.Tensor | None = None,
+ order: int = 2,
+) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
+ """Return the solver's loss and its derivatives in the model T.
Parameters
----------
@@ -38,16 +46,16 @@ def variance_loss(z, t, w, s0=None, order: int = 2):
w : Tensor of the same shape
Weights 1 / F (the freshness); 0 for padding.
s0 : Tensor of the same shape, optional
- If given, the variance term ``T + 1`` is held at ``s0``.
+ If given, the variance term T + 1 is held at s0.
order : {0, 1, 2}
Highest derivative to return.
Returns
-------
f : Tensor of shape (batch,)
- ``sum(w (z - t)^2 / (t + 1))``, summed in float64.
+ sum(w (z - t)^2 / (t + 1)), summed in float64.
g, c : Tensor or None
- First and second derivative of each sample's term in ``t``.
+ First and second derivative of each sample's term in t.
"""
e = z - t
if s0 is None:
@@ -73,16 +81,16 @@ class _LossWork:
The same operations in the same order on the same values, so the same
results to the last bit, but the factors that do not change during the
- fit (``-w``, ``2 w``; with ``s0``: ``w / s0``, ``-2 w / s0``,
- ``2 w / s0``) are formed once, and the arrays of the data's shape are
+ fit (-w, 2 w; with s0: w / s0, -2 w / s0,
+ 2 w / s0) are formed once, and the arrays of the data's shape are
written into buffers kept for the next evaluation instead of new
tensors each time. The derivatives returned are those buffers (or, for
- the curvature with ``s0``, a tensor kept for the whole fit): use them
+ the curvature with s0, a tensor kept for the whole fit): use them
before the next evaluation and do not change them.
"""
- def __init__(self, w: torch.Tensor, s0=None) -> None:
- """The fit's constant factors."""
+ def __init__(self, w: torch.Tensor, s0: torch.Tensor | None = None) -> None:
+ """Form the fit's constant factors."""
self.w, self.s0 = w, s0
self._buf = {}
if s0 is None:
@@ -94,14 +102,32 @@ def __init__(self, w: torch.Tensor, s0=None) -> None:
self.two_ws = 2 * self.ws
def buffer(self, name: str, like: torch.Tensor) -> torch.Tensor:
- """A scratch tensor laid out as ``torch.empty_like(like)``."""
+ """Return a scratch tensor laid out as torch.empty_like(like).
+
+ Returns
+ -------
+ torch.Tensor
+ The buffer kept under name, made anew if its shape or
+ stride differs from like.
+ """
b = self._buf.get(name)
if b is None or b.shape != like.shape or b.stride() != like.stride():
b = self._buf[name] = torch.empty_like(like)
return b
- def loss(self, z, t, order: int):
- """``variance_loss(z, t, w, s0, order)``; ``t`` is overwritten."""
+ def loss(
+ self, z: torch.Tensor, t: torch.Tensor, order: int
+ ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
+ """Return variance_loss(z, t, w, s0, order); t is overwritten.
+
+ Returns
+ -------
+ f : Tensor of shape (batch,)
+ The loss, summed in float64.
+ g, c : Tensor or None
+ First and second derivative of each sample's term in t
+ (kept buffers; None beyond order).
+ """
e = torch.sub(z, t, out=self.buffer("e", t))
if self.s0 is None:
s = t.add_(1)
@@ -124,8 +150,15 @@ def loss(self, z, t, order: int):
def _autocast(device_type: str) -> bool:
- """Whether torch's autocast is on for tensors of ``device_type``
- (it changes the type operations compute in)."""
+ """Return whether torch's autocast is on for tensors of device_type.
+
+ Autocast changes the type operations compute in.
+
+ Returns
+ -------
+ bool
+ True if autocast is enabled for device_type.
+ """
try:
return torch.is_autocast_enabled(device_type)
except TypeError: # torch before 2.4: no argument, and CUDA only
@@ -134,31 +167,46 @@ def _autocast(device_type: str) -> bool:
)
-def _plain(z, b, w, s0) -> bool:
- """Whether a fit's arrays suit :class:`_LossWork`: no autograd, and z,
- b, w (and s0) contiguous, of one shape and type, as the solver makes
- them (the buffers then have the layout and type that the operations
- would give)."""
+def _plain(z: torch.Tensor, b: torch.Tensor, w: torch.Tensor, s0: torch.Tensor | None) -> bool:
+ """Return whether a fit's arrays suit :class:`_LossWork`.
+
+ That is: no autograd, and z, b, w (and s0) contiguous, of one shape
+ and type, as the solver makes them (the buffers then have the layout
+ and type that the operations would give).
+
+ Returns
+ -------
+ bool
+ True if the arrays suit :class:`_LossWork`.
+ """
arrays = [a for a in (z, b, w, s0) if a is not None]
return all(
- not a.requires_grad
- and a.is_contiguous()
- and a.shape == z.shape
- and a.dtype == z.dtype
+ not a.requires_grad and a.is_contiguous() and a.shape == z.shape and a.dtype == z.dtype
for a in arrays
)
-def _geometric_sum(x: torch.Tensor, a: float, taps: int, back: bool):
- """``sum_d a^d x[t - d]`` over d < taps (``x[t + d]`` if not back).
+def _geometric_sum(x: torch.Tensor, a: float, taps: int, back: bool) -> torch.Tensor:
+ """Return sum_d a^d x[t - d] over d < taps (x[t + d] if not back).
By doubling: the sum over 2m taps is the sum over m plus a^m times
itself shifted by m, so a kernel of n taps costs about 2 log2(n)
shifted additions instead of n.
+
+ Returns
+ -------
+ torch.Tensor
+ The sum, of the shape of x.
"""
- def shifted_add(y, z, m, c):
- """y + c * (z shifted by m frames, zero-filled)."""
+ def shifted_add(y: torch.Tensor, z: torch.Tensor, m: int, c: float) -> torch.Tensor:
+ """Return y + c * (z shifted by m frames, zero-filled).
+
+ Returns
+ -------
+ torch.Tensor
+ The sum (y itself if m reaches past the frames).
+ """
if m >= y.shape[-1]:
return y
if y.requires_grad or z.requires_grad:
@@ -190,13 +238,13 @@ class _KeptSum:
The same copies and additions on the same values in the same order,
so the same sums to the last bit, but the additions alternate between
- two tensors made once (by ``torch.empty_like``, as before) instead of
+ two tensors made once (by torch.empty_like, as before) instead of
a new tensor each, and the slices of those tensors are made once too:
a call makes only three slices, of its input. The result is one of
the kept tensors (or the input itself): use it before the next call.
"""
- def __init__(self, like: torch.Tensor, a: float, taps: int, back: bool):
+ def __init__(self, like: torch.Tensor, a: float, taps: int, back: bool) -> None:
"""Lay out the doubling schedule of :func:`_geometric_sum`."""
n = like.shape[-1]
bufs = (torch.empty_like(like), torch.empty_like(like))
@@ -204,9 +252,18 @@ def __init__(self, like: torch.Tensor, a: float, taps: int, back: bool):
self.steps = []
inp = -1 # the input, as opposed to kept tensor 0 or 1
- def shifted_add(y, z, m, c):
- """Record y + c * (z shifted by m frames) into a kept tensor
- that is neither y nor z; the input only ever comes with m=1."""
+ def shifted_add(y: int, z: int, m: int, c: float) -> int:
+ """Record y + c * (z shifted by m frames) into a kept tensor.
+
+ The kept tensor is neither y nor z; the input only ever comes
+ with m=1.
+
+ Returns
+ -------
+ int
+ The index (0 or 1) of the kept tensor written, or y
+ itself if m reaches past the frames.
+ """
if m >= n:
return y
o = 1 if 0 in (y, z) else 0
@@ -217,11 +274,7 @@ def shifted_add(y, z, m, c):
zs = None if z == inp else bufs[z][..., :-m]
else:
cut = (out[..., -m:], out[..., :-m])
- ys = (
- None
- if y == inp
- else (bufs[y][..., -m:], bufs[y][..., :-m])
- )
+ ys = None if y == inp else (bufs[y][..., -m:], bufs[y][..., :-m])
zs = None if z == inp else bufs[z][..., m:]
self.steps.append((cut, ys, zs, c))
return o
@@ -236,7 +289,13 @@ def shifted_add(y, z, m, c):
self.result = None if y == inp else bufs[y]
def __call__(self, x: torch.Tensor) -> torch.Tensor:
- """The sum for x."""
+ """Return the sum for x.
+
+ Returns
+ -------
+ torch.Tensor
+ One of the kept tensors, or x itself if no addition is needed.
+ """
if self.result is None:
return x
if self.back:
@@ -246,9 +305,7 @@ def __call__(self, x: torch.Tensor) -> torch.Tensor:
for (out_head, out_body), ys, zs, c in self.steps:
if ys is None:
out_head.copy_(head)
- torch.add(
- body, shifted if zs is None else zs, alpha=c, out=out_body
- )
+ torch.add(body, shifted if zs is None else zs, alpha=c, out=out_body)
else:
out_head.copy_(ys[0])
torch.add(ys[1], zs, alpha=c, out=out_body)
@@ -256,17 +313,23 @@ def __call__(self, x: torch.Tensor) -> torch.Tensor:
class TimeKernel:
- """MATLAB ``convn(x, k, 'same')`` along the last axis, and its adjoint.
+ """MATLAB convn(x, k, 'same') along the last axis, and its adjoint.
- ``k`` has an odd length, as the solver's kernels do. Only its nonzero
+ k has an odd length, as the solver's kernels do. Only its nonzero
stretch is applied (the kernels are causal: their first half is zero).
- A causal exponential (``gain * decay^d`` from the centre on, as
- ``setParamsExtractTrial`` builds them) is applied by shifted
- additions (:func:`_geometric_sum`), other kernels by ``conv1d``.
+ A causal exponential (gain * decay^d from the centre on, as
+ setParamsExtractTrial builds them) is applied by shifted
+ additions (:func:`_geometric_sum`), other kernels by conv1d.
"""
def __init__(self, k: torch.Tensor) -> None:
- """Find the kernel's nonzero stretch and whether it is exponential."""
+ """Find the kernel's nonzero stretch and whether it is exponential.
+
+ Raises
+ ------
+ ValueError
+ If the kernel does not have an odd length.
+ """
self._sums = {}
k = k.flatten()
if k.numel() % 2 != 1:
@@ -290,16 +353,21 @@ def __init__(self, k: torch.Tensor) -> None:
if 0 < a < 1 and bool(((ratio - a).abs() <= 1e-6 * a).all()):
self.decay = a
- def _convolve_exponential(
- self, x: torch.Tensor, back: bool
- ) -> torch.Tensor:
- """``gain`` times :func:`_geometric_sum` of x, a new tensor. The
- sum is made in kept tensors (:class:`_KeptSum`, one per input
+ def _convolve_exponential(self, x: torch.Tensor, back: bool) -> torch.Tensor:
+ """Return gain times :func:`_geometric_sum` of x, a new tensor.
+
+ The sum is made in kept tensors (:class:`_KeptSum`, one per input
layout) on the thread that first called this kernel, outside
autograd and inference mode; any other call makes it in new
tensors, as before there were kept ones (two threads would
overwrite each other's kept tensors, and tensors made in
- inference mode cannot be written outside it)."""
+ inference mode cannot be written outside it).
+
+ Returns
+ -------
+ torch.Tensor
+ gain times the geometric sum of x.
+ """
a, taps = self.decay, self.lag + 1
thread = get_ident()
# setdefault: one thread owns the kept tensors, also when two
@@ -317,29 +385,42 @@ def _convolve_exponential(
return self.gain * kept(x)
def conv(self, x: torch.Tensor) -> torch.Tensor:
- """``convn(x, k, 'same')`` along the last axis."""
+ """Return convn(x, k, 'same') along the last axis.
+
+ Returns
+ -------
+ torch.Tensor
+ The convolution, of the shape of x.
+ """
if self.decay is not None:
return self._convolve_exponential(x, True)
- y = tnf.conv1d(
- tnf.pad(x.reshape(-1, 1, x.shape[-1]), self.pad_fwd), self.fwd
- )
+ y = tnf.conv1d(tnf.pad(x.reshape(-1, 1, x.shape[-1]), self.pad_fwd), self.fwd)
return y.reshape(x.shape)
def conv_adj(self, x: torch.Tensor) -> torch.Tensor:
- """``convn(x, flip(k), 'same')``: the adjoint of :meth:`conv`."""
+ """Return convn(x, flip(k), 'same'): the adjoint of :meth:`conv`.
+
+ Returns
+ -------
+ torch.Tensor
+ The adjoint convolution, of the shape of x.
+ """
if self.decay is not None:
return self._convolve_exponential(x, False)
- y = tnf.conv1d(
- tnf.pad(x.reshape(-1, 1, x.shape[-1]), self.pad_adj), self.adj
- )
+ y = tnf.conv1d(tnf.pad(x.reshape(-1, 1, x.shape[-1]), self.pad_adj), self.adj)
return y.reshape(x.shape)
-def _overlap_pairs(o: torch.Tensor):
+def _overlap_pairs(o: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Index pairs (j <= l) of a batch of symmetric overlap matrices.
Pairs whose overlap is above 1e-12 of the geometric mean of their own
(in any batch member), and every (j, j).
+
+ Returns
+ -------
+ jj, ll : Tensor of int
+ The first and second index of each pair, jj <= ll.
"""
d = torch.sqrt(torch.diagonal(o, dim1=-2, dim2=-1))
keep = (o > 1e-12 * d[:, :, None] * d[:, None, :]).any(0)
@@ -358,8 +439,14 @@ def __init__(self, jj: torch.Tensor, ll: torch.Tensor) -> None:
self.jo, self.lo = jj[self.off], ll[self.off]
self.self_idx = torch.nonzero(jj == ll).flatten()
- def apply(self, m: torch.Tensor, x: torch.Tensor, dim: int = -1):
- """``m`` holds the pairs along ``dim``, ``x`` the sources."""
+ def apply(self, m: torch.Tensor, x: torch.Tensor, dim: int = -1) -> torch.Tensor:
+ """Apply the pair sums: m holds the pairs along dim, x the sources.
+
+ Returns
+ -------
+ torch.Tensor
+ The sums y_j, of the shape of x.
+ """
y = torch.zeros_like(x)
y.index_add_(dim, self.jj, m * x.index_select(dim, self.ll))
if self.off.numel():
@@ -374,9 +461,9 @@ def apply(self, m: torch.Tensor, x: torch.Tensor, dim: int = -1):
class ActivityProblem:
"""The activity fit: events S given footprints H and baseline B.
- Minimizes ``sum(w (Z - T)^2 / (T + 1)) + lam sum(S)`` with
- ``T = H (S * k) + B`` (MATLAB's ``fitS``); with ``s0`` the variance
- term is held at ``s0`` (the debias refit).
+ Minimizes sum(w (Z - T)^2 / (T + 1)) + lam sum(S) with
+ T = H (S * k) + B (MATLAB's fitS); with s0 the variance
+ term is held at s0 (the debias refit).
Parameters
----------
@@ -392,7 +479,16 @@ class ActivityProblem:
Fixed variance term.
"""
- def __init__(self, z, h, b, k, w, lam: float, s0=None) -> None:
+ def __init__(
+ self,
+ z: torch.Tensor,
+ h: torch.Tensor,
+ b: torch.Tensor,
+ k: torch.Tensor,
+ w: torch.Tensor,
+ lam: float,
+ s0: torch.Tensor | None = None,
+ ) -> None:
"""Keep the data and find the source pairs that overlap."""
self.z, self.h, self.b, self.w = z, h, b, w
self.ht = h.transpose(1, 2).contiguous()
@@ -407,19 +503,34 @@ def __init__(self, z, h, b, k, w, lam: float, s0=None) -> None:
self.q = None
self._tail = None
self._work = _LossWork(w, s0)
- self._plain = (
- _plain(z, b, w, s0) and h.dtype == z.dtype and not h.requires_grad
- )
+ self._plain = _plain(z, b, w, s0) and h.dtype == z.dtype and not h.requires_grad
def model(self, s: torch.Tensor) -> torch.Tensor:
- """T = H (S * k) + B."""
+ """Return T = H (S * k) + B.
+
+ Returns
+ -------
+ torch.Tensor
+ The model, of shape (batch, pixels, frames).
+ """
return self.h @ self.kernel.conv(s) + self.b
- def _loss(self, s: torch.Tensor, order: int):
- """``variance_loss`` at T(S): through :class:`_LossWork` (its
- buffers) for the solver's own tensors; with the plain expressions
- when autograd follows an array, the types differ, or autocast or
- inference mode is on."""
+ def _loss(
+ self, s: torch.Tensor, order: int
+ ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
+ """Return variance_loss at T(S).
+
+ It goes through :class:`_LossWork` (its buffers) for the solver's
+ own tensors; with the plain expressions when autograd follows an
+ array, the types differ, or autocast or inference mode is on.
+
+ Returns
+ -------
+ f : Tensor of shape (batch,)
+ The loss.
+ g, c : Tensor or None
+ First and second derivative in T (None beyond order).
+ """
x = self.kernel.conv(s)
if (
not self._plain
@@ -435,12 +546,26 @@ def _loss(self, s: torch.Tensor, order: int):
return self._work.loss(self.z, t, order)
def value(self, s: torch.Tensor) -> torch.Tensor:
- """The loss at S, per batch member."""
+ """Return the loss at S, per batch member.
+
+ Returns
+ -------
+ torch.Tensor
+ The loss plus the L1 penalty, of shape (batch,).
+ """
f, _, _ = self._loss(s, 0)
return f + self.lam * s.sum((-2, -1), dtype=torch.float64)
- def value_grad(self, s: torch.Tensor):
- """Loss and gradient at S; keeps the curvature for the products."""
+ def value_grad(self, s: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Return loss and gradient at S; keeps the curvature for the products.
+
+ Returns
+ -------
+ f : Tensor of shape (batch,)
+ The loss plus the L1 penalty.
+ grad : Tensor
+ The gradient, in S's layout.
+ """
fixed_q = self.s0 is not None and self.q is not None
f, g, c = self._loss(s, 1 if fixed_q else 2)
if not fixed_q:
@@ -451,21 +576,38 @@ def value_grad(self, s: torch.Tensor):
return f + self.lam * s.sum((-2, -1), dtype=torch.float64), grad
def hess_mult(self, v: torch.Tensor) -> torch.Tensor:
- """Hessian product at the point of the last :meth:`value_grad`."""
+ """Return the Hessian product at the point of the last :meth:`value_grad`.
+
+ Returns
+ -------
+ torch.Tensor
+ The product of the Hessian with v, in S's layout.
+ """
y = self.pairs.apply(self.q, self.kernel.conv(v), dim=1)
return self.kernel.conv_adj(y)
def hess_diag(self) -> torch.Tensor:
- """The Hessian's diagonal, in S's layout."""
+ """Return the Hessian's diagonal, in S's layout.
+
+ Returns
+ -------
+ torch.Tensor
+ The diagonal, in S's layout.
+ """
return self.kernel_sq.conv_adj(self.q[:, self.pairs.self_idx])
- def _tail_curvature(self):
- """Each source's curvature summed over the decay that follows.
+ def _tail_curvature(self) -> torch.Tensor:
+ """Return each source's curvature summed over the decay that follows.
- ``sum_v m[v] decay^(2 (v - u))`` over v >= u, for every frame u,
+ sum_v m[v] decay^(2 (v - u)) over v >= u, for every frame u,
with m the curvature of the source's own activity; from a
cumulative sum in the log domain, which neither overflows nor
cancels.
+
+ Returns
+ -------
+ torch.Tensor
+ The sums, with one more frame than the activity (a zero last frame).
"""
if self._tail is None:
m = self.q[:, self.pairs.self_idx]
@@ -482,8 +624,10 @@ def _tail_curvature(self):
self._tail = torch.cat([tail, torch.zeros_like(tail[..., :1])], -1)
return self._tail
- def preconditioner(self, free: torch.Tensor, diag: torch.Tensor):
- """An approximate inverse of the Hessian on the free events.
+ def preconditioner(
+ self, free: torch.Tensor, diag: torch.Tensor
+ ) -> Callable[[torch.Tensor], torch.Tensor]:
+ """Return an approximate inverse of the Hessian on the free events.
With an exponential kernel the activity follows a first-order
recursion, x[t] = decay x[t-1] + gain s[t]. Between two free
@@ -494,6 +638,12 @@ def preconditioner(self, free: torch.Tensor, diag: torch.Tensor):
passes over the frames. It is exact for one source up to the
kernel's truncation; the coupling between sources is left to the
conjugate gradients. Other kernels get the Hessian's diagonal.
+
+ Returns
+ -------
+ Callable
+ A function that applies the approximate inverse to a tensor
+ of the layout of free.
"""
fm = free.to(diag.dtype)
a = self.kernel.decay
@@ -503,9 +653,7 @@ def preconditioner(self, free: torch.Tensor, diag: torch.Tensor):
lag = self.kernel.lag
idx = torch.arange(n_t, device=free.device).expand(free.shape)
last = torch.where(free, idx, -1).cummax(-1).values
- prv = torch.cat(
- [torch.full_like(last[..., :1], -1), last[..., :-1]], -1
- )
+ prv = torch.cat([torch.full_like(last[..., :1], -1), last[..., :-1]], -1)
nxt = torch.where(free, idx, n_t).flip(-1).cummin(-1).values.flip(-1)
nxt = torch.cat([nxt[..., 1:], torch.full_like(nxt[..., :1], n_t)], -1)
gap_p, gap_n = idx - prv, nxt - idx
@@ -514,16 +662,20 @@ def preconditioner(self, free: torch.Tensor, diag: torch.Tensor):
cn = torch.where((nxt < n_t) & (gap_n <= lag), a ** gap_n.to(dt), 0.0)
reach = gap_n.clamp(max=lag + 1)
tail = self._tail_curvature()
- m = tail[..., :-1] - a ** (2 * reach.to(dt)) * tail.gather(
- -1, idx + reach
- )
+ m = tail[..., :-1] - a ** (2 * reach.to(dt)) * tail.gather(-1, idx + reach)
scale = fm.to(dt) / (self.kernel.gain**2 * m)
prv, nxt = prv.clamp(min=0), nxt.clamp(max=n_t - 1)
cp, cn = cp.to(diag.dtype), cn.to(diag.dtype)
scale = scale.to(diag.dtype)
- def apply(r):
- """D M^-1 D^T on the free events."""
+ def apply(r: torch.Tensor) -> torch.Tensor:
+ """Return D M^-1 D^T on the free events.
+
+ Returns
+ -------
+ torch.Tensor
+ The product, of the layout of r.
+ """
u = (r - cn * r.gather(-1, nxt)) * scale
return fm * (u - cp * u.gather(-1, prv))
@@ -533,10 +685,10 @@ def apply(r):
class FootprintProblem:
"""The footprint fit: super-resolved footprints Hs given the activity.
- Minimizes ``sum(w (Z - T)^2 / (T + 1))`` with ``T = (G Hs) X + B``,
+ Minimizes sum(w (Z - T)^2 / (T + 1)) with T = (G Hs) X + B,
where G applies the footprint filter on the selected pixels (MATLAB's
- ``objfun_Hs`` and ``hessmult_Hs``); with ``s0`` the variance term is
- held at ``s0``.
+ objfun_Hs and hessmult_Hs); with s0 the variance term is
+ held at s0.
Parameters
----------
@@ -551,7 +703,16 @@ class FootprintProblem:
Fixed variance term.
"""
- def __init__(self, z, x, b, g, w, support, s0=None) -> None:
+ def __init__(
+ self,
+ z: torch.Tensor,
+ x: torch.Tensor,
+ b: torch.Tensor,
+ g: torch.Tensor,
+ w: torch.Tensor,
+ support: torch.Tensor,
+ s0: torch.Tensor | None = None,
+ ) -> None:
"""Keep the data and find the source pairs that interact."""
self.z, self.x, self.b, self.w, self.g = z, x, b, w, g
self.s0 = s0
@@ -570,14 +731,31 @@ def __init__(self, z, x, b, g, w, support, s0=None) -> None:
)
def footprints(self, hs: torch.Tensor) -> torch.Tensor:
- """H = G Hs."""
+ """Return H = G Hs.
+
+ Returns
+ -------
+ torch.Tensor
+ The footprints, of shape (batch, pixels, sources).
+ """
return self.g @ hs
- def _loss(self, hs: torch.Tensor, order: int):
- """``variance_loss`` at T(Hs): through :class:`_LossWork` (its
- buffers) for the solver's own tensors; with the plain expressions
- when autograd follows an array, the types differ, or autocast or
- inference mode is on."""
+ def _loss(
+ self, hs: torch.Tensor, order: int
+ ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
+ """Return variance_loss at T(Hs).
+
+ It goes through :class:`_LossWork` (its buffers) for the solver's
+ own tensors; with the plain expressions when autograd follows an
+ array, the types differ, or autocast or inference mode is on.
+
+ Returns
+ -------
+ f : Tensor of shape (batch,)
+ The loss.
+ g, c : Tensor or None
+ First and second derivative in T (None beyond order).
+ """
h = self.g @ hs
if (
not self._plain
@@ -593,11 +771,25 @@ def _loss(self, hs: torch.Tensor, order: int):
return self._work.loss(self.z, t, order)
def value(self, hs: torch.Tensor) -> torch.Tensor:
- """The loss at Hs, per batch member."""
+ """Return the loss at Hs, per batch member.
+
+ Returns
+ -------
+ torch.Tensor
+ The loss, of shape (batch,).
+ """
return self._loss(hs, 0)[0]
- def value_grad(self, hs: torch.Tensor):
- """Loss and gradient at Hs; keeps the curvature for the products."""
+ def value_grad(self, hs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Return loss and gradient at Hs; keeps the curvature for the products.
+
+ Returns
+ -------
+ f : Tensor of shape (batch,)
+ The loss.
+ grad : Tensor
+ The gradient, in Hs's layout.
+ """
f, g, c = self._loss(hs, 2)
# curvature summed over frames: pixels x source pairs; with s0
# and the buffered loss it does not change during the fit (c is
@@ -613,15 +805,36 @@ def value_grad(self, hs: torch.Tensor):
return f, self.gt @ (g @ self.xt)
def hess_mult(self, v: torch.Tensor) -> torch.Tensor:
- """Hessian product at the point of the last :meth:`value_grad`."""
+ """Return the Hessian product at the point of the last :meth:`value_grad`.
+
+ Returns
+ -------
+ torch.Tensor
+ The product of the Hessian with v, in Hs's layout.
+ """
return self.gt @ self.pairs.apply(self.p, self.g @ v)
def hess_diag(self) -> torch.Tensor:
- """The Hessian's diagonal, in Hs's layout."""
+ """Return the Hessian's diagonal, in Hs's layout.
+
+ Returns
+ -------
+ torch.Tensor
+ The diagonal, in Hs's layout.
+ """
return self.g2t @ self.p[:, :, self.pairs.self_idx]
- def preconditioner(self, free: torch.Tensor, diag: torch.Tensor):
- """The inverse of the Hessian's diagonal on the free entries."""
+ def preconditioner(
+ self, free: torch.Tensor, diag: torch.Tensor
+ ) -> Callable[[torch.Tensor], torch.Tensor]:
+ """Return the inverse of the Hessian's diagonal on the free entries.
+
+ Returns
+ -------
+ Callable
+ A function that multiplies a tensor of the layout of free
+ by that inverse.
+ """
minv = free.to(diag.dtype) / diag
return lambda r: minv * r
@@ -662,22 +875,54 @@ class FitInfo:
def _dot(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
- """Inner product of each batch member, in float64."""
+ """Inner product of each batch member, in float64.
+
+ Returns
+ -------
+ torch.Tensor
+ The inner products, of shape (batch,).
+ """
return (a * b).flatten(1).sum(1, dtype=torch.float64)
def _per_member(v: torch.Tensor, like: torch.Tensor) -> torch.Tensor:
- """A per-member vector shaped to broadcast against ``like``."""
+ """Return a per-member vector shaped to broadcast against like.
+
+ Returns
+ -------
+ torch.Tensor
+ v reshaped to (batch, 1, ..., 1), with as many dimensions as like.
+ """
return v.reshape(-1, *([1] * (like.dim() - 1)))
def _scale(s: torch.Tensor, a: torch.Tensor) -> torch.Tensor:
- """Each batch member of ``a`` times its own scalar."""
+ """Each batch member of a times its own scalar.
+
+ Returns
+ -------
+ torch.Tensor
+ The scaled tensor, of the shape and type of a.
+ """
return _per_member(s.to(a.dtype), a) * a
-def _pcg(amul, rhs, precond, tol, max_iter: int):
- """Preconditioned conjugate gradients for a batch of systems."""
+def _pcg(
+ amul: Callable[[torch.Tensor], torch.Tensor],
+ rhs: torch.Tensor,
+ precond: Callable[[torch.Tensor], torch.Tensor],
+ tol: torch.Tensor,
+ max_iter: int,
+) -> tuple[torch.Tensor, int]:
+ """Preconditioned conjugate gradients for a batch of systems.
+
+ Returns
+ -------
+ x : Tensor
+ The solution, of the shape of rhs.
+ n : int
+ The number of iterations made.
+ """
x = torch.zeros_like(rhs)
r = rhs.clone()
zv = precond(r)
@@ -706,14 +951,38 @@ def _pcg(amul, rhs, precond, tol, max_iter: int):
return x, n
-def _arc_search(problem, g, d, hd, q, delta, t, lo, hi, search):
+def _arc_search(
+ problem: ActivityProblem | FootprintProblem,
+ g: torch.Tensor,
+ d: torch.Tensor,
+ hd: torch.Tensor,
+ q: torch.Tensor,
+ delta: torch.Tensor,
+ t: torch.Tensor,
+ lo: torch.Tensor,
+ hi: torch.Tensor,
+ search: torch.Tensor,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, int]:
"""Backtracking search on the model along a projected step.
- From the step ``d`` (model value ``q``, ``hd`` = H d), tries
- ``clamp(d + t delta)`` for the members in ``search``, halving ``t``
- until the model decreases enough. Returns the new ``d``, ``hd``,
- ``q``, the unprojected step taken, the step lengths and the number
- of Hessian products used.
+ From the step d (model value q, hd = H d), tries
+ clamp(d + t delta) for the members in search, halving t
+ until the model decreases enough.
+
+ Returns
+ -------
+ d : Tensor
+ The new step.
+ hd : Tensor
+ The new H d.
+ q : Tensor
+ The new model value.
+ raw : Tensor
+ The unprojected step taken.
+ t : Tensor
+ The step lengths.
+ n_prod : int
+ The number of Hessian products used.
"""
grad_q = g + hd
d_old, raw = d, d
@@ -737,10 +1006,20 @@ def _arc_search(problem, g, d, hd, q, delta, t, lo, hi, search):
return d, hd, q, raw, t, n_prod
-def _model_step(problem, g, diag, lo, hi, alive, tol, cg_iter, rounds):
- """A step that lowers the quadratic model within the bounds.
-
- Minimizes ``q(d) = g.d + d.Hd / 2`` over ``lo <= d <= hi``
+def _model_step(
+ problem: ActivityProblem | FootprintProblem,
+ g: torch.Tensor,
+ diag: torch.Tensor,
+ lo: torch.Tensor,
+ hi: torch.Tensor,
+ alive: torch.Tensor,
+ tol: torch.Tensor,
+ cg_iter: int,
+ rounds: int,
+) -> tuple[torch.Tensor, torch.Tensor, int]:
+ """Find a step that lowers the quadratic model within the bounds.
+
+ Minimizes q(d) = g.d + d.Hd / 2 over lo <= d <= hi
approximately, as trust-region Newton methods for bound constraints
do: a projected, diagonally scaled gradient step picks the variables
that no bound holds; then conjugate gradients on those, a backtracking
@@ -748,8 +1027,14 @@ def _model_step(problem, g, diag, lo, hi, alive, tol, cg_iter, rounds):
reached a bound held there, until none does. Each search starts from
twice the step length that the round before accepted.
- Returns the step, the model's value there (per member) and the
- number of Hessian products.
+ Returns
+ -------
+ d : Tensor
+ The step.
+ q : Tensor
+ The model's value there (per member).
+ n_prod : int
+ The number of Hessian products.
"""
zero = torch.zeros_like(g)
q = torch.zeros(g.shape[0], dtype=torch.float64, device=g.device)
@@ -778,9 +1063,7 @@ def _model_step(problem, g, diag, lo, hi, alive, tol, cg_iter, rounds):
search = todo & (_dot(delta, delta) > 0)
if not search.any():
break
- d, hd, q, raw, t, n = _arc_search(
- problem, g, d, hd, q, delta, t, lo, hi, search
- )
+ d, hd, q, raw, t, n = _arc_search(problem, g, d, hd, q, delta, t, lo, hi, search)
n_prod += n
t = (2 * t).clamp(max=1.0)
# the variables that the bounds cut are held there from now on;
@@ -793,11 +1076,11 @@ def _model_step(problem, g, diag, lo, hi, alive, tol, cg_iter, rounds):
return d, q, n_prod
-def projected_newton( # noqa: C901
- problem,
+def projected_newton(
+ problem: ActivityProblem | FootprintProblem,
x0: torch.Tensor,
- lb,
- ub,
+ lb: torch.Tensor | float,
+ ub: torch.Tensor | float,
*,
max_iter: int = 100,
ftol: float | None = None,
@@ -819,13 +1102,13 @@ def projected_newton( # noqa: C901
Parameters
----------
problem : object
- With ``value(x)``, ``value_grad(x)`` (which keeps the curvature),
- ``hess_mult(v)``, ``hess_diag()`` and ``preconditioner(free,
- diag)``; values are per batch member.
+ With value(x), value_grad(x) (which keeps the curvature),
+ hess_mult(v), hess_diag() and preconditioner(free,
+ diag); values are per batch member.
x0 : Tensor of shape (batch, ...)
Start; it is projected into the bounds.
lb, ub : Tensor or float
- Bounds, broadcastable to ``x0``. Variables with ``lb == ub`` stay
+ Bounds, broadcastable to x0. Variables with lb == ub stay
there.
max_iter : int
Cap on the Newton iterations.
@@ -871,9 +1154,7 @@ def projected_newton( # noqa: C901
floor = diag.flatten(1).amax(1).clamp_min(1e-300) * 1e-12
diag = torch.maximum(diag, _per_member(floor, diag))
tol = torch.sqrt(opt / opt0).clamp(1e-8, cg_tol)
- d, q, n = _model_step(
- problem, g, diag, lo, hi, alive, tol, cg_iter, rounds
- )
+ d, q, n = _model_step(problem, g, diag, lo, hi, alive, tol, cg_iter, rounds)
n_prod += n
pred = torch.where(alive, -q, pred)
done = alive & (-q <= ftol * (1 + f.abs()))
@@ -934,9 +1215,19 @@ def projected_newton( # noqa: C901
def fit_activity(
- z, h, b, k, w, lam: float, s_start, *, s0=None, free=None, **options
+ z: torch.Tensor,
+ h: torch.Tensor,
+ b: torch.Tensor,
+ k: torch.Tensor,
+ w: torch.Tensor,
+ lam: float,
+ s_start: torch.Tensor,
+ *,
+ s0: torch.Tensor | None = None,
+ free: torch.Tensor | None = None,
+ **options: Any, # noqa: ANN401
) -> tuple[torch.Tensor, FitInfo]:
- """Fit the events S >= 0 (MATLAB's ``fitS``), to convergence.
+ """Fit the events S >= 0 (MATLAB's fitS), to convergence.
Parameters
----------
@@ -956,6 +1247,13 @@ def fit_activity(
Entries of S to fit; the others are held at 0.
**options
Passed to :func:`projected_newton`.
+
+ Returns
+ -------
+ s : Tensor of shape (batch, sources, frames)
+ The fitted events.
+ info : FitInfo
+ How the fit ended.
"""
problem = ActivityProblem(z, h, b, k, w, lam, s0)
ub = torch.full_like(s_start, float("inf"))
@@ -966,11 +1264,20 @@ def fit_activity(
def fit_footprints(
- z, x, b, g, w, hs_start, valid, *, s0=None, **options
+ z: torch.Tensor,
+ x: torch.Tensor,
+ b: torch.Tensor,
+ g: torch.Tensor,
+ w: torch.Tensor,
+ hs_start: torch.Tensor,
+ valid: torch.Tensor,
+ *,
+ s0: torch.Tensor | None = None,
+ **options: Any, # noqa: ANN401
) -> tuple[torch.Tensor, FitInfo]:
"""Fit the super-resolved footprints Hs >= 0 on their support.
- MATLAB's footprint fit (``objfun_Hs``), to convergence.
+ MATLAB's footprint fit (objfun_Hs), to convergence.
Parameters
----------
@@ -987,6 +1294,13 @@ def fit_footprints(
Fixed variance term (see :class:`FootprintProblem`).
**options
Passed to :func:`projected_newton`.
+
+ Returns
+ -------
+ hs : Tensor of shape (batch, pixels, sources)
+ The fitted footprints.
+ info : FitInfo
+ How the fit ended.
"""
problem = FootprintProblem(z, x, b, g, w, valid, s0)
ub = torch.where(
diff --git a/src/giant_python/extraction/raster/solver_setup.py b/src/giant_python/extraction/raster/solver_setup.py
index a9057307..04d1eea5 100644
--- a/src/giant_python/extraction/raster/solver_setup.py
+++ b/src/giant_python/extraction/raster/solver_setup.py
@@ -1,12 +1,12 @@
"""Parameters, filters and inputs of SiLo's subproblem solver.
-Port of GIAnT-MATLAB's ``setParamsExtractTrial.m`` (the footprint filter,
+Port of GIAnT-MATLAB's setParamsExtractTrial.m (the footprint filter,
the three surround filters, the temporal kernels and the windows) and of
-the inputs that ``extractTrial.m`` hands to its subproblem solver.
+the inputs that extractTrial.m hands to its subproblem solver.
A subproblem is one connected group of sources in one trial of one imaging
path. Its pixels are listed in MATLAB's column-major order of the 2-D
-selected-pixel map (``find(selPix)``), so pixel ``k`` here is row ``k`` of
+selected-pixel map (find(selPix)), so pixel k here is row k of
MATLAB's arrays. MATLAB v7.3 files read with h5py have their dimensions
reversed.
"""
@@ -21,16 +21,22 @@
import h5py
import numpy as np
+import numpy.typing as npt
from scipy import sparse
from .localization import gauss_filter
def gaussian_kernel_1d(sigma: float, size: int) -> np.ndarray:
- """MATLAB ``imgaussfilt``'s 1-D kernel of an odd ``size``, sum 1.
+ """MATLAB imgaussfilt's 1-D kernel of an odd size, sum 1.
- Values below ``eps`` times the largest are set to 0 before the
- normalization, as ``images.internal.createGaussianKernel`` does.
+ Values below eps times the largest are set to 0 before the
+ normalization, as images.internal.createGaussianKernel does.
+
+ Returns
+ -------
+ np.ndarray
+ The kernel, shape (size,), summing to 1.
"""
r = (size - 1) / 2
x = np.arange(-r, r + 1, dtype=np.float64)
@@ -40,17 +46,28 @@ def gaussian_kernel_1d(sigma: float, size: int) -> np.ndarray:
def _impulse_response(sigma: float, size: int) -> np.ndarray:
- """``imgaussfilt`` of a centred impulse with ``FilterSize`` = its size."""
+ """``imgaussfilt`` of a centred impulse with FilterSize = its size.
+
+ Returns
+ -------
+ np.ndarray
+ The 2-D impulse response, shape (size, size).
+ """
g = gaussian_kernel_1d(sigma, size)
return g[:, None] * g[None, :]
def temporal_kernel(tau: float) -> np.ndarray:
- """Causal exponential kernel of ``setParamsExtractTrial``, sum 1.
+ """Return the causal exponential kernel of setParamsExtractTrial, sum 1.
- ``ceil(6 tau)`` zeros, then ``exp(-(0:ceil(6 tau)) / tau)``: convolving
+ ceil(6 tau) zeros, then exp(-(0:ceil(6 tau)) / tau): convolving
events with it ('same') gives the activity, and an event at frame t
peaks at frame t.
+
+ Returns
+ -------
+ np.ndarray
+ The kernel, summing to 1.
"""
n = math.ceil(6 * tau)
k = np.concatenate([np.zeros(n), np.exp(-np.arange(n + 1) / tau)])
@@ -75,8 +92,14 @@ def temporal_kernel(tau: float) -> np.ndarray:
_NOT_NEGATIVE = ("lam", "phi", "baseline_penalty")
-def _check_numbers(params) -> None:
- """Reject numbers that are not finite or have the wrong sign."""
+def _check_numbers(params: SolverParams) -> None:
+ """Reject numbers that are not finite or have the wrong sign.
+
+ Raises
+ ------
+ ValueError
+ If a parameter is not positive and finite, or is negative.
+ """
given = [n for n in _POSITIVE_IF_GIVEN if getattr(params, n) is not None]
for name in list(_POSITIVE) + given:
v = getattr(params, name)
@@ -88,12 +111,14 @@ def _check_numbers(params) -> None:
raise ValueError(f"{name} must not be negative")
-def f0_image_frames(discard, trim_s: float, analyze_hz: float) -> np.ndarray:
- """The frames a trial's F0 image averages: those kept (not discarded
- for motion), less ``trim_s`` seconds at each end, where the baseline
- fit is biased (``round(trim_s * analyze_hz)`` frames, halves rounded
+def f0_image_frames(discard: npt.ArrayLike, trim_s: float, analyze_hz: float) -> np.ndarray:
+ """Return the frames a trial's F0 image averages.
+
+ These are those kept (not discarded
+ for motion), less trim_s seconds at each end, where the baseline
+ fit is biased (round(trim_s * analyze_hz) frames, halves rounded
up as MATLAB does); all kept frames when the trim would leave none
- (GIAnT-MATLAB's ``F0imTrim_s``, ``processAllTrials_Async.m``).
+ (GIAnT-MATLAB's F0imTrim_s, processAllTrials_Async.m).
Parameters
----------
@@ -108,7 +133,7 @@ def f0_image_frames(discard, trim_s: float, analyze_hz: float) -> np.ndarray:
"""
keep = ~np.asarray(discard, dtype=bool).ravel()
# MATLAB's round (half away from zero), as the spine readout's trim
- n_trim = int(math.floor(float(trim_s) * float(analyze_hz) + 0.5))
+ n_trim = math.floor(float(trim_s) * float(analyze_hz) + 0.5)
trimmed = keep.copy()
if n_trim > 0:
trimmed[:n_trim] = False
@@ -120,13 +145,13 @@ def f0_image_frames(discard, trim_s: float, analyze_hz: float) -> np.ndarray:
class SolverParams:
"""Parameters of the subproblem solver.
- The defaults are SILo's for SLAP2, and ``footprint_variance``, which
+ The defaults are SILo's for SLAP2, and footprint_variance, which
MATLAB does not have, is 'fixed'.
Attributes
----------
analyze_hz : float
- Frame rate of the extraction (``params.analyzeHz``).
+ Frame rate of the extraction (params.analyzeHz).
tau_s, tau2_s : float
Decay time constants of the activity channel and of channel 2.
sigma_px : float
@@ -134,20 +159,20 @@ class SolverParams:
sel_radius : int
Radius of the selected region around a source, pixels.
baseline_window_s : float
- Timescale of the baseline (``baselineWindow_Glu_s``).
+ Timescale of the baseline (baselineWindow_Glu_s).
denoise_window_s : float
Timescale over which signals may be smoothed.
min_baseline : float
Lower bound of the baseline, in normalized units.
lam : float
- L1 penalty on the events (``params.lambda``).
+ L1 penalty on the events (params.lambda).
phi : float
- Share of ``lam`` kept in the debias refit.
+ Share of lam kept in the debias refit.
nmf_iter : int
Outer iterations (activity, baseline, footprints).
photon_scale : float or None
Counts per photon that the data were divided by. None for a
- recording whose scale ``extractTrial`` estimates.
+ recording whose scale extractTrial estimates.
debias_variance : {'fixed', 'model'}
Variance term of the debias refit: held at its value at the
refit's start (a weighted least-squares refit) or following the
@@ -169,36 +194,36 @@ class SolverParams:
Curvature penalty of the baseline spline, in knot intervals' worth
of data weight.
tau_full : float or None
- ``tau_s`` in frames; None for ``tau_s * analyze_hz``.
+ tau_s in frames; None for tau_s * analyze_hz.
baseline_mode : str
How the activity channel's baseline is found (the variants of the
baseline test; see :mod:`~giant_python.extraction.raster.solver`):
- 'fit' (MATLAB's: ``splitFreq`` start, then ``fitB``; R0), 'fixed'
+ 'fit' (MATLAB's: splitFreq start, then fitB; R0), 'fixed'
(an external baseline, held; N0), 'gain' (the external baseline
times one gain per pixel; N1), 'gain_shared' (N1 times a time
course shared by the subproblem's pixels; N2) or 'fit_from'
- (``fitB`` of the correction to the external baseline; N3). All but
- 'fit' need ``Subproblem.baseline``. Not a MATLAB option.
+ (fitB of the correction to the external baseline; N3). All but
+ 'fit' need Subproblem.baseline. Not a MATLAB option.
outside_footprint : float
'gain_shared': the shared time course is estimated from the pixels
where every source's footprint is below this share of its largest
value.
valid_kernel : int
Side of the square around each source where the footprint fit may
- put intensity (odd; 5 by default; MATLAB's ``validKernel`` is
+ put intensity (odd; 5 by default; MATLAB's validKernel is
3 x 3, the setting to compare with MATLAB). The footprint
- is ``hfilter`` blurring that support, so its width (RMS per axis)
- lies between ``hfilter``'s sigma (0.9 ``sigma_px``) and
- ``sqrt(sigma**2 + r**2)``, r = (valid_kernel - 1) / 2 (all weight
- on the corners): 1.20 to 1.56 px for 3 and ``sigma_px`` 1.33, up
+ is hfilter blurring that support, so its width (RMS per axis)
+ lies between hfilter's sigma (0.9 sigma_px) and
+ sqrt(sigma**2 + r**2), r = (valid_kernel - 1) / 2 (all weight
+ on the corners): 1.20 to 1.56 px for 3 and sigma_px 1.33, up
to 2.33 px for 5. A Gaussian footprint of sigma 1.8 px is matched
best at 1.56 px with 3 and at 1.74 px with 5.
- ``PlanParams.valid_kernel`` is the same quantity for the plan's
+ PlanParams.valid_kernel is the same quantity for the plan's
zones.
snr_mode : {'diagonal', 'projected'}
- Trace noise SD mode in ``activity_noise``: MATLAB's pixel-independent
- normal matrix (``'diagonal'``), or WLS-projected residuals capturing
- spatial bilinear and short-lag temporal correlations (``'projected'``).
+ Trace noise SD mode in activity_noise: MATLAB's pixel-independent
+ normal matrix ('diagonal'), or WLS-projected residuals capturing
+ spatial bilinear and short-lag temporal correlations ('projected').
"""
analyze_hz: float = 200.0
@@ -224,22 +249,21 @@ class SolverParams:
snr_mode: str = "diagonal"
def __post_init__(self) -> None:
- """Reject values the solver cannot run with."""
+ """Reject values the solver cannot run with.
+
+ Raises
+ ------
+ ValueError
+ If a value is not allowed (see the parameter descriptions).
+ """
for name in ("debias_variance", "footprint_variance"):
if getattr(self, name) not in ("fixed", "model"):
- raise ValueError(
- f"{name} must be 'fixed' or 'model', not "
- f"{getattr(self, name)!r}"
- )
+ raise ValueError(f"{name} must be 'fixed' or 'model', not {getattr(self, name)!r}")
if self.snr_mode not in ("diagonal", "projected"):
- raise ValueError(
- "snr_mode must be 'diagonal' or 'projected', not "
- f"{self.snr_mode!r}"
- )
+ raise ValueError(f"snr_mode must be 'diagonal' or 'projected', not {self.snr_mode!r}")
if self.baseline_mode not in BASELINE_MODES:
raise ValueError(
- f"baseline_mode must be one of {BASELINE_MODES}, not "
- f"{self.baseline_mode!r}"
+ f"baseline_mode must be one of {BASELINE_MODES}, not {self.baseline_mode!r}"
)
if not 0 < self.outside_footprint < 1:
raise ValueError("outside_footprint must lie in (0, 1)")
@@ -247,9 +271,7 @@ def __post_init__(self) -> None:
if isinstance(vk, bool) or not isinstance(vk, (int, np.integer)):
raise ValueError(f"valid_kernel must be an integer, not {vk!r}")
if vk < 1 or vk % 2 == 0:
- raise ValueError(
- f"valid_kernel must be odd and positive, not {vk}"
- )
+ raise ValueError(f"valid_kernel must be odd and positive, not {vk}")
if self.nmf_iter < 1:
raise ValueError(f"nmf_iter must be >= 1, not {self.nmf_iter}")
_check_numbers(self)
@@ -306,16 +328,14 @@ def hfilter(self) -> np.ndarray:
@cached_property
def bfilter(self) -> np.ndarray:
- """The three surround filters, ``(3, size, size)``.
+ """The three surround filters, (3, size, size).
A ring (wide minus narrow Gaussian, negative values cut), and the
ring times a left-right and an up-down gradient.
"""
r = int(self.sel_radius)
size = 4 * r + 1
- ring = np.maximum(
- 0, _impulse_response(r, size) - _impulse_response(r / 2, size)
- )
+ ring = np.maximum(0, _impulse_response(r, size) - _impulse_response(r / 2, size))
mask = np.zeros((size, size))
c = math.ceil(size / 2) - 1
mask[:, c + 1 :] = 1
@@ -350,10 +370,10 @@ class Subproblem:
An external baseline of the activity channel in the data's units
(the F0 network's, mapped by
:func:`~giant_python.extraction.raster.baseline_map.map_baseline`),
- for ``SolverParams.baseline_mode`` other than 'fit'.
+ for SolverParams.baseline_mode other than 'fit'.
f0_frames : ndarray of bool, shape (frames,) or None
Frames over which the solver averages each pixel's final baseline
- (``SubproblemResult.f0_image``; :func:`f0_image_frames`); None: no
+ (SubproblemResult.f0_image; :func:`f0_image_frames`); None: no
F0 image.
"""
@@ -370,7 +390,14 @@ class Subproblem:
_coords: tuple | None = field(default=None, repr=False)
def __post_init__(self) -> None:
- """Check that the arrays fit together."""
+ """Check that the arrays fit together.
+
+ Raises
+ ------
+ ValueError
+ If the arrays do not fit together, an index is negative, or two
+ sources share a position or lie outside the crop.
+ """
self.sel = np.asarray(self.sel, dtype=bool)
self.sources_rc = np.asarray(self.sources_rc, dtype=np.int64)
self.sources_rc = self.sources_rc.reshape(-1, 2)
@@ -379,20 +406,14 @@ def __post_init__(self) -> None:
n_px = int(self.sel.sum())
if self.y.shape[1] != n_px or self.finv.shape != self.y.shape[1:]:
raise ValueError(
- f"sel has {n_px} pixels; y is {self.y.shape} and finv "
- f"{self.finv.shape}"
+ f"sel has {n_px} pixels; y is {self.y.shape} and finv {self.finv.shape}"
)
for name in ("pixels", "sources"):
index = getattr(self, name)
if index is not None and np.asarray(index).min(initial=0) < 0:
raise ValueError(f"{name} holds a negative index")
r, c = self.sources_rc[:, 0], self.sources_rc[:, 1]
- inside = (
- (r >= 0)
- & (r < self.sel.shape[0])
- & (c >= 0)
- & (c < self.sel.shape[1])
- )
+ inside = (r >= 0) & (r < self.sel.shape[0]) & (c >= 0) & (c < self.sel.shape[1])
if not inside.all():
raise ValueError("sources_rc lies outside the crop")
if np.unique(self.sources_rc, axis=0).shape[0] != len(r):
@@ -431,7 +452,15 @@ def coords(self) -> tuple[np.ndarray, np.ndarray]:
def sel_coords(sel: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
- """Rows and columns of ``find(sel)``: column-major order."""
+ """Return the rows and columns of find(sel): column-major order.
+
+ Returns
+ -------
+ rows : np.ndarray
+ Row of each selected pixel.
+ cols : np.ndarray
+ Column of each selected pixel.
+ """
cols, rows = np.nonzero(np.asarray(sel, dtype=bool).T)
return rows, cols
@@ -439,10 +468,15 @@ def sel_coords(sel: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
def conv_operator(sel: np.ndarray, filt: np.ndarray) -> sparse.csr_matrix:
"""``convn(map, filt, 'same')`` on the selected pixels, as a matrix.
- The map is zero outside ``sel``; the result is read at the selected
+ The map is zero outside sel; the result is read at the selected
pixels. Row p of the (pixels x pixels) matrix holds the filter values
that pixel p receives from each selected pixel (MATLAB's
- ``getSurround``).
+ getSurround).
+
+ Returns
+ -------
+ sparse.csr_matrix
+ The (pixels x pixels) operator.
"""
sel = np.asarray(sel, dtype=bool)
rows, cols = sel_coords(sel)
@@ -453,20 +487,13 @@ def conv_operator(sel: np.ndarray, filt: np.ndarray) -> sparse.csr_matrix:
fv = filt[fr, fc]
src_r = rows[:, None] + (filt.shape[0] // 2 - fr)[None, :]
src_c = cols[:, None] + (filt.shape[1] // 2 - fc)[None, :]
- inside = (
- (src_r >= 0)
- & (src_r < sel.shape[0])
- & (src_c >= 0)
- & (src_c < sel.shape[1])
- )
+ inside = (src_r >= 0) & (src_r < sel.shape[0]) & (src_c >= 0) & (src_c < sel.shape[1])
src = np.full(src_r.shape, -1, dtype=np.int64)
src[inside] = order[src_r[inside], src_c[inside]]
use = src >= 0
dst = np.broadcast_to(np.arange(n)[:, None], src.shape)
wts = np.broadcast_to(fv[None, :], src.shape)
- return sparse.csr_matrix(
- (wts[use], (dst[use], src[use])), shape=(n, n), dtype=np.float64
- )
+ return sparse.csr_matrix((wts[use], (dst[use], src[use])), shape=(n, n), dtype=np.float64)
def initial_footprints(
@@ -475,7 +502,7 @@ def initial_footprints(
sigma_px: float,
valid_kernel: int = 3,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- """Starting footprints of ``extractSources``.
+ """Return the starting footprints of extractSources.
Returns
-------
@@ -483,9 +510,9 @@ def initial_footprints(
Super-resolved footprints: a plus-shaped 5 pixels at each source,
sum 1 (over the crop).
h : ndarray of shape (pixels, sources)
- ``hs`` blurred with a Gaussian of ``sigma_px`` (replicate padding).
+ hs blurred with a Gaussian of sigma_px (replicate padding).
valid : ndarray of bool, shape (pixels, sources)
- The ``valid_kernel`` x ``valid_kernel`` pixels around each source
+ The valid_kernel x valid_kernel pixels around each source
(MATLAB: 3 x 3), where the footprint fit may put intensity.
"""
r_v = (int(valid_kernel) - 1) // 2
@@ -511,19 +538,37 @@ def initial_footprints(
def _is_empty(ds: h5py.Dataset) -> bool:
- """Whether a v7.3 dataset holds an empty MATLAB array."""
+ """Whether a v7.3 dataset holds an empty MATLAB array.
+
+ Returns
+ -------
+ bool
+ True if the dataset is marked MATLAB_empty.
+ """
return "MATLAB_empty" in ds.attrs and bool(ds.attrs["MATLAB_empty"])
-def _mat_scalar(g: h5py.Group, name: str, default=None):
- """A numeric scalar field of a MATLAB struct, or ``default``."""
+def _mat_scalar(g: h5py.Group, name: str, default: float | None = None) -> float | None:
+ """Return a numeric scalar field of a MATLAB struct, or default.
+
+ Returns
+ -------
+ float or None
+ The field's first value; default if the field is missing or empty.
+ """
if name not in g or _is_empty(g[name]):
return default
return float(np.asarray(g[name]).ravel()[0])
def _mat_str(g: h5py.Group, name: str, default: str) -> str:
- """A char field of a MATLAB struct, or ``default``."""
+ """Return a char field of a MATLAB struct, or default.
+
+ Returns
+ -------
+ str
+ The field's text; default if the field is missing or empty.
+ """
if name not in g or _is_empty(g[name]):
return default
codes = np.asarray(g[name]).ravel()
@@ -531,33 +576,54 @@ def _mat_str(g: h5py.Group, name: str, default: str) -> str:
def _mat_valid_kernel(g: h5py.Group, default: int) -> int:
- """The side of a saved ``validKernel``: a square of trues, odd side."""
+ """Return the side of a saved validKernel: a square of trues, odd side.
+
+ Returns
+ -------
+ int
+ The side of the square; default if the field is missing or empty.
+
+ Raises
+ ------
+ ValueError
+ If validKernel is not a square of ones.
+ """
if "validKernel" not in g or _is_empty(g["validKernel"]):
return default
k = np.asarray(g["validKernel"])
ones = k == 1 # not astype(bool): 2, -1 or NaN are not ones
if k.ndim != 2 or k.shape[0] != k.shape[1] or not ones.all():
raise ValueError(
- f"validKernel must be a square of ones; it is {k.shape} with "
- f"{int(ones.sum())} ones"
+ f"validKernel must be a square of ones; it is {k.shape} with {int(ones.sum())} ones"
)
return int(k.shape[0])
def params_from_matlab(g: h5py.Group) -> SolverParams:
- """The solver's parameters from a saved MATLAB ``params`` struct.
+ """Return the solver's parameters from a saved MATLAB params struct.
The filters and kernels are derived again from the scalar parameters;
a warning is given if they differ from the saved ones.
- ``footprint_variance`` is not a MATLAB parameter: it is read from a
- ``footprintVariance`` field if the struct has one, and is
+ footprint_variance is not a MATLAB parameter: it is read from a
+ footprintVariance field if the struct has one, and is
:class:`SolverParams`'s default ('fixed') otherwise. For MATLAB's loss
- use ``dataclasses.replace(params, footprint_variance='model')``.
+ use dataclasses.replace(params, footprint_variance='model').
+
+ Returns
+ -------
+ SolverParams
+ The parameters.
"""
d = SolverParams()
- def num(name, default):
- """A scalar field, or the default."""
+ def num(name: str, default: float | None) -> float | None:
+ """Return a scalar field, or the default.
+
+ Returns
+ -------
+ float or None
+ The field's value, or default.
+ """
return _mat_scalar(g, name, default)
p = SolverParams(
@@ -574,9 +640,7 @@ def num(name, default):
nmf_iter=int(num("nmfIter", d.nmf_iter)),
photon_scale=num("photonScale", None),
debias_variance=_mat_str(g, "debiasVariance", "fixed").lower(),
- footprint_variance=_mat_str(
- g, "footprintVariance", d.footprint_variance
- ).lower(),
+ footprint_variance=_mat_str(g, "footprintVariance", d.footprint_variance).lower(),
baseline_knot_factor=num("baselineKnotFactor", 0.5),
baseline_penalty=num("baselinePenalty", 30.0),
tau_full=num("tau_full", None),
@@ -596,9 +660,7 @@ def num(name, default):
if name == "Bfilter":
saved = saved.transpose(2, 0, 1)
saved = saved.reshape(ours.shape) if saved.size == ours.size else saved
- if saved.shape != ours.shape or not np.allclose(
- saved, ours, rtol=1e-9, atol=1e-12
- ):
+ if saved.shape != ours.shape or not np.allclose(saved, ours, rtol=1e-9, atol=1e-12):
warnings.warn(
f"saved params.{name} differs from the one derived from "
"the scalar parameters; the derived one is used",
@@ -607,8 +669,20 @@ def num(name, default):
return p
-def _trial_pixel_index(trial_file: Path, row0, col0, sel) -> np.ndarray:
- """Indices of a crop's pixels in the trial's selected-pixel list."""
+def _trial_pixel_index(trial_file: Path, row0: int, col0: int, sel: np.ndarray) -> np.ndarray:
+ """Return the indices of a crop's pixels in the trial's selected-pixel list.
+
+ Returns
+ -------
+ np.ndarray
+ For each pixel of sel, its index in the trial's selected-pixel
+ list.
+
+ Raises
+ ------
+ ValueError
+ If the trial file does not select every pixel of the subproblem.
+ """
with h5py.File(trial_file, "r") as f:
full = np.asarray(f["selPix"], dtype=bool).T
index = np.full(full.shape, -1, dtype=np.int64)
@@ -625,15 +699,22 @@ def _trial_pixel_index(trial_file: Path, row0, col0, sel) -> np.ndarray:
def load_matlab_subproblem(
- path, dtype=np.float64
+ path: str | Path, dtype: npt.DTypeLike = np.float64
) -> tuple[Subproblem, SolverParams]:
- """One of MATLAB's saved subproblems (``sub_###.mat``) and its params.
+ """One of MATLAB's saved subproblems (sub_###.mat) and its params.
- ``extractTrial`` saves them with ``params.saveSubproblemsDir`` set:
- ``Y_p`` (already divided by ``photonScale``), ``F_inv_p``,
- ``sources_p``, ``selPix_p``, ``params``, and the crop's place in the
+ extractTrial saves them with params.saveSubproblemsDir set:
+ Y_p (already divided by photonScale), F_inv_p,
+ sources_p, selPix_p, params, and the crop's place in the
trial's map. The pixels' indices in the trial's selected-pixel list
- come from ``trial.mat`` beside the file, when it is there.
+ come from trial.mat beside the file, when it is there.
+
+ Returns
+ -------
+ sub : Subproblem
+ The subproblem.
+ params : SolverParams
+ The parameters saved with it.
"""
path = Path(path)
with h5py.File(path, "r") as f:
diff --git a/src/giant_python/extraction/raster/spots.py b/src/giant_python/extraction/raster/spots.py
index f0d78860..4cc39bb5 100644
--- a/src/giant_python/extraction/raster/spots.py
+++ b/src/giant_python/extraction/raster/spots.py
@@ -13,7 +13,7 @@
apart the events' positions form two clusters; closer than about 1.5 px
they cannot be told from a continuum.
-This module labels each spot (sources linked within ``link_px``) from two
+This module labels each spot (sources linked within link_px) from two
tests, without changing the sources or their traces:
1. the correlation of the sources' event trains (:func:`event_train_corr`);
@@ -21,20 +21,20 @@
movie minus its baseline (:func:`localize_events`), and a mixture of
Gaussians fitted to their positions with each event's own error
(:func:`mixture_fit`, an extreme-deconvolution fit with a broad
- component for mislocalized events): the number of components ``K`` by
+ component for mislocalized events): the number of components K by
BIC, the intrinsic spread of the events' cloud (its major SD with the
- errors removed), and the power to find ``K >= 2`` were the spot's
+ errors removed), and the power to find K >= 2 were the spot's
sources separate points (:func:`separation_power`).
Labels (:data:`LABELS`), in this order of precedence:
* 'single': one source;
-* 'close_pair': ``K >= 2``, the events form separate clusters (sources
+* 'close_pair': K >= 2, the events form separate clusters (sources
about 2 px apart or more that fire independently);
* 'merge': one source cut in two, which analyses may merge: the sources'
- event trains correlate at ``split_corr`` or more, or the events form one
- cloud no wider than ``compact_px`` (a point source's);
-* 'continuum': ``K = 1`` although the test had at least ``min_power`` to
+ event trains correlate at split_corr or more, or the events form one
+ cloud no wider than compact_px (a point source's);
+* 'continuum': K = 1 although the test had at least min_power to
see the sources as separate points: one extended object whose events
occur at varying positions, or sources closer than about 1.5 px. SILo's
several sources describe where the events fall and help to fit the movie;
@@ -45,9 +45,11 @@
from __future__ import annotations
import warnings
+from collections.abc import Sequence
from dataclasses import dataclass, field
import numpy as np
+from numpy.typing import ArrayLike
from scipy.optimize import least_squares
LABELS = ("single", "close_pair", "merge", "continuum", "undecided")
@@ -109,13 +111,28 @@ class SpotSettings:
n_sim: int = 20
def to_dict(self) -> dict:
- """The settings as a dict."""
+ """Return the settings as a dict.
+
+ Returns
+ -------
+ dict
+ Each settings field by name.
+ """
return {k: getattr(self, k) for k in self.__dataclass_fields__}
def link_groups(rc: np.ndarray, link_px: float) -> np.ndarray:
- """Spot of each position (zero-based ids, single linkage within
- ``link_px``; ids in order of the groups' first member)."""
+ """Spot of each position.
+
+ Zero-based ids, single linkage within link_px; ids in order of the
+ groups' first member.
+
+ Returns
+ -------
+ np.ndarray
+ The zero-based spot id of each position (int64); a position that is not finite
+ forms a spot of its own.
+ """
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components
from scipy.spatial import cKDTree
@@ -146,8 +163,16 @@ def link_groups(rc: np.ndarray, link_px: float) -> np.ndarray:
def event_train_corr(events: np.ndarray) -> float:
- """Mean pairwise correlation of event trains ``(sources, frames)``, each
- smoothed over 3 frames (NaN as 0); NaN for fewer than two trains."""
+ """Mean pairwise correlation of event trains (sources, frames).
+
+ Each train is smoothed over 3 frames (NaN as 0); NaN for fewer than two
+ trains.
+
+ Returns
+ -------
+ float
+ The mean correlation over all pairs of trains; NaN for fewer than two trains.
+ """
ev = np.nan_to_num(np.asarray(events, dtype=np.float64))
if ev.ndim != 2 or ev.shape[0] < 2:
return float("nan")
@@ -156,29 +181,54 @@ def event_train_corr(events: np.ndarray) -> float:
with np.errstate(invalid="ignore", divide="ignore"):
cc = np.corrcoef(sm)
iu = np.triu_indices(ev.shape[0], 1)
- return (
- float(np.nanmean(cc[iu]))
- if np.isfinite(cc[iu]).any()
- else float("nan")
- )
+ return float(np.nanmean(cc[iu])) if np.isfinite(cc[iu]).any() else float("nan")
+
+def robust_sd(x: np.ndarray, axis: int | None = None) -> np.ndarray | float:
+ """MAD-based SD, NaN left out.
-def robust_sd(x, axis=None):
- """MAD-based SD, NaN left out."""
+ Returns
+ -------
+ np.ndarray or float
+ The robust SD of x, along axis when given.
+ """
med = np.nanmedian(x, axis=axis, keepdims=True)
return _MAD * np.nanmedian(np.abs(x - med), axis=axis)
-def _fit_event(img, rr, cc, sd, r0, c0, sigma, radius):
- """Weighted fit of ``A G(r, c; sigma) + b`` to one event image; returns
- the position, its standard errors and the amplitude, or None."""
+def _fit_event(
+ img: np.ndarray,
+ rr: np.ndarray,
+ cc: np.ndarray,
+ sd: np.ndarray,
+ r0: float,
+ c0: float,
+ sigma: float,
+ radius: float,
+) -> tuple[float, float, float, float, float] | None:
+ """Weighted fit of A G(r, c; sigma) + b to one event image.
+
+ Returns the position, its standard errors and the amplitude, or None.
+
+ Returns
+ -------
+ tuple[float, float, float, float, float] or None
+ The fitted row and column, their standard errors (row, column) and the amplitude;
+ None when the fit is not possible.
+ """
ok = np.isfinite(img) & np.isfinite(sd) & (sd > 0)
if ok.sum() < 8:
return None
y, r, c, w = img[ok], rr[ok], cc[ok], 1.0 / sd[ok]
- def res(p):
- """Weighted residuals at parameters ``p``."""
+ def res(p: np.ndarray) -> np.ndarray:
+ """Weighted residuals at parameters p.
+
+ Returns
+ -------
+ np.ndarray
+ The weighted differences between the model and the image at the valid pixels.
+ """
a, pr, pc, b = p
g = np.exp(-((r - pr) ** 2 + (c - pc) ** 2) / (2 * sigma**2))
return (a * g + b - y) * w
@@ -187,9 +237,7 @@ def res(p):
lo = [0.0, r0 - radius, c0 - radius, -np.inf]
hi = [np.inf, r0 + radius, c0 + radius, np.inf]
try:
- f = least_squares(
- res, [a0, r0, c0, float(np.nanmedian(y))], bounds=(lo, hi)
- )
+ f = least_squares(res, [a0, r0, c0, float(np.nanmedian(y))], bounds=(lo, hi))
except ValueError:
return None
dof = max(int(ok.sum()) - 4, 1)
@@ -232,18 +280,31 @@ def localize_events(
Returns
-------
- dict of arrays ``frame, snr, r, c, se_r, se_c`` (one entry per event).
+ dict of arrays frame, snr, r, c, se_r, se_c (one entry per event).
"""
with warnings.catch_warnings():
# all-NaN pixels and frames (discards, pixels outside the image)
warnings.simplefilter("ignore", RuntimeWarning)
- return _localize(
- x, rr, cc, center, radius, settings, weight_sd, n_frames
- )
+ return _localize(x, rr, cc, center, radius, settings, weight_sd, n_frames)
-def _localize(x, rr, cc, center, radius, settings, weight_sd, n_frames):
- """:func:`localize_events` itself."""
+def _localize(
+ x: np.ndarray,
+ rr: np.ndarray,
+ cc: np.ndarray,
+ center: tuple[float, float],
+ radius: float,
+ settings: SpotSettings,
+ weight_sd: float,
+ n_frames: int,
+) -> dict[str, np.ndarray]:
+ """:func:`localize_events` itself.
+
+ Returns
+ -------
+ dict[str, np.ndarray]
+ As for :func:`localize_events`: frame, snr, r, c, se_r, se_c, one entry per event.
+ """
out = {k: [] for k in ("frame", "snr", "r", "c", "se_r", "se_c")}
x = np.asarray(x, dtype=np.float64)
if x.ndim != 2 or x.shape[0] < n_frames + 2 or x.shape[1] < 9:
@@ -251,9 +312,7 @@ def _localize(x, rr, cc, center, radius, settings, weight_sd, n_frames):
d2 = (rr - center[0]) ** 2 + (cc - center[1]) ** 2
w = np.exp(-d2 / (2 * weight_sd**2))
good = np.isfinite(x)
- trace = (
- np.where(good, x, 0.0) @ w / np.maximum(good.astype(float) @ w, 1e-12)
- )
+ trace = np.where(good, x, 0.0) @ w / np.maximum(good.astype(float) @ w, 1e-12)
trace[good.sum(1) < 0.5 * x.shape[1]] = np.nan
n = len(trace) - n_frames + 1
y = sum(trace[k : k + n] for k in range(n_frames))
@@ -262,12 +321,7 @@ def _localize(x, rr, cc, center, radius, settings, weight_sd, n_frames):
return {k: np.asarray(v) for k, v in out.items()}
z = np.nan_to_num(y / sd, nan=-np.inf)
peak = (
- np.flatnonzero(
- (z[1:-1] > z[:-2])
- & (z[1:-1] >= z[2:])
- & (z[1:-1] > settings.min_snr)
- )
- + 1
+ np.flatnonzero((z[1:-1] > z[:-2]) & (z[1:-1] >= z[2:]) & (z[1:-1] > settings.min_snr)) + 1
)
taken: list = []
for i in peak[np.argsort(-z[peak], kind="stable")]:
@@ -278,9 +332,7 @@ def _localize(x, rr, cc, center, radius, settings, weight_sd, n_frames):
for i in sorted(taken):
with np.errstate(invalid="ignore"):
img = np.nanmean(x[i : i + n_frames], 0)
- fit = _fit_event(
- img, rr, cc, px_sd, center[0], center[1], settings.sigma_px, radius
- )
+ fit = _fit_event(img, rr, cc, px_sd, center[0], center[1], settings.sigma_px, radius)
if fit is None:
continue
r, c, se_r, se_c, _ = fit
@@ -292,8 +344,16 @@ def _localize(x, rr, cc, center, radius, settings, weight_sd, n_frames):
# ------------------------------------------------------------ mixture fit
-def _logn(x, mu, T):
- """``log N(x | mu, T)`` and ``T^-1`` for (n, 2) points, (n, 2, 2) T."""
+def _logn(x: np.ndarray, mu: np.ndarray, T: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """``log N(x | mu, T)`` and T^-1 for (n, 2) points, (n, 2, 2) T.
+
+ Returns
+ -------
+ log_density : np.ndarray
+ The log of the normal density of each point, shape (n,).
+ inv : np.ndarray
+ The inverse of each T, shape (n, 2, 2).
+ """
d = x - mu
det = T[:, 0, 0] * T[:, 1, 1] - T[:, 0, 1] * T[:, 1, 0]
inv = np.empty_like(T)
@@ -303,9 +363,16 @@ def _logn(x, mu, T):
return -0.5 * (m + np.log(det) + 2 * np.log(2 * np.pi)), inv
-def error_cov(se_r, se_c) -> np.ndarray:
- """Each event's position error covariance ``(n, 2, 2)`` from the fit's
- standard errors (:data:`ERROR_K`, :data:`ERROR_FLOOR_PX`)."""
+def error_cov(se_r: ArrayLike, se_c: ArrayLike) -> np.ndarray:
+ """Each event's position error covariance (n, 2, 2).
+
+ From the fit's standard errors (:data:`ERROR_K`, :data:`ERROR_FLOOR_PX`).
+
+ Returns
+ -------
+ np.ndarray
+ Diagonal covariance matrices of the row and column errors, shape (n, 2, 2).
+ """
se = np.c_[np.asarray(se_r, float), np.asarray(se_c, float)]
se = np.where(np.isfinite(se), se, 1.0)
v = (ERROR_K * se) ** 2 + ERROR_FLOOR_PX**2
@@ -339,13 +406,35 @@ class MixtureFit:
outlier: float = 0.0
-def _xd(x, S, K, center, rng, n_init, iters, w=1e-3):
- """Best of ``n_init`` extreme-deconvolution EM runs with K components
- and the fixed outlier component at ``center``."""
+def _xd(
+ x: np.ndarray,
+ S: np.ndarray,
+ K: int,
+ center: ArrayLike,
+ rng: np.random.Generator,
+ n_init: int,
+ iters: int,
+ w: float = 1e-3,
+) -> tuple[float, np.ndarray, np.ndarray, np.ndarray, float]:
+ """Best of n_init extreme-deconvolution EM runs with K components.
+
+ Plus the fixed outlier component at center.
+
+ Returns
+ -------
+ loglik : float
+ The log-likelihood of the best run.
+ weights : np.ndarray
+ The K components' weights.
+ means : np.ndarray
+ The K components' means, shape (K, 2).
+ covs : np.ndarray
+ The K components' intrinsic covariances, shape (K, 2, 2).
+ outlier : float
+ The outlier component's weight.
+ """
n = x.shape[0]
- lo_out, _ = _logn(
- x, np.asarray(center, float), OUTLIER_VAR * np.eye(2)[None] + S
- )
+ lo_out, _ = _logn(x, np.asarray(center, float), OUTLIER_VAR * np.eye(2)[None] + S)
best = None
for _ in range(n_init):
mu = x[rng.choice(n, K, replace=False)].copy()
@@ -378,8 +467,7 @@ def _xd(x, S, K, center, rng, n_init, iters, w=1e-3):
mu[k] = (qk[:, None] * b).sum(0) / sq
db = b - mu[k]
V[k] = (
- np.einsum("n,ni,nj->ij", qk, db, db)
- + np.einsum("n,nij->ij", qk, B)
+ np.einsum("n,ni,nj->ij", qk, db, db) + np.einsum("n,nij->ij", qk, B)
) / sq + w * np.eye(2)
if ll - ll_old < 1e-6 * abs(ll):
break
@@ -390,11 +478,20 @@ def _xd(x, S, K, center, rng, n_init, iters, w=1e-3):
def mixture_fit(
- x, S, center, kmax=3, n_init=6, iters=200, seed=0, bic_margin=0.0
-):
- """Fits with K = 1..kmax (at most one per 8 events); returns the chosen
- fit and all fits: the one-component fit unless a fit with more
- components has a BIC lower by at least ``bic_margin``, then the lowest.
+ x: np.ndarray,
+ S: np.ndarray,
+ center: ArrayLike,
+ kmax: int = 3,
+ n_init: int = 6,
+ iters: int = 200,
+ seed: int = 0,
+ bic_margin: float = 0.0,
+) -> tuple[MixtureFit, list[MixtureFit]]:
+ """Fits with K = 1..kmax (at most one per 8 events).
+
+ Returns the chosen fit and all fits: the one-component fit unless a fit
+ with more components has a BIC lower by at least bic_margin, then the
+ lowest.
Parameters
----------
@@ -406,36 +503,59 @@ def mixture_fit(
Centre of the outlier component (the spot's centre).
bic_margin : float
BIC difference needed to prefer more than one component.
+
+ Returns
+ -------
+ best : MixtureFit
+ The chosen fit.
+ fits : list[MixtureFit]
+ The fits for K = 1 up to the largest K tried.
"""
rng = np.random.default_rng(seed)
n = x.shape[0]
fits = []
for K in range(1, min(kmax, max(n // 8, 1)) + 1):
- ll, al, mu, V, a_out = _xd(
- x, S, K, center, rng, 1 if K == 1 else n_init, iters
- )
+ ll, al, mu, V, a_out = _xd(x, S, K, center, rng, 1 if K == 1 else n_init, iters)
p = 6 * K # means, covariances, weights and the outlier weight
- fits.append(
- MixtureFit(K, ll, -2 * ll + p * np.log(n), al, mu, V, a_out)
- )
+ fits.append(MixtureFit(K, ll, -2 * ll + p * np.log(n), al, mu, V, a_out))
more = [f for f in fits[1:] if f.bic <= fits[0].bic - bic_margin]
return (min(more, key=lambda f: f.bic) if more else fits[0]), fits
-def bic_gain(fits) -> float:
- """BIC of one component minus the lowest BIC with more (NaN without
- such a fit): positive values favour separate clusters."""
+def bic_gain(fits: Sequence[MixtureFit]) -> float:
+ """BIC of one component minus the lowest BIC with more.
+
+ NaN without such a fit; positive values favour separate clusters.
+
+ Returns
+ -------
+ float
+ The BIC difference; NaN when fits has fewer than two fits.
+ """
if len(fits) < 2:
return float("nan")
return float(fits[0].bic - min(f.bic for f in fits[1:]))
def separation_power(
- points, S, outlier, center, n_sim=20, seed=0, bic_margin=0.0
-):
- """P(K >= 2, by BIC with ``bic_margin``) for events drawn equally from
- point sources at ``points`` with the events' own errors ``S`` and
- outlier share."""
+ points: ArrayLike,
+ S: np.ndarray,
+ outlier: float,
+ center: ArrayLike,
+ n_sim: int = 20,
+ seed: int = 0,
+ bic_margin: float = 0.0,
+) -> float:
+ """P(K >= 2, by BIC with bic_margin) for events drawn from point sources.
+
+ Events are drawn equally from point sources at points with the events'
+ own errors S and outlier share.
+
+ Returns
+ -------
+ float
+ The share of simulations in which K >= 2 was chosen; NaN with fewer than two points.
+ """
pts = np.asarray(points, dtype=np.float64).reshape(-1, 2)
if pts.shape[0] < 2:
return float("nan")
@@ -447,9 +567,9 @@ def separation_power(
lab = rng.integers(0, pts.shape[0], n)
x = pts[lab] + np.einsum("nij,nj->ni", L, rng.standard_normal((n, 2)))
out = rng.random(n) < outlier
- x[out] = np.asarray(center) + rng.standard_normal(
- (int(out.sum()), 2)
- ) * np.sqrt(OUTLIER_VAR)
+ x[out] = np.asarray(center) + rng.standard_normal((int(out.sum()), 2)) * np.sqrt(
+ OUTLIER_VAR
+ )
best, _ = mixture_fit(
x,
S,
@@ -500,38 +620,36 @@ class SpotResult:
center: np.ndarray = field(default_factory=lambda: np.full(2, np.nan))
-def event_test(
- events: dict, source_rc: np.ndarray, settings: SpotSettings, seed: int = 0
-) -> dict:
- """The event test of one spot from its events' canvas positions.
-
- ``events`` holds ``r, c, se_r, se_c`` (all trials); the events used are
- those within ``trim_px`` of the circle around the sources' mean that
- holds them all. Returns ``n_events`` and, with at least
- ``min_events`` (and :data:`MIN_FIT_EVENTS`), ``K`` (more than one
- component only with a BIC lower by ``bic_margin``), ``bic_gain``,
- ``cloud_major``, ``cloud_minor`` and (only when ``K == 1``) ``power``.
+def event_test(events: dict, source_rc: np.ndarray, settings: SpotSettings, seed: int = 0) -> dict:
+ """Run the event test of one spot from its events' canvas positions.
+
+ events holds r, c, se_r, se_c (all trials); the events used are
+ those within trim_px of the circle around the sources' mean that
+ holds them all. Returns n_events and, with at least
+ min_events (and :data:`MIN_FIT_EVENTS`), K (more than one
+ component only with a BIC lower by bic_margin), bic_gain,
+ cloud_major, cloud_minor and (only when K == 1) power.
+
+ Returns
+ -------
+ dict
+ n_events and, when enough events remain, K, bic_gain, cloud_major,
+ cloud_minor and (only when K == 1) power.
"""
src = np.asarray(source_rc, dtype=np.float64).reshape(-1, 2)
center = src.mean(0)
rad = float(np.max(np.hypot(*(src - center).T))) + settings.trim_px
x = np.c_[np.asarray(events["r"], float), np.asarray(events["c"], float)]
keep = (
- np.isfinite(x).all(1) & (np.hypot(*(x - center).T) <= rad)
- if x.size
- else np.zeros(0, bool)
+ np.isfinite(x).all(1) & (np.hypot(*(x - center).T) <= rad) if x.size else np.zeros(0, bool)
)
- out = dict(n_events=int(keep.sum()))
+ out = {"n_events": int(keep.sum())}
if keep.sum() < max(settings.min_events, MIN_FIT_EVENTS):
return out
x = x[keep]
- S = error_cov(
- np.asarray(events["se_r"])[keep], np.asarray(events["se_c"])[keep]
- )
- best, fits = mixture_fit(
- x, S, center, seed=seed, bic_margin=settings.bic_margin
- )
- w, v = np.linalg.eigh(fits[0].covs[0])
+ S = error_cov(np.asarray(events["se_r"])[keep], np.asarray(events["se_c"])[keep])
+ best, fits = mixture_fit(x, S, center, seed=seed, bic_margin=settings.bic_margin)
+ w, _v = np.linalg.eigh(fits[0].covs[0])
out.update(
K=int(best.K),
bic_gain=bic_gain(fits),
@@ -551,10 +669,14 @@ def event_test(
return out
-def spot_label(
- n_sources: int, event_corr: float, test: dict, settings: SpotSettings
-) -> str:
- """A spot's label (:data:`LABELS`) from its tests."""
+def spot_label(n_sources: int, event_corr: float, test: dict, settings: SpotSettings) -> str:
+ """Assign a spot's label (:data:`LABELS`) from its tests.
+
+ Returns
+ -------
+ str
+ One of single, close_pair, merge, continuum or undecided.
+ """
if n_sources < 2:
return "single"
k = test.get("K", 0)
diff --git a/src/giant_python/extraction/raster/stage_files.py b/src/giant_python/extraction/raster/stage_files.py
index b498f8a5..4fd39927 100644
--- a/src/giant_python/extraction/raster/stage_files.py
+++ b/src/giant_python/extraction/raster/stage_files.py
@@ -1,10 +1,10 @@
"""Small files that SILo's stages hand to each other.
-* The per-trial localization file (the ``localize`` stage's output, one per
+* The per-trial localization file (the localize stage's output, one per
trial-path): what the plan stage and the per-trial summary need of a
localized trial.
* The seeds file: seeds given to the plan stage instead of its own seeding
- (MATLAB's ``thetaf``, for parity runs).
+ (MATLAB's thetaf, for parity runs).
Layout of a localization file (HDF5, row-major; images in MATLAB's
orientation, zero-based coordinates)::
@@ -23,16 +23,16 @@
across-trial alignment is patchwise
/null_im (draws, rows, cols) float32: the bootstrap null's activity
images, calibrated like act_im, when the run's seeding
- needs them (``seed_acceptance='null'``)
+ needs them (seed_acceptance='null')
-Peaks fitted later (``giant silo`` fits them in the background) go to a
-sidecar ``.peaks.h5`` (``/peaks``), so that the localization file is
+Peaks fitted later (giant silo fits them in the background) go to a
+sidecar .peaks.h5 (/peaks), so that the localization file is
never written while the plan stage reads it.
-Layout of a seeds file: ``/Path/seeds`` ``(n, 4)`` ``[amplitude, row,
-col, sigma]`` per imaging path (numpy orientation), with the root attribute
-``index_base`` (0 or 1) saying whether rows and columns are zero- or
-one-based (MATLAB's ``thetaf`` is one-based).
+Layout of a seeds file: /Path/seeds (n, 4) [amplitude, row,
+col, sigma] per imaging path (numpy orientation), with the root attribute
+index_base (0 or 1) saying whether rows and columns are zero- or
+one-based (MATLAB's thetaf is one-based).
"""
from __future__ import annotations
@@ -40,13 +40,16 @@
import os
from dataclasses import dataclass
from pathlib import Path
-from typing import Optional
+from typing import TYPE_CHECKING
import h5py
import numpy as np
from ... import __version__
+if TYPE_CHECKING:
+ from .plan import TrialImages
+
LOCALIZATION_FORMAT = "giant-silo-localization"
LOCALIZATION_VERSION = 1
@@ -75,14 +78,22 @@ class LocalizationRecord:
act_im: np.ndarray
summary: np.ndarray
discard: np.ndarray
- peaks: Optional[np.ndarray]
+ peaks: np.ndarray | None
attrs: dict
- half_ims: Optional[np.ndarray] = None
- null_im: Optional[np.ndarray] = None
+ half_ims: np.ndarray | None = None
+ null_im: np.ndarray | None = None
+
+ def trial_images(self) -> TrialImages:
+ """Return the plan stage's input.
+
+ A :class:`~giant_python.extraction.raster.plan.TrialImages`.
- def trial_images(self):
- """The plan stage's input
- (:class:`~giant_python.extraction.raster.plan.TrialImages`)."""
+ Returns
+ -------
+ TrialImages
+ The record's mean image, activity image, peaks, discard mask, half images and null
+ images, as the plan stage takes them.
+ """
from .plan import TrialImages
return TrialImages(
@@ -95,8 +106,15 @@ def trial_images(self):
)
-def _value(v):
- """An HDF5 attribute as a Python value."""
+def _value(v: object) -> object:
+ """Convert an HDF5 attribute to a Python value.
+
+ Returns
+ -------
+ object
+ bytes decoded to str, a numpy scalar as its Python value, anything else
+ unchanged.
+ """
if isinstance(v, bytes):
return v.decode()
if isinstance(v, np.generic):
@@ -105,15 +123,15 @@ def _value(v):
def write_localization(
- path,
+ path: str | Path,
mean_im: np.ndarray,
act_im: np.ndarray,
summary: np.ndarray,
discard: np.ndarray,
- peaks: Optional[np.ndarray],
+ peaks: np.ndarray | None,
attrs: dict,
- half_ims: Optional[np.ndarray] = None,
- null_im: Optional[np.ndarray] = None,
+ half_ims: np.ndarray | None = None,
+ null_im: np.ndarray | None = None,
) -> Path:
"""Write a localization file (written whole, then moved into place).
@@ -122,11 +140,11 @@ def write_localization(
path : str or Path
Destination (replaced).
mean_im, act_im, summary, discard, peaks, half_ims, null_im :
- See :class:`LocalizationRecord`; ``peaks`` None if not fitted,
- ``half_ims`` and ``null_im`` None if not kept.
+ See :class:`LocalizationRecord`; peaks None if not fitted,
+ half_ims and null_im None if not kept.
attrs : dict
- Attributes (``settings_hash``, ``movie``, ``path``, ``trial``,
- ``align_hz``, ``num_channels``, ``z_depth``).
+ Attributes (settings_hash, movie, path, trial,
+ align_hz, num_channels, z_depth).
Returns
-------
@@ -143,7 +161,7 @@ def write_localization(
f.attrs[key] = value
f.attrs["peaks_fitted"] = int(peaks is not None)
f.attrs["half_ims"] = int(half_ims is not None)
- opts = dict(compression="gzip", compression_opts=4, shuffle=True)
+ opts = {"compression": "gzip", "compression_opts": 4, "shuffle": True}
f.create_dataset("mean_im", data=np.asarray(mean_im), **opts)
f.create_dataset("act_im", data=np.asarray(act_im), **opts)
f.create_dataset("summary", data=np.asarray(summary), **opts)
@@ -151,9 +169,7 @@ def write_localization(
if peaks is not None:
f["peaks"] = np.asarray(peaks, dtype=np.float64).reshape(-1, 4)
if half_ims is not None:
- f.create_dataset(
- "half_ims", data=np.asarray(half_ims, np.float32), **opts
- )
+ f.create_dataset("half_ims", data=np.asarray(half_ims, np.float32), **opts)
if null_im is not None:
f.attrs["null_im"] = 1
null = np.asarray(null_im, np.float32)
@@ -173,14 +189,26 @@ def write_localization(
return path
-def peaks_file(path) -> Path:
- """The sidecar of a localization file's peaks fitted later."""
+def peaks_file(path: str | Path) -> Path:
+ """Return the sidecar of a localization file's peaks fitted later.
+
+ Returns
+ -------
+ Path
+ Path of the .peaks.h5 file beside the localization file.
+ """
path = Path(path)
return path.with_name(path.stem + ".peaks.h5")
-def _sidecar_peaks(path) -> Optional[np.ndarray]:
- """Peaks from a localization file's sidecar, or None."""
+def _sidecar_peaks(path: str | Path) -> np.ndarray | None:
+ """Peaks from a localization file's sidecar, or None.
+
+ Returns
+ -------
+ np.ndarray or None
+ The sidecar's peaks, or None if there is no sidecar.
+ """
side = peaks_file(path)
if not side.exists():
return None
@@ -188,10 +216,16 @@ def _sidecar_peaks(path) -> Optional[np.ndarray]:
return f["peaks"][()]
-def localization_attrs(path) -> Optional[dict]:
- """A localization file's attributes, or None if it cannot be read.
+def localization_attrs(path: str | Path) -> dict | None:
+ """Read a localization file's attributes, or None if it cannot be read.
+
+ peaks_fitted is 1 when the peaks are in the file or its sidecar.
- ``peaks_fitted`` is 1 when the peaks are in the file or its sidecar.
+ Returns
+ -------
+ dict or None
+ The file's attributes, or None if the file is not a localization file or cannot be
+ read.
"""
try:
with h5py.File(path, "r") as f:
@@ -206,7 +240,7 @@ def localization_attrs(path) -> Optional[dict]:
def read_localization(
- path, peaks: bool = True, half_ims: bool = True
+ path: str | Path, peaks: bool = True, half_ims: bool = True
) -> LocalizationRecord:
"""Read a localization file (and its peaks' sidecar, if there is one).
@@ -221,6 +255,12 @@ def read_localization(
Read the half images, when the file has them (only the patchwise
alignment uses them).
+ Returns
+ -------
+ LocalizationRecord
+ The localized trial-path; its peaks come from the sidecar when the file has none and
+ peaks is True.
+
Raises
------
ValueError
@@ -243,9 +283,7 @@ def read_localization(
discard=f["discard"][()].astype(bool),
peaks=f["peaks"][()] if "peaks" in f else None,
attrs={k: _value(v) for k, v in f.attrs.items()},
- half_ims=(
- f["half_ims"][()] if half_ims and "half_ims" in f else None
- ),
+ half_ims=(f["half_ims"][()] if half_ims and "half_ims" in f else None),
null_im=f["null_im"][()] if "null_im" in f else None,
)
if rec.peaks is None and peaks:
@@ -255,16 +293,17 @@ def read_localization(
return rec
-def add_peaks(path, peaks: np.ndarray) -> Path:
- """Store a trial's peaks fitted later, in the localization file's
- sidecar (written whole, then moved into place).
+def add_peaks(path: str | Path, peaks: np.ndarray) -> Path:
+ """Store a trial's peaks fitted later, in the localization file's sidecar.
+
+ The sidecar is written whole, then moved into place.
Parameters
----------
path : str or Path
The localization file.
peaks : ndarray of shape (n, 4)
- ``[amplitude, row, col, sigma]``, zero-based.
+ [amplitude, row, col, sigma], zero-based.
Returns
-------
@@ -285,7 +324,7 @@ def add_peaks(path, peaks: np.ndarray) -> Path:
return side
-def write_seeds(path, seeds: dict, index_base: int = 0) -> Path:
+def write_seeds(path: str | Path, seeds: dict, index_base: int = 0) -> Path:
"""Write a seeds file.
Parameters
@@ -293,14 +332,19 @@ def write_seeds(path, seeds: dict, index_base: int = 0) -> Path:
path : str or Path
Destination (replaced).
seeds : dict
- One-based path number to an ``(n, 4)`` array ``[amplitude, row,
- col, sigma]``.
+ One-based path number to an (n, 4) array [amplitude, row,
+ col, sigma].
index_base : {0, 1}
Whether rows and columns are zero- or one-based.
Returns
-------
Path
+
+ Raises
+ ------
+ ValueError
+ If `index_base` is not 0 or 1.
"""
if index_base not in (0, 1):
raise ValueError("index_base must be 0 or 1")
@@ -311,7 +355,7 @@ def write_seeds(path, seeds: dict, index_base: int = 0) -> Path:
return Path(path)
-def read_seeds(path, n_paths: int) -> list:
+def read_seeds(path: str | Path, n_paths: int) -> list:
"""Each path's seeds from a seeds file, zero-based.
Parameters
@@ -324,8 +368,13 @@ def read_seeds(path, n_paths: int) -> list:
Returns
-------
list of (ndarray or None)
- Index ``d`` holds path ``d + 1``'s seeds, None where the file has
+ Index d holds path d + 1's seeds, None where the file has
none (that path seeds itself).
+
+ Raises
+ ------
+ ValueError
+ If the file's index_base is not 0 or 1.
"""
out: list = [None] * n_paths
with h5py.File(path, "r") as f:
diff --git a/src/giant_python/extraction/raster/summary.py b/src/giant_python/extraction/raster/summary.py
index 71b0999e..cc96320c 100644
--- a/src/giant_python/extraction/raster/summary.py
+++ b/src/giant_python/extraction/raster/summary.py
@@ -1,12 +1,12 @@
"""SILo's output files in GIAnT-MATLAB's schema.
-Port of what ``SILo.m`` (GIAnT-MATLAB main 5a0673b) does after extraction:
+Port of what SILo.m (GIAnT-MATLAB main 5a0673b) does after extraction:
the kinetics test (:mod:`~giant_python.extraction.raster.kinetics`), the
-experiment summary (``saveExperimentSummaryH5.m``), the per-trial summary
-(``savePerTrialSummaryH5.m``) and the trial table's ``source_extraction``
+experiment summary (saveExperimentSummaryH5.m), the per-trial summary
+(savePerTrialSummaryH5.m) and the trial table's source_extraction
fields. The files have MATLAB's names, sizes, orientation (column-major:
-h5py shows MATLAB's dimensions reversed), classes and ``/row_major = 0``,
-so that MATLAB's ``h5read`` and GIAnT-Python's
+h5py shows MATLAB's dimensions reversed), classes and /row_major = 0,
+so that MATLAB's h5read and GIAnT-Python's
:func:`~giant_python.io.hdf5.load_struct_h5` read them as MATLAB's.
Trials are processed one at a time: a path's trials may be given as
@@ -22,12 +22,15 @@
import math
import os
import warnings
+from collections.abc import Callable, Sequence
+from concurrent.futures import Future
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Callable, Optional, Sequence, Union
+from typing import Union
import h5py
import numpy as np
+import numpy.typing as npt
from ...io.hdf5 import write_matlab_value
from .kinetics import (
@@ -47,35 +50,36 @@
@dataclass
class AlignmentRecord:
- """The registration's per-frame motion of one trial (MATLAB's
- ``aData``), as the experiment summary's ``frame_info`` uses it.
+ """The registration's per-frame motion of one trial (MATLAB's aData).
+
+ It is as the experiment summary's frame_info uses it.
Attributes
----------
ds_frames : ndarray
- One-based line of each registered frame (``DSframes``).
+ One-based line of each registered frame (DSframes).
motion_r, motion_c : ndarray
- Row and column motion of each registered frame (``motionDSr``,
- ``motionDSc``).
+ Row and column motion of each registered frame (motionDSr,
+ motionDSc).
motion_z : ndarray or None
- ``motionDSz``, when the file has it.
+ motionDSz, when the file has it.
online_x, online_y, online_z : ndarray or None
- The online motion correction (``slap2.onlineMotion?shift``).
+ The online motion correction (slap2.onlineMotion?shift).
z_depth : float
- ``slap2.Z_depths`` (NaN when missing).
+ slap2.Z_depths (NaN when missing).
"""
ds_frames: np.ndarray
motion_r: np.ndarray
motion_c: np.ndarray
- motion_z: Optional[np.ndarray] = None
- online_x: Optional[np.ndarray] = None
- online_y: Optional[np.ndarray] = None
- online_z: Optional[np.ndarray] = None
+ motion_z: np.ndarray | None = None
+ online_x: np.ndarray | None = None
+ online_y: np.ndarray | None = None
+ online_z: np.ndarray | None = None
z_depth: float = math.nan
-def read_alignment_record(path) -> AlignmentRecord:
+def read_alignment_record(path: str | Path) -> AlignmentRecord:
"""Read what the summary needs from a ``*_ALIGNMENTDATA.h5``.
Parameters
@@ -88,8 +92,22 @@ def read_alignment_record(path) -> AlignmentRecord:
AlignmentRecord
"""
- def vec(f, name):
- """A dataset as a flat float64 vector, or None."""
+ def vec(f: h5py.File, name: str) -> np.ndarray | None:
+ """Return a dataset as a flat float64 vector, or None.
+
+ Parameters
+ ----------
+ f : h5py.File
+ The open file.
+ name : str
+ The dataset's path in the file.
+
+ Returns
+ -------
+ ndarray or None
+ The dataset's values as a flat float64 vector; None when the file has no such
+ dataset.
+ """
if name not in f:
return None
return np.asarray(f[name][()], dtype=np.float64).ravel()
@@ -119,19 +137,19 @@ class PathResult:
per-trial peaks).
trials : list
One entry per trial of the trial table: None (not extracted), a
- ``TrialOutcome``, or a function returning it.
+ TrialOutcome, or a function returning it.
alignment : list
- One ``AlignmentRecord`` (or None) per trial; needed for the trials
+ One AlignmentRecord (or None) per trial; needed for the trials
that have an outcome.
roi_labels : list of str
The user ROIs' labels.
roi_masks : list of ndarray of bool
Their masks in the consensus frame.
z_depth : float
- The path's ``Z_depths`` (NaN: not written).
+ The path's Z_depths (NaN: not written).
trial_peaks : list or None
- Each trial's own peaks (zero-based ``[amplitude, row, col,
- sigma]`` in its registered frame, or None); None uses the plan's.
+ Each trial's own peaks (zero-based [amplitude, row, col,
+ sigma] in its registered frame, or None); None uses the plan's.
kinetics : KineticsTest or None
Set by :func:`kinetics_test`.
"""
@@ -142,29 +160,66 @@ class PathResult:
roi_labels: list = field(default_factory=list)
roi_masks: list = field(default_factory=list)
z_depth: float = math.nan
- trial_peaks: Optional[list] = None
- kinetics: Optional[KineticsTest] = None
-
- def outcome(self, t: int) -> Optional[TrialOutcome]:
- """Trial ``t``'s outcome (loaded if given as a function)."""
+ trial_peaks: list | None = None
+ kinetics: KineticsTest | None = None
+
+ def outcome(self, t: int) -> TrialOutcome | None:
+ """Return trial t's outcome (loaded if given as a function).
+
+ Parameters
+ ----------
+ t : int
+ Zero-based trial index.
+
+ Returns
+ -------
+ TrialOutcome or None
+ The trial's outcome; None when the trial has none (not extracted, or beyond
+ trials).
+ """
entry = self.trials[t] if t < len(self.trials) else None
return entry() if callable(entry) else entry
- def sizes(self, t: int) -> Optional[TrialShape]:
- """Trial ``t``'s sizes (None without an outcome): from its loader's
- ``sizes()`` when it has one (reading no traces), else from its
- outcome."""
+ def sizes(self, t: int) -> TrialShape | None:
+ """Return trial t's sizes (None without an outcome).
+
+ They come from its loader's sizes() when it has one (reading no traces), else
+ from its outcome.
+
+ Parameters
+ ----------
+ t : int
+ Zero-based trial index.
+
+ Returns
+ -------
+ TrialShape or None
+ The trial's sizes; None without an outcome.
+ """
entry = self.trials[t] if t < len(self.trials) else None
if hasattr(entry, "sizes"):
return entry.sizes()
out = self.outcome(t)
return None if out is None else TrialShape.of(out)
- def activity_ls(self, t: int):
- """Trial ``t``'s activity-channel least-squares traces and SNR,
- ``(ls[0], snr)`` of its outcome (None without activity): from its
- loader's ``activity_ls()`` when it has one (reading only those),
- else from its outcome."""
+ def activity_ls(self, t: int) -> tuple[np.ndarray, np.ndarray] | None:
+ """Return trial t's activity-channel least-squares traces and SNR.
+
+ They are (ls[0], snr) of its outcome (None without activity): from its
+ loader's activity_ls() when it has one (reading only those),
+ else from its outcome.
+
+ Parameters
+ ----------
+ t : int
+ Zero-based trial index.
+
+ Returns
+ -------
+ tuple of (ndarray, ndarray) or None
+ The activity channel's least-squares traces ls[0] and the sources' SNR;
+ None without activity.
+ """
entry = self.trials[t] if t < len(self.trials) else None
if hasattr(entry, "activity_ls"):
return entry.activity_ls()
@@ -181,23 +236,28 @@ def kinetics_test(
min_score: float,
min_snr: float = 0.0,
min_event_rate: float = 0.0,
- judge_below: Optional[float] = None,
+ judge_below: float | None = None,
) -> KineticsTest:
- """Run the kinetics test on a path (``rejectFastSources``).
+ """Run the kinetics test on a path (rejectFastSources).
The activity channel's least-squares traces of every extracted trial
- are scored; the result is stored in ``result.kinetics``. With
- ``min_snr`` or ``min_event_rate`` (events per minute) above 0 the
+ are scored; the result is stored in result.kinetics. With
+ min_snr or min_event_rate (events per minute) above 0 the
evidence test
(:func:`~giant_python.extraction.raster.kinetics.weak_sources`, not in
MATLAB) removes the weak sources too. The event criterion is skipped
when the kinetics test counts no events at all: no trial has traces,
- or the sensor's decay is under 3 frames. With ``judge_below`` the
+ or the sensor's decay is under 3 frames. With judge_below the
evidence test judges only the sources whose seed height in the plan's
combined image
(:func:`~giant_python.extraction.raster.seeding.seed_heights`, robust
SDs) is below it, or unknown; stronger seeds are kept whatever their
evidence.
+
+ Returns
+ -------
+ KineticsTest
+ The kinetics test, also stored in result.kinetics.
"""
traces, snrs = [], []
for t in range(len(result.trials)):
@@ -208,9 +268,7 @@ def kinetics_test(
n = result.plan.n_sources
kin = reject_fast_sources(traces, n, tau_s, analyze_hz, min_score)
if min_snr > 0 or min_event_rate > 0:
- counted = any(np.size(t) for t in traces) and (
- int(np.floor(tau_s * analyze_hz + 0.5)) >= 3
- )
+ counted = any(np.size(t) for t in traces) and (int(np.floor(tau_s * analyze_hz + 0.5)) >= 3)
kin.snr = mean_snr(snrs, n)
kin.event_rate = np.full(n, np.nan)
if counted:
@@ -225,9 +283,7 @@ def kinetics_test(
)
if judge_below is not None:
plan = result.plan
- kin.seed_height = seed_heights(
- plan.act_im, plan.source_rows, plan.source_cols
- )
+ kin.seed_height = seed_heights(plan.act_im, plan.source_rows, plan.source_cols)
kin.weak &= ~(kin.seed_height >= judge_below)
kin.keep = kin.keep & ~kin.weak
result.kinetics = kin
@@ -235,14 +291,27 @@ def kinetics_test(
def _ordered(num_channels: int, activity_channel: int) -> np.ndarray:
- """Zero-based file channels in analysis order (activity first)."""
+ """Return the zero-based file channels in analysis order (activity first).
+
+ Returns
+ -------
+ ndarray
+ The channels' file indices (int64), the activity channel first.
+ """
a = activity_channel - 1
return np.r_[np.arange(a, num_channels), np.arange(a)].astype(np.int64)
-def _nearest(ds: np.ndarray, values: np.ndarray, lines) -> np.ndarray:
- """MATLAB ``interp1(ds, values, lines, 'nearest', 'extrap')`` (ties to
- the right); one registered frame: its value throughout."""
+def _nearest(ds: np.ndarray, values: np.ndarray, lines: npt.ArrayLike) -> np.ndarray:
+ """Return MATLAB interp1(ds, values, lines, 'nearest', 'extrap').
+
+ Ties go to the right; one registered frame: its value throughout.
+
+ Returns
+ -------
+ ndarray
+ The nearest values at each of lines.
+ """
lines = np.asarray(lines, dtype=np.float64)
if ds.size == 1:
return np.full(lines.shape, float(values[0]))
@@ -252,21 +321,29 @@ def _nearest(ds: np.ndarray, values: np.ndarray, lines) -> np.ndarray:
return values[np.where(take_right, right, left)]
-def _pchip(ds: np.ndarray, values: np.ndarray, lines) -> np.ndarray:
- """``interp1(..., 'pchip', 'extrap')`` as the loader upsamples motion."""
+def _pchip(ds: np.ndarray, values: np.ndarray, lines: npt.ArrayLike) -> np.ndarray:
+ """Return interp1(..., 'pchip', 'extrap') as the loader upsamples motion.
+
+ Returns
+ -------
+ ndarray
+ The motion values interpolated at each of lines.
+ """
return upsample_motion(ds, values, np.asarray(lines, dtype=np.float64))
class _Writer:
- """Values written into an HDF5 file as ``saveStructToH5.m`` would."""
+ """Values written into an HDF5 file as saveStructToH5.m would."""
def __init__(self, f: h5py.File) -> None:
"""Wrap an open file."""
self.f = f
- def put(self, path: str, value) -> None:
- """Write a value (MATLAB orientation) at ``/a/b/name``; empty values
- are skipped and groups exist only above datasets, as in MATLAB."""
+ def put(self, path: str, value: object) -> None:
+ """Write a value (MATLAB orientation) at /a/b/name.
+
+ Empty values are skipped and groups exist only above datasets, as in MATLAB.
+ """
parent, name = path.rsplit("/", 1)
if np.ndim(value) and np.size(value) == 0:
return
@@ -274,13 +351,19 @@ def put(self, path: str, value) -> None:
write_matlab_value(grp, name, value)
def create(
- self, path: str, size: tuple, dtype, compressed: bool = False
+ self, path: str, size: tuple, dtype: npt.DTypeLike, compressed: bool = False
) -> h5py.Dataset:
- """An empty dataset of MATLAB size ``size``: contiguous, or with
- ``compressed`` deflated in chunks of one column of images (the
- first HDF5 axis, along which :func:`_profile_blocks` writes and
- readers take blocks), split along the last axis if a column
- exceeds 1 GiB."""
+ """Create an empty dataset of MATLAB size size.
+
+ It is contiguous, or with compressed deflated in chunks of one column of images
+ (the first HDF5 axis, along which :func:`_profile_blocks` writes and readers take
+ blocks), split along the last axis if a column exceeds 1 GiB.
+
+ Returns
+ -------
+ h5py.Dataset
+ The new dataset.
+ """
parent, name = path.rsplit("/", 1)
grp = self.f.require_group(parent) if parent else self.f
shape = tuple(size[::-1])
@@ -290,24 +373,28 @@ def create(
item = np.dtype(dtype).itemsize
while np.prod(chunk) * item > 2**30 and chunk[-1] > 1:
chunk[-1] = (chunk[-1] + 1) // 2
- options = dict(
- chunks=tuple(chunk),
- compression="gzip",
- compression_opts=1,
- shuffle=True,
- )
+ options = {
+ "chunks": tuple(chunk),
+ "compression": "gzip",
+ "compression_opts": 1,
+ "shuffle": True,
+ }
return grp.create_dataset(name, shape=shape, dtype=dtype, **options)
def _profile_blocks(
- ds, images, cols_per_block: int = 64, reversed_order: bool = False
+ ds: h5py.Dataset,
+ images: Callable[[int, int], np.ndarray],
+ cols_per_block: int = 64,
+ reversed_order: bool = False,
) -> None:
- """Write images ``(..., rows, cols)`` as MATLAB's ``(..., rows, cols)``
- array (h5py: reversed) in blocks of columns.
+ """Write images (..., rows, cols) as MATLAB's (..., rows, cols) array.
+
+ The array (h5py: reversed) is written in blocks of columns.
- ``images(c0, c1)`` returns the block's array in MATLAB orientation,
- ``(lead..., rows, c1 - c0)``, or with ``reversed_order`` already in the
- file's (h5py's) orientation, ``(c1 - c0, rows, ...lead reversed)``,
+ images(c0, c1) returns the block's array in MATLAB orientation,
+ (lead..., rows, c1 - c0), or with reversed_order already in the
+ file's (h5py's) orientation, (c1 - c0, rows, ...lead reversed),
which saves transposing a large block. A block that
:func:`_deflated_by_column` allows is written by
:func:`_write_deflated` (the same stored bytes, deflated in threads),
@@ -317,11 +404,7 @@ def _profile_blocks(
for c0 in range(0, n_cols, cols_per_block):
c1 = min(n_cols, c0 + cols_per_block)
block = images(c0, c1)
- block = (
- np.ascontiguousarray(block)
- if reversed_order
- else np.ascontiguousarray(block.T)
- )
+ block = np.ascontiguousarray(block) if reversed_order else np.ascontiguousarray(block.T)
level = _deflated_by_column(ds, block, c1 - c0)
if level is not None:
_write_deflated(ds, c0, block, level)
@@ -340,9 +423,11 @@ def _profile_blocks(
:meth:`_Writer.create` makes), besides the block itself."""
-def _deflated_by_column(ds, block: np.ndarray, n_cols: int):
- """The deflate level when ``block`` (``n_cols`` indices of the first
- axis, the file's orientation, contiguous) can be written into ``ds``
+def _deflated_by_column(ds: h5py.Dataset, block: np.ndarray, n_cols: int) -> int | None:
+ """Return the deflate level when block can be written by :func:`_write_deflated`.
+
+ That is when block (n_cols indices of the first
+ axis, the file's orientation, contiguous) can be written into ds
by :func:`_write_deflated` with the bytes that writing it through
HDF5 stores; None otherwise (it is then written through h5py).
@@ -356,6 +441,12 @@ def _deflated_by_column(ds, block: np.ndarray, n_cols: int):
:func:`_write_deflated` with zeros: the fill value must be zero and
written (fill time not 'never'), which also makes an extended dataset
read zeros there as it would.
+
+ Returns
+ -------
+ int or None
+ The deflate level; None when the block cannot be written by
+ :func:`_write_deflated`.
"""
chunks = ds.chunks
if (
@@ -388,10 +479,18 @@ def _deflated_by_column(ds, block: np.ndarray, n_cols: int):
def _shuffled(data: np.ndarray, chunks: tuple) -> np.ndarray:
- """One chunk as HDF5's shuffle filter passes it on: the first byte of
- every element, then the second, ...; ``data`` is the chunk's part of
+ """Return one chunk as HDF5's shuffle filter passes it on.
+
+ That is the first byte of
+ every element, then the second, ...; data is the chunk's part of
the block (a view, all of the chunk but the end of the last axis
- where the chunk overhangs it, completed here with zeros)."""
+ where the chunk overhangs it, completed here with zeros).
+
+ Returns
+ -------
+ ndarray
+ The shuffled chunk, ``(itemsize, *chunks)`` bytes (uint8).
+ """
size = data.dtype.itemsize
out = np.empty((size,) + tuple(chunks), np.uint8)
n = data.shape[-1]
@@ -404,25 +503,35 @@ def _shuffled(data: np.ndarray, chunks: tuple) -> np.ndarray:
def _deflate_threads(chunk_bytes: int) -> int:
- """Threads for :func:`_write_deflated`, 1 to ``_DEFLATE_THREADS``: as
- many as fit ``_DEFLATE_MEMORY`` at the estimate of about four chunk
+ """Return the threads for :func:`_write_deflated`, 1 to _DEFLATE_THREADS.
+
+ As
+ many as fit _DEFLATE_MEMORY at the estimate of about four chunk
sizes per thread (see there). The estimate is what the scheduling
- aims at, not a bound: the true peak can exceed it by about a chunk."""
+ aims at, not a bound: the true peak can exceed it by about a chunk.
+
+ Returns
+ -------
+ int
+ The number of threads.
+ """
fit = _DEFLATE_MEMORY // (4 * max(int(chunk_bytes), 1))
return int(max(1, min(_DEFLATE_THREADS, fit)))
-def _write_deflated(ds, c0: int, block: np.ndarray, level: int) -> None:
- """Write ``block`` at index ``c0`` of the first axis of a dataset that
+def _write_deflated(ds: h5py.Dataset, c0: int, block: np.ndarray, level: int) -> None:
+ """Write block at index c0 of the first axis of a dataset, deflated in threads.
+
+ The dataset is one that
:func:`_deflated_by_column` allows, its chunks shuffled and deflated
- at ``level`` in threads and written as they are stored
- (``write_direct_chunk``), in order: the file holds the bytes that
- writing the block through HDF5's filters stores (zlib's ``compress``
+ at level in threads and written as they are stored
+ (write_direct_chunk), in order: the file holds the bytes that
+ writing the block through HDF5's filters stores (zlib's compress
at the same level is HDF5's deflate filter), but one core's deflating
no longer sets the time. A chunk that overhangs the last axis is
completed with zeros, as HDF5 completes it with the zero fill value.
- Memory: at most ``2 x threads`` chunks are given to the threads and
+ Memory: at most 2 x threads chunks are given to the threads and
not yet written (the queue is bounded; a slow write holds back the
deflating). The buffers are estimated at about four chunk sizes per
thread: a chunk being deflated holds its shuffled copy and the
@@ -430,7 +539,7 @@ def _write_deflated(ds, c0: int, block: np.ndarray, level: int) -> None:
about the chunk, more while zlib grows it), while earlier results
are still held until they are written (their compressed bytes, at
most about a chunk each). :func:`_deflate_threads` chooses the
- threads so that this estimate fits ``_DEFLATE_MEMORY`` (4 GiB). It is
+ threads so that this estimate fits _DEFLATE_MEMORY (4 GiB). It is
what the scheduling aims at, not a bound: the true peak can exceed it
by about a chunk (a result held while the next output is made),
besides the block itself. Footprint images are mostly zeros and
@@ -445,12 +554,18 @@ def _write_deflated(ds, c0: int, block: np.ndarray, level: int) -> None:
threads = _deflate_threads(int(np.prod(chunks)) * block.dtype.itemsize)
zero = (0,) * (block.ndim - 2)
- def deflate(i, t0):
- """The stored bytes of one chunk."""
+ def deflate(i: int, t0: int) -> bytes:
+ """Return the stored bytes of one chunk.
+
+ Returns
+ -------
+ bytes
+ The chunk, shuffled and deflated.
+ """
data = block[i : i + 1, ..., t0 : t0 + depth]
return zlib.compress(_shuffled(data, chunks), level)
- def store(item):
+ def store(item: tuple[int, int, Future[bytes]]) -> None:
"""Write one deflated chunk."""
i, t0, future = item
ds.id.write_direct_chunk((c0 + i,) + zero + (t0,), future.result())
@@ -474,15 +589,22 @@ def _footprint_images(
c0: int,
c1: int,
) -> np.ndarray:
- """Footprints ``(pixels, sources)`` as images ``(sources, rows, c1 -
- c0)`` of columns ``c0:c1`` (zero elsewhere)."""
+ """Return footprints (pixels, sources) as images (sources, rows, c1 - c0).
+
+ The images are of columns c0:c1 (zero elsewhere).
+
+ Returns
+ -------
+ ndarray
+ The images, float32.
+ """
sel = (cols >= c0) & (cols < c1)
out = np.zeros((footprints.shape[1], shape[0], c1 - c0), np.float32)
out[:, rows[sel], cols[sel] - c0] = footprints[sel].T
return out
-def _write_path( # noqa: C901
+def _write_path(
ew: _Writer,
pw: _Writer,
name: str,
@@ -491,11 +613,15 @@ def _write_path( # noqa: C901
num_channels: int,
activity_channel: int,
) -> None:
- """Write one path's groups of both summaries."""
+ """Write one path's groups of both summaries.
+
+ Raises
+ ------
+ ValueError
+ If a trial's traces and frames differ in number.
+ """
plan = result.plan
- frame_offset = (
- None if plan.frame_offset is None else np.asarray(plan.frame_offset)
- )
+ frame_offset = None if plan.frame_offset is None else np.asarray(plan.frame_offset)
kin = result.kinetics
n_src_all = plan.n_sources
keep = kin.keep if kin is not None else np.ones(n_src_all, bool)
@@ -534,13 +660,11 @@ def _write_path( # noqa: C901
rej = np.flatnonzero(~keep)
ew.put(
f"{name}/sources/rejected/seed_coords",
- np.column_stack(
- [
- np.zeros(rej.size),
- plan.source_rows[rej].astype(np.float64),
- plan.source_cols[rej].astype(np.float64),
- ]
- ),
+ np.column_stack([
+ np.zeros(rej.size),
+ plan.source_rows[rej].astype(np.float64),
+ plan.source_cols[rej].astype(np.float64),
+ ]),
)
ew.put(
f"{name}/sources/rejected/kinetic_score",
@@ -567,9 +691,7 @@ def _write_path( # noqa: C901
)
# frame_info, global and user-ROI traces, and the sources' traces
- fi = {
- k: np.full(total, np.nan) for k in ("oX", "oY", "oZ", "nX", "nY", "nZ")
- }
+ fi = {k: np.full(total, np.nan) for k in ("oX", "oY", "oZ", "nX", "nY", "nZ")}
lines = np.zeros(total)
discard = np.zeros(total, bool)
n_rois = len(result.roi_masks)
@@ -711,9 +833,7 @@ def _write_path( # noqa: C901
f"{name}/visualizations/mean_im",
mean_im.transpose(2, 0, 1)[:, None],
)
- f0_vals = _f0_values(
- f0_trials, n_trials, sel_rows.size, num_channels, ordered
- )
+ f0_vals = _f0_values(f0_trials, n_trials, sel_rows.size, num_channels, ordered)
if f0_vals is not None:
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
@@ -728,13 +848,11 @@ def _write_path( # noqa: C901
if n_kept:
ew.put(
f"{name}/visualizations/act_im_peaks",
- np.column_stack(
- [
- np.zeros(n_kept),
- plan.source_rows[kept].astype(np.float64),
- plan.source_cols[kept].astype(np.float64),
- ]
- ),
+ np.column_stack([
+ np.zeros(n_kept),
+ plan.source_rows[kept].astype(np.float64),
+ plan.source_cols[kept].astype(np.float64),
+ ]),
)
if gf is not None and total:
ew.put(f"{name}/global/F", gf)
@@ -753,14 +871,10 @@ def _write_path( # noqa: C901
if write_sources:
mean_fp = (profile_sum / n_profile).astype(np.float32)
- ds = ew.create(
- f"{name}/sources/spatial/profiles", (n_kept, 1, h, w), np.float32
- )
+ ds = ew.create(f"{name}/sources/spatial/profiles", (n_kept, 1, h, w), np.float32)
_profile_blocks(
ds,
- lambda c0, c1: _footprint_images(
- mean_fp, sel_rows, sel_cols, (h, w), c0, c1
- )[:, None],
+ lambda c0, c1: _footprint_images(mean_fp, sel_rows, sel_cols, (h, w), c0, c1)[:, None],
)
ew.put(
f"{name}/sources/spatial/coords",
@@ -770,9 +884,7 @@ def _write_path( # noqa: C901
ok = ~np.isnan(snr)
mean_snr = np.full(n_kept, np.nan)
some = ok.any(axis=1)
- mean_snr[some] = (
- np.where(ok, snr, 0).sum(1)[some] / ok.sum(1)[some]
- )
+ mean_snr[some] = np.where(ok, snr, 0).sum(1)[some] / ok.sum(1)[some]
ew.put(f"{name}/sources/temporal/SNR", mean_snr.reshape(-1, 1))
if kin is not None and kin.score.size == n_src_all:
ew.put(
@@ -801,9 +913,16 @@ def _write_path( # noqa: C901
def _centroids(
fp: np.ndarray, rows: np.ndarray, cols: np.ndarray, zero_if_empty: bool
) -> np.ndarray:
- """Zero-based ``[0, row, col]`` centroid of each footprint
- ``(pixels, sources)``; 0 (experiment summary) or NaN (per trial) where a
- footprint sums to 0 or less."""
+ """Return zero-based [0, row, col] centroid of each footprint (pixels, sources).
+
+ It is 0 (experiment summary) or NaN (per trial) where a
+ footprint sums to 0 or less.
+
+ Returns
+ -------
+ ndarray
+ The centroids (sources, 3).
+ """
fp = np.where(np.isnan(fp), 0.0, np.asarray(fp, dtype=np.float64))
wsum = fp.sum(axis=0)
out = np.zeros((fp.shape[1], 3))
@@ -815,10 +934,17 @@ def _centroids(
return out
-def _peaks_to_consensus(plan, t: int, peaks: np.ndarray) -> np.ndarray:
- """A trial's own peaks (found in its registered image) in the consensus
- frame, ``(n, 2)`` rows and columns: through the inverse of the trial's
- map, or minus its shift (MATLAB's ``savePerTrialSummaryH5``)."""
+def _peaks_to_consensus(plan: ExtractionPlan, t: int, peaks: np.ndarray) -> np.ndarray:
+ """Return a trial's own peaks (found in its registered image) in the consensus frame.
+
+ They are (n, 2) rows and columns: through the inverse of the trial's
+ map, or minus its shift (MATLAB's savePerTrialSummaryH5).
+
+ Returns
+ -------
+ ndarray
+ The peaks' rows and columns in the consensus frame, (n, 2).
+ """
warp = plan.warp
if t < warp.n_trials and warp.aligned[t] and not warp.is_shift(t):
rows, cols = warp.inverse(t, peaks[:, 1], peaks[:, 2])
@@ -827,13 +953,31 @@ def _peaks_to_consensus(plan, t: int, peaks: np.ndarray) -> np.ndarray:
return peaks[:, 1:3] - shift
-def _f0_values(f0_trials, n_trials, n_pixels, num_channels, ordered):
- """The trials' F0 values at the selected pixels ``(trials, channels,
- pixels)`` (float32, file channel order) from each trial's ``f0_image``
+def _f0_values(
+ f0_trials: dict,
+ n_trials: int,
+ n_pixels: int,
+ num_channels: int,
+ ordered: np.ndarray,
+) -> np.ndarray | None:
+ """Return the trials' F0 values at the selected pixels (trials, channels, pixels).
+
+ They are float32, in file channel order, from each trial's f0_image
(analyzed channels in analysis order x selected pixels); NaN for
channels not analyzed and trials without one. None when no trial has
one. Only the selected pixels are kept, so the images are written in
- blocks (:func:`_write_f0`)."""
+ blocks (:func:`_write_f0`).
+
+ Returns
+ -------
+ ndarray or None
+ The F0 values; None when no trial has an F0 image.
+
+ Raises
+ ------
+ ValueError
+ If a trial's F0 image does not have n_pixels pixels.
+ """
if not f0_trials:
return None
vals = np.full((n_trials, num_channels, n_pixels), np.nan, np.float32)
@@ -841,21 +985,34 @@ def _f0_values(f0_trials, n_trials, n_pixels, num_channels, ordered):
img = np.asarray(img, dtype=np.float64)
if img.shape[1] != n_pixels:
raise ValueError(
- f"trial {t}: an F0 image of {img.shape[1]} pixels; the plan "
- f"selects {n_pixels}"
+ f"trial {t}: an F0 image of {img.shape[1]} pixels; the plan selects {n_pixels}"
)
for c in range(img.shape[0]):
vals[t, int(ordered[c])] = img[c]
return vals
-def _user_roi_f0(masks, f0_vals, pixels, shape, activity_index):
- """Each user ROI's mean F0 over its mask per channel and trial
- ``(rois, channels, trials)`` and the share of its mask pixels with an
- F0 value in the activity channel ``(rois, trials)``
- (GIAnT-MATLAB's ``user_rois/per_trial_F0`` and
- ``per_trial_F0_coverage``); mask pixels that are not selected have no
- value."""
+def _user_roi_f0(
+ masks: Sequence[np.ndarray],
+ f0_vals: np.ndarray,
+ pixels: tuple[np.ndarray, np.ndarray],
+ shape: tuple[int, int],
+ activity_index: int,
+) -> tuple[np.ndarray, np.ndarray]:
+ """Return each user ROI's mean F0 over its mask per channel and trial, and its coverage.
+
+ The mean is (rois, channels, trials) and the coverage is the share of its mask
+ pixels with an
+ F0 value in the activity channel (rois, trials)
+ (GIAnT-MATLAB's user_rois/per_trial_F0 and
+ per_trial_F0_coverage); mask pixels that are not selected have no
+ value.
+
+ Returns
+ -------
+ tuple of (ndarray, ndarray)
+ The mean F0 (rois, channels, trials) and the coverage (rois, trials).
+ """
n_trials, n_ch, _ = f0_vals.shape
rows, cols = pixels
h, w = shape
@@ -871,15 +1028,23 @@ def _user_roi_f0(masks, f0_vals, pixels, shape, activity_index):
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
mean[r] = np.nanmean(vals, axis=2).T
- coverage[r] = (
- np.isfinite(vals[:, activity_index, :]).sum(axis=1) / m.sum()
- )
+ coverage[r] = np.isfinite(vals[:, activity_index, :]).sum(axis=1) / m.sum()
return mean, coverage
-def _write_f0(pw: _Writer, name, masks, f0_vals, pixels, shape, activity):
- """The per-trial summary's F0 images, written in blocks of columns, and
- the user ROIs' F0 (nothing without F0 images)."""
+def _write_f0(
+ pw: _Writer,
+ name: str,
+ masks: Sequence[np.ndarray],
+ f0_vals: np.ndarray | None,
+ pixels: tuple[np.ndarray, np.ndarray],
+ shape: tuple[int, int],
+ activity: int,
+) -> None:
+ """Write the per-trial summary's F0 images, in blocks of columns.
+
+ Also the user ROIs' F0 (nothing without F0 images).
+ """
if f0_vals is None:
return
n_trials, n_ch, _ = f0_vals.shape
@@ -891,8 +1056,14 @@ def _write_f0(pw: _Writer, name, masks, f0_vals, pixels, shape, activity):
np.float32,
)
- def block(c0, c1):
- """Columns ``c0:c1`` of every trial's F0 images."""
+ def block(c0: int, c1: int) -> np.ndarray:
+ """Return columns c0:c1 of every trial's F0 images.
+
+ Returns
+ -------
+ ndarray
+ The block of F0 images in the file's orientation.
+ """
out = np.full((n_trials, n_ch, 1, h, c1 - c0), np.nan, np.float32)
sel = (cols >= c0) & (cols < c1)
out[:, :, 0, rows[sel], cols[sel] - c0] = f0_vals[:, :, sel]
@@ -900,9 +1071,7 @@ def block(c0, c1):
_profile_blocks(ds, block)
if masks:
- roi_f0, coverage = _user_roi_f0(
- masks, f0_vals, pixels, shape, activity
- )
+ roi_f0, coverage = _user_roi_f0(masks, f0_vals, pixels, shape, activity)
pw.put(f"{name}/user_rois/per_trial_F0", roi_f0)
pw.put(f"{name}/user_rois/per_trial_F0_coverage", coverage)
@@ -916,19 +1085,20 @@ def _write_per_trial(
per_trial_fp: dict,
snr: np.ndarray,
write_sources: bool,
- f0_vals: Optional[np.ndarray] = None,
+ f0_vals: np.ndarray | None = None,
activity_index: int = 0,
) -> None:
- """Write one path's group of the per-trial summary (with the trials'
- F0 images and the user ROIs' F0 when ``f0_vals`` is given, see
- :func:`_f0_values`; ``activity_index`` is the zero-based file channel
- of the activity)."""
+ """Write one path's group of the per-trial summary.
+
+ The trials'
+ F0 images and the user ROIs' F0 are written when f0_vals is given, see
+ :func:`_f0_values`; activity_index is the zero-based file channel
+ of the activity.
+ """
plan = result.plan
h, w = plan.shape
act_aligned = np.full((n_trials, h, w), np.nan)
- mean_aligned = np.full(
- (n_trials, h, w, plan.mean_aligned.shape[3]), np.nan
- )
+ mean_aligned = np.full((n_trials, h, w, plan.mean_aligned.shape[3]), np.nan)
m = min(n_trials, plan.act_aligned.shape[0])
act_aligned[:m] = plan.act_aligned[:m]
mean_aligned[:m] = plan.mean_aligned[:m]
@@ -948,9 +1118,7 @@ def _write_per_trial(
(h, w),
activity_index,
)
- peaks = (
- plan.trial_peaks if result.trial_peaks is None else result.trial_peaks
- )
+ peaks = plan.trial_peaks if result.trial_peaks is None else result.trial_peaks
if any(p is not None for p in peaks):
n_peaks = np.zeros(n_trials, dtype=np.int32)
for t in range(min(n_trials, len(peaks))):
@@ -976,20 +1144,28 @@ def _write_per_trial(
coords[:, :, 0] = 0
for t, fp in per_trial_fp.items():
coords[t] = _centroids(fp, rows, cols, zero_if_empty=False)
- _write_trial_profiles(
- pw, name, per_trial_fp, rows, cols, (h, w), n_trials, n_kept
- )
+ _write_trial_profiles(pw, name, per_trial_fp, rows, cols, (h, w), n_trials, n_kept)
pw.put(f"{name}/sources/spatial/per_trial_coords", coords)
pw.put(f"{name}/sources/temporal/per_trial_SNR", snr.T.copy())
def _write_trial_profiles(
- pw: _Writer, name, per_trial_fp, rows, cols, shape, n_trials, n_kept
+ pw: _Writer,
+ name: str,
+ per_trial_fp: dict,
+ rows: np.ndarray,
+ cols: np.ndarray,
+ shape: tuple[int, int],
+ n_trials: int,
+ n_kept: int,
) -> None:
- """The per-trial summary's ``per_trial_profiles``: each trial's
- footprints ``per_trial_fp`` (pixels x kept sources, at the selected
- pixels ``rows``, ``cols``; their NaN are set to 0 here, in place) as
- images of ``shape``, NaN for trials without."""
+ """Write the per-trial summary's per_trial_profiles.
+
+ Each trial's
+ footprints per_trial_fp (pixels x kept sources, at the selected
+ pixels rows, cols; their NaN are set to 0 here, in place) as
+ images of shape, NaN for trials without.
+ """
h, w = shape
# every trial's footprints as images: almost all zeros, and trials x
# sources x rows x cols values (100 GB per path for 200 trials of a
@@ -1011,11 +1187,19 @@ def _write_trial_profiles(
fill = np.full(n_trials, np.nan, np.float32)
fill[list(fp32)] = 0
- def block(c0, c1):
- """Columns ``c0:c1`` of every trial's profiles, in the file's
- orientation ``(cols, rows, 1, sources, trials)``: MATLAB's ``(trials,
- sources, 1, rows, cols)`` reversed, built in place rather than
- transposed (a block of a long session is GBs)."""
+ def block(c0: int, c1: int) -> np.ndarray:
+ """Return columns c0:c1 of every trial's profiles.
+
+ They are in the file's
+ orientation (cols, rows, 1, sources, trials): MATLAB's (trials,
+ sources, 1, rows, cols) reversed, built in place rather than
+ transposed (a block of a long session is GBs).
+
+ Returns
+ -------
+ ndarray
+ The block of profiles in the file's orientation.
+ """
out = np.empty((c1 - c0, h, 1, n_kept, n_trials), np.float32)
out[...] = fill # 0 in the trials with profiles, NaN in the others
sel = (cols >= c0) & (cols < c1)
@@ -1028,17 +1212,17 @@ def block(c0, c1):
def write_summaries(
- experiment_path,
- per_trial_path,
- paths: Sequence[Optional[PathResult]],
+ experiment_path: str | Path,
+ per_trial_path: str | Path,
+ paths: Sequence[PathResult | None],
params: dict,
n_trials: int,
num_channels: int,
activity_channel: int,
) -> None:
- """Write ``experiment_summary.h5`` and ``per_trial_summary.h5``.
+ """Write experiment_summary.h5 and per_trial_summary.h5.
- Ports of ``saveExperimentSummaryH5.m`` and ``savePerTrialSummaryH5.m``;
+ Ports of saveExperimentSummaryH5.m and savePerTrialSummaryH5.m;
both files are written under temporary names and moved into place when
complete. Run :func:`kinetics_test` on each path first (a path without
it keeps every source and gets no kinetics fields).
@@ -1051,7 +1235,7 @@ def write_summaries(
One entry per imaging path of the trial table; None for a path
without valid trials (it is left out, as in MATLAB).
params : dict
- The ``params`` struct (:meth:`SiloParams.to_matlab`).
+ The params struct (:meth:`SiloParams.to_matlab`).
n_trials : int
Trials of the trial table (the trial axis of the per-trial file).
num_channels : int
diff --git a/src/giant_python/extraction/raster/trial.py b/src/giant_python/extraction/raster/trial.py
index 6e3e371e..a9bb6e0f 100644
--- a/src/giant_python/extraction/raster/trial.py
+++ b/src/giant_python/extraction/raster/trial.py
@@ -1,16 +1,16 @@
"""Load and localize one registered SLAP2 trial as SiLo does.
-Port of GIAnT-MATLAB's ``loadAndProcessTrialAsync.m``: the registered 80 Hz
-movie (``*_REGISTERED_DOWNSAMPLED-80Hz.h5`` or ``.tif``, channels
+Port of GIAnT-MATLAB's loadAndProcessTrialAsync.m: the registered 80 Hz
+movie (``*_REGISTERED_DOWNSAMPLED-80Hz.h5`` or .tif, channels
interleaved by frame) and its ``*_ALIGNMENTDATA.h5`` give the activity
-channel, NaN at the frames discarded for motion (from ``recNegErr``) and at
-the first ``discardInitial_s``, the variance factor ``slap2.varFacDS`` and
+channel, NaN at the frames discarded for motion (from recNegErr) and at
+the first discardInitial_s, the variance factor slap2.varFacDS and
the trial's mean image; :func:`localize_trial` then runs
:func:`~giant_python.extraction.raster.localization.localize_sources`, with
-the F0 network's ``_BASELINE-80Hz.h5`` when a baseline folder is
-given (GIAnT-MATLAB branch ``localization-network-baseline``).
+the F0 network's _BASELINE-80Hz.h5 when a baseline folder is
+given (GIAnT-MATLAB branch localization-network-baseline).
-Arrays are ``(frames, rows, cols)`` in MATLAB's row and column orientation
+Arrays are (frames, rows, cols) in MATLAB's row and column orientation
(the TIFF pages are transposed, as MATLAB's reader returns them).
"""
@@ -23,6 +23,7 @@
import h5py
import numpy as np
+import numpy.typing as npt
from .localization import (
RasterLocalization,
@@ -34,8 +35,22 @@
def _medfilt1_zeropad(x: np.ndarray, n: int) -> np.ndarray:
- """MATLAB ``medfilt1(x, n)``: zero padding; for even n the median of
- ``x(k - n/2 : k + n/2 - 1)``."""
+ """Apply MATLAB medfilt1(x, n): zero padding.
+
+ For even n the median of x(k - n/2 : k + n/2 - 1).
+
+ Parameters
+ ----------
+ x : np.ndarray
+ The signal.
+ n : int
+ Window length.
+
+ Returns
+ -------
+ np.ndarray
+ The median filtered signal, as long as x.
+ """
lo = n // 2 if n % 2 == 0 else (n - 1) // 2
hi = n - 1 - lo
xp = np.concatenate([np.zeros(lo), x, np.zeros(hi)])
@@ -43,14 +58,40 @@ def _medfilt1_zeropad(x: np.ndarray, n: int) -> np.ndarray:
def _dilate(b: np.ndarray, w: int) -> np.ndarray:
- """1-D binary dilation with a window of w (outside counts as false)."""
+ """Dilate a 1-D binary array with a window of w (outside counts as false).
+
+ Parameters
+ ----------
+ b : np.ndarray
+ Boolean array.
+ w : int
+ Window length.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean array, True where the window around the sample holds a True.
+ """
h = w // 2
p = np.concatenate([np.zeros(h, bool), b, np.zeros(h, bool)])
return np.lib.stride_tricks.sliding_window_view(p, w).any(1)
def _erode(b: np.ndarray, w: int) -> np.ndarray:
- """1-D binary erosion with a window of w (outside counts as true)."""
+ """Erode a 1-D binary array with a window of w (outside counts as true).
+
+ Parameters
+ ----------
+ b : np.ndarray
+ Boolean array.
+ w : int
+ Window length.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean array, True where the window around the sample holds only True.
+ """
h = w // 2
p = np.concatenate([np.ones(h, bool), b, np.ones(h, bool)])
return np.lib.stride_tricks.sliding_window_view(p, w).all(1)
@@ -62,15 +103,31 @@ def discard_frames(
motion_thresh: float = 2.0,
discard_initial_s: float = 0.0,
) -> np.ndarray:
- """SiLo's motion discards from the alignment's ``recNegErr``.
+ """Return SiLo's motion discards from the alignment's recNegErr.
- ``recNegErr`` minus its 4 s median, normalized by the larger of its 5th
- percentile's magnitude and 0.005, above ``motion_thresh`` (dilated by
+ recNegErr minus its 4 s median, normalized by the larger of its 5th
+ percentile's magnitude and 0.005, above motion_thresh (dilated by
about 50 ms, kept where above half the threshold, then closed); plus the
- first ``discard_initial_s``.
+ first discard_initial_s.
+
+ Parameters
+ ----------
+ rec_neg_err : np.ndarray
+ The alignment's recNegErr.
+ align_hz : float
+ Frame rate of the registered movie.
+ motion_thresh : float
+ Threshold on the normalized recNegErr.
+ discard_initial_s : float
+ Seconds at the start that are discarded.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean array with a value per frame, True at the discarded frames.
"""
rne = np.asarray(rec_neg_err, dtype=np.float64).ravel()
- tmp = rne - _medfilt1_zeropad(rne, int(math.floor(4 * align_hz + 0.5)))
+ tmp = rne - _medfilt1_zeropad(rne, math.floor(4 * align_hz + 0.5))
tmp = -tmp / min(-0.005, matlab_prctile(tmp, 5))
window = 2 * math.ceil(0.025 * align_hz) + 1
over = _dilate(tmp > motion_thresh, window) & (tmp > motion_thresh / 2)
@@ -87,19 +144,19 @@ class RegisteredTrial:
----------
movie : ndarray of shape (frames, rows, cols), or SparseMovie
The activity channel, NaN at discarded frames; a
- :class:`SparseMovie` when loaded with ``lazy``.
+ :class:`SparseMovie` when loaded with lazy.
var_factor : ndarray of the same shape, a PixelReader, or None
- ``slap2.varFacDS`` (None for raster imaging); a
- :class:`PixelReader` when loaded with ``lazy``.
+ slap2.varFacDS (None for raster imaging); a
+ :class:`PixelReader` when loaded with lazy.
mean_im : ndarray of shape (rows, cols, channels)
- Mean over all frames, NaN where more than ``nan_thresh`` is missing.
+ Mean over all frames, NaN where more than nan_thresh is missing.
discard : ndarray of bool
Discarded frames.
align_hz : float
Frame rate of the registered movie.
half_ims : ndarray of shape (2, rows, cols, channels), or None
Mean images of two independent halves of the frames (MATLAB's
- ``halfIMs``, for the patchwise across-trial alignment); only when
+ halfIMs, for the patchwise across-trial alignment); only when
asked for.
"""
@@ -114,7 +171,7 @@ class RegisteredTrial:
def trial_halves(n_frames: int, block_len: int) -> np.ndarray:
"""Split a trial's frames into two halves of equal size.
- Port of ``trialHalves.m``: alternating blocks of ``block_len`` frames
+ Port of trialHalves.m: alternating blocks of block_len frames
(neighbouring frames share noise); the larger half's last frames move to
the other half until the two are equal to a frame.
@@ -132,10 +189,8 @@ def trial_halves(n_frames: int, block_len: int) -> np.ndarray:
return half
-def half_mean_images(
- stack: np.ndarray, half: np.ndarray, nan_thresh: float
-) -> np.ndarray:
- """Mean images of the two halves of a trial (MATLAB's ``halfIMs``).
+def half_mean_images(stack: np.ndarray, half: np.ndarray, nan_thresh: float) -> np.ndarray:
+ """Mean images of the two halves of a trial (MATLAB's halfIMs).
Parameters
----------
@@ -158,10 +213,12 @@ def half_mean_images(
def _channel_means(stack: np.ndarray, nan_thresh: float) -> tuple:
- """The mean image of each channel (NaN ignored) and the pixels missing
- in more than ``nan_thresh`` of the frames, averaged over channels.
+ """Return the mean image of each channel and the pixels missing in many frames.
+
+ The mean image ignores NaN; the pixels are those missing
+ in more than nan_thresh of the frames, averaged over channels.
- ``np.nanmean(stack, axis=0)`` and ``np.isnan(stack).mean(axis=(0, 1))``
+ np.nanmean(stack, axis=0) and np.isnan(stack).mean(axis=(0, 1))
one channel at a time: the same values (the frames are summed in the
same order per pixel; the missing samples are counted exactly), with a
copy of one channel at a time instead of all of them.
@@ -190,31 +247,45 @@ def _channel_means(stack: np.ndarray, nan_thresh: float) -> tuple:
class PixelReader:
- """A ``(frames, rows, cols)`` dataset left in its HDF5 file and read at
- chosen pixels: stored as MATLAB's rows x cols x frames, so
- ``(frames, cols, rows)`` in the file.
+ """A (frames, rows, cols) dataset left in its HDF5 file and read at chosen pixels.
+
+ It is stored as MATLAB's rows x cols x frames, so
+ (frames, cols, rows) in the file.
:func:`~giant_python.extraction.raster.localization.localize_sources`
takes one for the variance factor and for the baseline: it needs them at
the valid pixels only, a few percent of the frame.
"""
- def __init__(self, path, dataset: str, block: int = 256) -> None:
- """Open ``dataset`` of the file for its shape. ``block`` is the
+ def __init__(self, path: str | Path, dataset: str, block: int = 256) -> None:
+ """Open dataset of the file for its shape.
+
+ block is the
number of frames :meth:`at_pixels` reads at a time from a dataset
without spatial tiles; a tiled one is read tile by tile, all frames
- of a tile at once."""
+ of a tile at once.
+ """
self.path, self.dataset, self.block = Path(path), dataset, block
with h5py.File(self.path, "r") as f:
n, cols, rows = f[dataset].shape
self.shape = (n, rows, cols)
def at_pixels(self, vidx: np.ndarray) -> np.ndarray:
- """float32 ``(frames, len(vidx))`` at the row-major pixels ``vidx``.
+ """Read float32 (frames, len(vidx)) at the row-major pixels vidx.
Only the storage chunks that hold a requested pixel are read (the
baseline is stored in tiles of 64 x 64 pixels); of a dataset stored
frame by frame, the rectangle around the requested pixels.
+
+ Parameters
+ ----------
+ vidx : np.ndarray
+ Row-major pixel indices.
+
+ Returns
+ -------
+ np.ndarray
+ float32 (frames, len(vidx)), the values at the pixels.
"""
n, rows, cols = self.shape
vidx = np.asarray(vidx, np.int64)
@@ -229,9 +300,7 @@ def at_pixels(self, vidx: np.ndarray) -> np.ndarray:
d = f[self.dataset] # (frames, cols, rows)
chunks = d.chunks or d.shape
if chunks[1] < cols or chunks[2] < rows:
- tile = (c // chunks[1]) * (
- rows // chunks[2] + 1
- ) + r // chunks[2]
+ tile = (c // chunks[1]) * (rows // chunks[2] + 1) + r // chunks[2]
for t in np.unique(tile):
k = np.flatnonzero(tile == t)
c0 = int(c[k[0]] // chunks[1]) * chunks[1]
@@ -246,8 +315,21 @@ def at_pixels(self, vidx: np.ndarray) -> np.ndarray:
out[a : a + part.shape[0]] = part[:, c - c0, r - r0]
return out
- def __array__(self, dtype=None, copy=None):
- """The whole dataset (for code that wants the array)."""
+ def __array__(self, dtype: npt.DTypeLike | None = None, copy: bool | None = None) -> np.ndarray:
+ """Return the whole dataset (for code that wants the array).
+
+ Parameters
+ ----------
+ dtype : dtype, optional
+ Type of the returned array; float32 if None.
+ copy : bool, optional
+ Accepted for numpy's array protocol; the array is always a new one.
+
+ Returns
+ -------
+ np.ndarray
+ The dataset as (frames, rows, cols).
+ """
with h5py.File(self.path, "r") as f:
a = np.asarray(f[self.dataset][()], np.float32)
a = np.ascontiguousarray(a.transpose(0, 2, 1))
@@ -255,10 +337,11 @@ def __array__(self, dtype=None, copy=None):
class SparseMovie:
- """A trial's activity channel kept at the pixels imaged in each block of
- frames (the scan images a few percent of the registered frame).
+ """A trial's activity channel kept at the pixels imaged in each block of frames.
+
+ The scan images a few percent of the registered frame.
- Stands in for the ``(frames, rows, cols)`` array, NaN where a pixel was
+ Stands in for the (frames, rows, cols) array, NaN where a pixel was
not imaged, at a discarded frame, or in an exclusion zone:
:func:`~giant_python.extraction.raster.localization.localize_sources`
asks it for the valid pixels and for the movie at those.
@@ -266,37 +349,68 @@ class SparseMovie:
Parameters
----------
shape : tuple
- ``(frames, rows, cols)``.
+ (frames, rows, cols).
blocks : list
- ``(first frame, last frame + 1, pixels, values)`` per block of
+ (first frame, last frame + 1, pixels, values) per block of
frames: the row-major pixels with a sample in the block (sorted) and
- their float32 values ``(frames of the block, pixels)``.
+ their float32 values (frames of the block, pixels).
discard : ndarray of bool, shape (frames,)
Discarded frames.
seen : ndarray of int, shape (rows * cols,)
Samples of each pixel in the frames not discarded.
"""
- def __init__(self, shape, blocks, discard, seen, exclude=None) -> None:
- """Keep the blocks. ``exclude`` (optional) is a boolean array
- ``(rows, cols)``, True at the pixels read as NaN; it is used as
- given, :meth:`excluding` converts a mask to boolean."""
+ def __init__(
+ self,
+ shape: tuple[int, ...],
+ blocks: list[tuple[int, int, np.ndarray, np.ndarray]],
+ discard: np.ndarray,
+ seen: np.ndarray,
+ exclude: np.ndarray | None = None,
+ ) -> None:
+ """Keep the blocks.
+
+ exclude (optional) is a boolean array
+ (rows, cols), True at the pixels read as NaN; it is used as
+ given, :meth:`excluding` converts a mask to boolean.
+ """
self.shape = tuple(int(v) for v in shape)
self.blocks, self.discard, self.seen = blocks, discard, seen
self.exclude = exclude
- def excluding(self, mask: np.ndarray) -> "SparseMovie":
- """The movie with the pixels of ``mask`` (rows, cols) set to NaN."""
+ def excluding(self, mask: np.ndarray) -> SparseMovie:
+ """Return the movie with the pixels of mask (rows, cols) set to NaN.
+
+ Parameters
+ ----------
+ mask : np.ndarray
+ Pixels to read as NaN, converted to boolean.
+
+ Returns
+ -------
+ SparseMovie
+ A movie that also excludes the pixels of any mask given before.
+ """
mask = np.asarray(mask, bool)
if self.exclude is not None:
mask = mask | self.exclude
- return SparseMovie(
- self.shape, self.blocks, self.discard, self.seen, mask
- )
+ return SparseMovie(self.shape, self.blocks, self.discard, self.seen, mask)
def valid_pixels(self, nan_thresh: float) -> np.ndarray:
- """Pixels with a sample in at least ``1 - nan_thresh`` of the frames
- (``np.isnan(movie).mean(0) < nan_thresh`` of the array)."""
+ """Return the pixels with a sample in at least 1 - nan_thresh of the frames.
+
+ This is np.isnan(movie).mean(0) < nan_thresh of the array.
+
+ Parameters
+ ----------
+ nan_thresh : float
+ Largest fraction of missing frames of a valid pixel (exclusive).
+
+ Returns
+ -------
+ np.ndarray
+ Boolean array (rows, cols), True at the valid pixels.
+ """
n = self.shape[0]
missing = (n - self.seen).astype(np.float64).reshape(self.shape[1:])
if self.exclude is not None:
@@ -304,8 +418,21 @@ def valid_pixels(self, nan_thresh: float) -> np.ndarray:
return missing / n < nan_thresh
def at_pixels(self, vidx: np.ndarray) -> np.ndarray:
- """float32 ``(frames, len(vidx))`` at the row-major pixels ``vidx``,
- laid out in memory as numpy lays out ``array[:, vidx]``."""
+ """Return float32 (frames, len(vidx)) at the row-major pixels vidx.
+
+ The array is laid out in memory as numpy lays out array[:, vidx].
+
+ Parameters
+ ----------
+ vidx : np.ndarray
+ Row-major pixel indices.
+
+ Returns
+ -------
+ np.ndarray
+ float32 (frames, len(vidx)), NaN where a pixel was not imaged, at a
+ discarded frame, or excluded.
+ """
n, rows, cols = self.shape
vidx = np.asarray(vidx, np.int64)
out = np.empty((len(vidx), n), np.float32).T
@@ -322,9 +449,22 @@ def at_pixels(self, vidx: np.ndarray) -> np.ndarray:
out[:, self.exclude.ravel()[vidx]] = np.nan
return out
- def __array__(self, dtype=None, copy=None):
- """The whole movie as an array."""
- n, rows, cols = self.shape
+ def __array__(self, dtype: npt.DTypeLike | None = None, copy: bool | None = None) -> np.ndarray:
+ """Return the whole movie as an array.
+
+ Parameters
+ ----------
+ dtype : dtype, optional
+ Type of the returned array; float32 if None.
+ copy : bool, optional
+ Accepted for numpy's array protocol; the array is always a new one.
+
+ Returns
+ -------
+ np.ndarray
+ The movie as (frames, rows, cols), NaN where a pixel was not imaged.
+ """
+ _n, rows, cols = self.shape
out = self.at_pixels(np.arange(rows * cols)).reshape(self.shape)
out = np.ascontiguousarray(out)
return out if dtype is None else out.astype(dtype, copy=False)
@@ -336,13 +476,20 @@ class _HalfSums:
block = 256 # frames at a time: a half's frames are not copied at once
def __init__(self, shape: tuple) -> None:
- """Empty sums and counts for images of ``shape``."""
+ """Empty sums and counts for images of shape."""
self.total = np.zeros((2,) + tuple(shape))
self.count = np.zeros((2,) + tuple(shape))
def add(self, chunk: np.ndarray, half: np.ndarray) -> None:
- """Add the frames ``chunk`` (frames, channels, rows, cols) whose
- halves are ``half``."""
+ """Add the frames chunk whose halves are half.
+
+ Parameters
+ ----------
+ chunk : np.ndarray
+ Frames (frames, channels, rows, cols).
+ half : np.ndarray
+ 0 or 1 for each frame of the chunk.
+ """
for h in (0, 1):
x = chunk[half == h]
ok = ~np.isnan(x)
@@ -350,15 +497,26 @@ def add(self, chunk: np.ndarray, half: np.ndarray) -> None:
self.count[h] += ok.sum(axis=0)
def images(self, half: np.ndarray, nan_thresh: float) -> np.ndarray:
- """float32 ``(2, rows, cols, channels)``."""
+ """Return the half images as float32 (2, rows, cols, channels).
+
+ Parameters
+ ----------
+ half : np.ndarray
+ 0 or 1 for each frame.
+ nan_thresh : float
+ A pixel missing in more than this fraction of a half's frames is NaN.
+
+ Returns
+ -------
+ np.ndarray
+ float32 (2, rows, cols, channels), the mean image of each half.
+ """
n_ch, rows, cols = self.total.shape[1:]
out = np.empty((2, rows, cols, n_ch), np.float32)
for h in (0, 1):
with np.errstate(invalid="ignore", divide="ignore"):
m = self.total[h] / self.count[h]
- seen = self.count[h].mean(axis=0) / np.float64(
- (half == h).sum()
- )
+ seen = self.count[h].mean(axis=0) / np.float64((half == h).sum())
missing = 1 - seen > nan_thresh
m[:, missing] = np.nan
out[h] = m.transpose(1, 2, 0)
@@ -370,9 +528,25 @@ def images(self, half: np.ndarray, nan_thresh: float) -> np.ndarray:
def _sum_after(start: np.ndarray, x: np.ndarray, ok: np.ndarray) -> np.ndarray:
- """``start`` plus the frames of ``x`` (frames, pixels) one after the
- other, 0 where not ``ok``: one addition per frame and pixel in frame
- order, as a sum over the frames of the whole movie adds them."""
+ """Return start plus the frames of x (frames, pixels) one after the other.
+
+ Not ok counts as 0: one addition per frame and pixel in frame
+ order, as a sum over the frames of the whole movie adds them.
+
+ Parameters
+ ----------
+ start : np.ndarray
+ The sum so far, per pixel.
+ x : np.ndarray
+ Frames (frames, pixels).
+ ok : np.ndarray
+ Boolean array like x, False where a sample is left out.
+
+ Returns
+ -------
+ np.ndarray
+ The sum per pixel.
+ """
seq = np.empty((x.shape[0] + 1, x.shape[1]), start.dtype)
seq[0] = start
seq[1:] = x
@@ -380,17 +554,17 @@ def _sum_after(start: np.ndarray, x: np.ndarray, ok: np.ndarray) -> np.ndarray:
return np.add.reduce(seq, axis=0)
-def _read_h5_trial( # noqa: C901
- path,
+def _read_h5_trial(
+ path: str | Path,
num_channels: int,
activity_channel: int,
nan_thresh: float,
- half,
+ half: np.ndarray | None,
discard: np.ndarray,
) -> tuple:
- """The activity channel, the channels' mean image and the half images of
- a registered HDF5 movie, read 64 frames at a time and kept at the pixels
- imaged.
+ """Read the activity channel, mean image and half images of a registered HDF5 movie.
+
+ The movie is read 64 frames at a time and kept at the pixels imaged.
The values of reading the whole movie (:func:`_channel_means`,
:func:`half_mean_images`): each pixel's frames are summed in the same
@@ -426,9 +600,7 @@ def _read_h5_trial( # noqa: C901
pad = np.arange(min(n_px, _MIN_PIXELS))
for a in range(0, n_frames, _READ_FRAMES):
b = min(n_frames, a + _READ_FRAMES)
- raw = np.asarray(
- d[a * num_channels : b * num_channels], dtype=np.float32
- )
+ raw = np.asarray(d[a * num_channels : b * num_channels], dtype=np.float32)
got = ~np.isnan(raw).all(axis=0) # (cols, rows): any sample
pc, pr = np.nonzero(got)
pixels = np.unique(pr * cols + pc) # row-major, sorted
@@ -452,14 +624,10 @@ def _read_h5_trial( # noqa: C901
for h in (0, 1):
sel = half[a:b] == h
if sel.any():
- h_run[h, ch, pixels] = _sum_after(
- h_run[h, ch, pixels], x[sel], ok[sel]
- )
+ h_run[h, ch, pixels] = _sum_after(h_run[h, ch, pixels], x[sel], ok[sel])
h_count[h, ch, pixels] += ok[sel].sum(axis=0)
del raw
- if half is not None and (
- b % _HalfSums.block == 0 or b == n_frames
- ):
+ if half is not None and (b % _HalfSums.block == 0 or b == n_frames):
h_total += h_run
h_run[:] = 0
shape2 = (num_channels, rows, cols)
@@ -471,9 +639,7 @@ def _read_h5_trial( # noqa: C901
means[:, :, ch] = np.true_divide(
total[ch], n_frames - gaps[ch], out=total[ch], casting="unsafe"
)
- missing = (
- gaps.sum(axis=0) / np.float64(n_frames * num_channels) > nan_thresh
- )
+ missing = gaps.sum(axis=0) / np.float64(n_frames * num_channels) > nan_thresh
means[missing] = np.nan
halves = None
if half is not None:
@@ -485,8 +651,15 @@ def _read_h5_trial( # noqa: C901
return movie, means, halves
-def _check_channels(num_channels, activity_channel) -> None:
- """Reject channel arguments that would deinterleave or select wrongly."""
+def _check_channels(num_channels: int, activity_channel: int) -> None:
+ """Reject channel arguments that would deinterleave or select wrongly.
+
+ Raises
+ ------
+ ValueError
+ If a channel argument is not an integer, num_channels is below 1, or
+ activity_channel is not one of the channels (1-based).
+ """
for name, v in (
("num_channels", num_channels),
("activity_channel", activity_channel),
@@ -494,9 +667,7 @@ def _check_channels(num_channels, activity_channel) -> None:
if isinstance(v, bool) or not isinstance(v, (int, np.integer)):
raise ValueError(f"{name} must be an integer, not {v!r}")
if num_channels < 1:
- raise ValueError(
- f"num_channels must be at least 1, not {num_channels}"
- )
+ raise ValueError(f"num_channels must be at least 1, not {num_channels}")
if not 1 <= activity_channel <= num_channels:
raise ValueError(
f"activity_channel {activity_channel} is not one of the "
@@ -504,12 +675,22 @@ def _check_channels(num_channels, activity_channel) -> None:
)
-def _read_tiff_pages(path) -> np.ndarray:
- """All pages of a registered TIFF as one ``(pages, rows, cols)`` array.
+def _read_tiff_pages(path: str | Path) -> np.ndarray:
+ """Read all pages of a registered TIFF as one (pages, rows, cols) array.
+
+ MATLAB's Fast_BigTiff_Write gives one series of all pages, but
+ GIAnT-Python's registration writes one page per TiffWriter.write, a
+ series each; tifffile.imread would return only the first.
+
+ Parameters
+ ----------
+ path : str or Path
+ The TIFF file.
- MATLAB's ``Fast_BigTiff_Write`` gives one series of all pages, but
- GIAnT-Python's registration writes one page per ``TiffWriter.write``, a
- series each; ``tifffile.imread`` would return only the first.
+ Returns
+ -------
+ np.ndarray
+ The pages, (pages, rows, cols).
"""
import tifffile
@@ -536,21 +717,21 @@ def load_registered_trial(
half_ims: bool = False,
lazy: bool = False,
) -> RegisteredTrial:
- """Read a registered trial as ``loadAndProcessTrialAsync`` does.
+ """Read a registered trial as loadAndProcessTrialAsync does.
Parameters
----------
moco_dir : str or Path
GIAnT's motion-correction folder.
fn : str
- The registered movie's file name (``..._REGISTERED_DOWNSAMPLED-80Hz``
- ``.tif`` or ``.h5``).
+ The registered movie's file name (..._REGISTERED_DOWNSAMPLED-80Hz
+ .tif or .h5).
num_channels : int
Channels interleaved in the movie.
activity_channel : int
- 1-based channel of the activity signal (``activityChannel``).
+ 1-based channel of the activity signal (activityChannel).
motion_thresh, discard_initial_s, nan_thresh : float
- SiLo's ``motionThresh``, ``discardInitial_s`` and ``nanThresh``.
+ SiLo's motionThresh, discardInitial_s and nanThresh.
half_ims : bool
Also return the mean images of two halves of the frames
(alternating 0.5 s blocks), which the patchwise across-trial
@@ -569,15 +750,15 @@ def load_registered_trial(
Raises
------
ValueError
- If ``num_channels`` is not a positive integer or ``activity_channel``
+ If num_channels is not a positive integer or activity_channel
not one of its 1-based channels (0 would select the last one).
Warns
-----
UserWarning
- If the page count is not a multiple of ``num_channels`` (the pages
+ If the page count is not a multiple of num_channels (the pages
after the last full frame are left out).
- """
+ """ # noqa: DOC502
_check_channels(num_channels, activity_channel)
moco_dir = Path(moco_dir)
path = moco_dir / fn
@@ -589,15 +770,13 @@ def load_registered_trial(
if half_ims:
with h5py.File(moco_dir / f"{stem}_ALIGNMENTDATA.h5", "r") as f:
hz = float(np.asarray(f["alignHz"]).ravel()[0])
- half = trial_halves(n_frames, int(math.floor(0.5 * hz + 0.5)))
+ half = trial_halves(n_frames, math.floor(0.5 * hz + 0.5))
with h5py.File(moco_dir / f"{stem}_ALIGNMENTDATA.h5", "r") as f:
hz = float(np.asarray(f["alignHz"]).ravel()[0])
rne = np.asarray(f["recNegErr"]).ravel()
# the discards come from the alignment alone: known before the movie
# is read, so the valid pixels can be counted while reading
- discard = discard_frames(
- rne[:n_frames], hz, motion_thresh, discard_initial_s
- )
+ discard = discard_frames(rne[:n_frames], hz, motion_thresh, discard_initial_s)
movie, mean_im, halves = _read_h5_trial(
path, num_channels, activity_channel, nan_thresh, half, discard
)
@@ -605,9 +784,7 @@ def load_registered_trial(
if path.suffix == ".h5":
with h5py.File(path, "r") as f:
name = next(iter(f.keys()))
- raw = f[name][
- ()
- ] # (pages, cols, rows): MATLAB's rows x cols x pages
+ raw = f[name][()] # (pages, cols, rows): MATLAB's rows x cols x pages
else:
raw = _read_tiff_pages(path) # (pages, MATLAB col, MATLAB row)
raw = np.asarray(raw, dtype=np.float32).transpose(0, 2, 1)
@@ -630,7 +807,7 @@ def load_registered_trial(
hz = float(np.asarray(f["alignHz"]).ravel()[0])
halves = half_mean_images(
stack,
- trial_halves(n_frames, int(math.floor(0.5 * hz + 0.5))),
+ trial_halves(n_frames, math.floor(0.5 * hz + 0.5)),
nan_thresh,
)
movie = np.ascontiguousarray(stack[:, activity_channel - 1])
@@ -651,9 +828,7 @@ def load_registered_trial(
else:
vf = np.asarray(f["slap2/varFacDS"][()], np.float32)
vf = np.ascontiguousarray(vf.transpose(0, 2, 1))
- discard = discard_frames(
- rne[:n_frames], align_hz, motion_thresh, discard_initial_s
- )
+ discard = discard_frames(rne[:n_frames], align_hz, motion_thresh, discard_initial_s)
if not isinstance(movie, SparseMovie):
movie[discard] = np.nan
return RegisteredTrial(movie, vf, mean_im, discard, align_hz, halves)
@@ -673,23 +848,33 @@ def localize_trial(
) -> tuple[RasterLocalization, RegisteredTrial]:
"""Load one registered trial and localize it (SiLo's per-trial step).
- With ``baseline_dir``, ``_BASELINE-80Hz.h5`` (``slap2-f0
- predict-registered``) replaces the moving median. As in MATLAB, a failed
+ With baseline_dir, _BASELINE-80Hz.h5 (slap2-f0
+ predict-registered) replaces the moving median. As in MATLAB, a failed
localization is retried with the first and last rows and columns set to
NaN (invalid inputs, such as a wrong baseline size, are not retried).
- With ``half_ims`` the trial also carries the mean images of two halves
- of its frames (MATLAB's ``hIM``, for the patchwise alignment). Without
- ``find_peaks`` the per-trial Gaussian peak fit is left out
- (``localization.peaks`` is None); :func:`~giant_python.extraction.
- raster.peaks.get_act_im_peaks` on ``localization.summary`` gives them
+ With half_ims the trial also carries the mean images of two halves
+ of its frames (MATLAB's hIM, for the patchwise alignment). Without
+ find_peaks the per-trial Gaussian peak fit is left out
+ (localization.peaks is None); :func:`~giant_python.extraction.
+ raster.peaks.get_act_im_peaks` on localization.summary gives them
later.
- Against MATLAB's ``loadAndProcessTrialAsync``: ``mIM`` is
- ``trial.mean_im``, ``aIM`` is ``localization.act_im``, ``peaks`` is
- ``localization.peaks`` (``[amplitude, row, col, sigma]``, zero-based),
- ``discardFrames`` is ``trial.discard`` and ``hIM`` is
- ``trial.half_ims``. The alignment data (``aData``) is not returned;
+ Against MATLAB's loadAndProcessTrialAsync: mIM is
+ trial.mean_im, aIM is localization.act_im, peaks is
+ localization.peaks ([amplitude, row, col, sigma], zero-based),
+ discardFrames is trial.discard and hIM is
+ trial.half_ims. The alignment data (aData) is not returned;
extraction reads what it needs from the file.
+
+ Returns
+ -------
+ tuple[RasterLocalization, RegisteredTrial]
+ The localization and the loaded trial.
+
+ Raises
+ ------
+ ValueError
+ If the baseline's /sd is not (frame, col, row).
"""
p = params or RasterLocalizationParams()
trial = load_registered_trial(
@@ -716,10 +901,7 @@ def localize_trial(
with h5py.File(bpath, "r") as f:
has_sd = "sd" in f
if has_sd and f["sd"].ndim != 3:
- raise ValueError(
- f"{bpath}: /sd must be (frame, col, row), not "
- f"{f['sd'].shape}"
- )
+ raise ValueError(f"{bpath}: /sd must be (frame, col, row), not {f['sd'].shape}")
if has_sd:
baseline_sd = PixelReader(bpath, "sd")
check_inputs(trial.movie.shape, p, baseline, trial.var_factor, baseline_sd)
diff --git a/src/giant_python/extraction/raster/trial_data.py b/src/giant_python/extraction/raster/trial_data.py
index a72d3997..535abea5 100644
--- a/src/giant_python/extraction/raster/trial_data.py
+++ b/src/giant_python/extraction/raster/trial_data.py
@@ -1,27 +1,27 @@
"""A SLAP2 trial's raw data at the selected pixels, at the extraction rate.
-Port of the SLAP2 branch of ``loadTrial`` in GIAnT-MATLAB's
-``processAllTrials_Async.m`` and of its helpers ``slap2FramesAt``,
-``rawFramesAt``, ``compensationPad``, ``onlineCompensation`` and
-``blockCompensation``, with the ``'Pixels'`` mode of ``slap2FrameSums``:
+Port of the SLAP2 branch of loadTrial in GIAnT-MATLAB's
+processAllTrials_Async.m and of its helpers slap2FramesAt,
+rawFramesAt, compensationPad, onlineCompensation and
+blockCompensation, with the 'Pixels' mode of slap2FrameSums:
-* frames are formed from the raw file at ``analyze_hz`` (200 Hz), with
+* frames are formed from the raw file at analyze_hz (200 Hz), with
getImages' exponential kernel but without invalid samples, only at the
raster pixels that the wanted points' bilinear neighbours fall on;
* each wanted point of the consensus frame is read at its position in the
trial's registered frame (the across-trial warp) plus the within-trial
motion, which is the registration's motion interpolated to the frames;
-* with registration's ``compensateOnline``, frames are formed with the
+* with registration's compensateOnline, frames are formed with the
online motion correction undone, block by block;
* besides the data and its variance multiplier at the selected pixels, the
loader returns the global trace (labeled pixels) and the user-ROI traces
- (plain and denoised by a rank-3 SVD, ``nansvd.m``).
+ (plain and denoised by a rank-3 SVD, nansvd.m).
-Conventions: images are ``(rows, cols)`` in MATLAB's orientation; lines are
+Conventions: images are (rows, cols) in MATLAB's orientation; lines are
one-based, as in MATLAB and :mod:`giant_python.registration`; pixel and
frame indices are zero-based. Selected pixels are listed in MATLAB's
-column-major order of the map (``find(selPix)``). The warp takes and returns
-zero-based ``(row, col)`` coordinates.
+column-major order of the map (find(selPix)). The warp takes and returns
+zero-based (row, col) coordinates.
"""
from __future__ import annotations
@@ -31,13 +31,14 @@
import threading
import time
import warnings
+from collections.abc import Callable, Iterable, Iterator, Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field, replace
from pathlib import Path
-from typing import Callable, Optional, Sequence
import h5py
import numpy as np
+import numpy.typing as npt
import torch
from scipy.interpolate import PchipInterpolator
@@ -49,7 +50,7 @@
from .localization import matlab_prctile
SVD_COMPONENTS = 3
-"""Rank of the user-ROI denoising (``nansvd(D, 3, 10, nanThresh)``)."""
+"""Rank of the user-ROI denoising (nansvd(D, 3, 10, nanThresh))."""
SVD_ITERATIONS = 10
"""Most gap-filling iterations of the user-ROI denoising."""
@@ -62,25 +63,25 @@ class TrialLoadParams:
Attributes
----------
analyze_hz : float
- Frame rate of the extraction (``analyzeHz``).
+ Frame rate of the extraction (analyzeHz).
activity_channel : int
- One-based channel of the activity signal (``activityChannel``); it
+ One-based channel of the activity signal (activityChannel); it
becomes channel 0 of the data.
photon_scale : float
- Raw counts per unit of the data (``photonScale``; 25 for SLAP2).
+ Raw counts per unit of the data (photonScale; 25 for SLAP2).
baseline_window_s : float
Window of the moving mean that fills missing samples
- (``baselineWindow_Glu_s``; ``baselineWindow_samps`` frames).
+ (baselineWindow_Glu_s; baselineWindow_samps frames).
nan_thresh : float
Largest share of missing samples of a pixel or frame used in the
- user-ROI denoising (``nanThresh``).
+ user-ROI denoising (nanThresh).
block_frames : int
- Frames formed around one online offset (MATLAB's ``blocksize``).
+ Frames formed around one online offset (MATLAB's blocksize).
variance_mode : {'freshness', 'kernel'}
- Per-sample variance multiplier ``finv``: MATLAB's reciprocal summed
- weights ``1 / sum(c * F1)`` (``'freshness'``), or the
+ Per-sample variance multiplier finv: MATLAB's reciprocal summed
+ weights 1 / sum(c * F1) ('freshness'), or the
pooling-conserved exponential-kernel variance factor
- ``kappa_dt * sum(c * F2) / sum(c * F1)^2`` (``'kernel'``).
+ kappa_dt * sum(c * F2) / sum(c * F1)^2 ('kernel').
"""
analyze_hz: float = 200.0
@@ -92,11 +93,16 @@ class TrialLoadParams:
variance_mode: str = "freshness"
def __post_init__(self) -> None:
- """Validate ``variance_mode``."""
+ """Validate variance_mode.
+
+ Raises
+ ------
+ ValueError
+ If variance_mode is not 'freshness' or 'kernel'.
+ """
if self.variance_mode not in ("freshness", "kernel"):
raise ValueError(
- "variance_mode must be 'freshness' or 'kernel', not "
- f"{self.variance_mode!r}"
+ f"variance_mode must be 'freshness' or 'kernel', not {self.variance_mode!r}"
)
@property
@@ -107,10 +113,21 @@ def baseline_window_samps(self) -> float:
def ordered_channels(self, num_channels: int) -> list:
"""Zero-based file channels in analysis order (activity first).
+ Parameters
+ ----------
+ num_channels : int
+ The recording's number of channels.
+
+ Returns
+ -------
+ list of int
+ The zero-based channels: the activity channel, those after it,
+ then those before it.
+
Raises
------
ValueError
- If ``activity_channel`` is not an integer, or not one of the
+ If activity_channel is not an integer, or not one of the
recording's 1-based channels.
"""
a = self.activity_channel
@@ -119,8 +136,7 @@ def ordered_channels(self, num_channels: int) -> list:
a = int(a)
if not 1 <= a <= num_channels:
raise ValueError(
- f"activity_channel {a} is not one of the {num_channels} "
- "channels (1-based)"
+ f"activity_channel {a} is not one of the {num_channels} channels (1-based)"
)
return list(range(a - 1, num_channels)) + list(range(a - 1))
@@ -129,17 +145,29 @@ def ordered_channels(self, num_channels: int) -> list:
class RigidShift:
"""An across-trial shift: the default warp of a trial.
- Maps the consensus position ``(row, col)`` to ``(row + row_shift,
- col + col_shift)`` of the trial's registered frame (SILo's
- ``motOutput``). The loader adds a shift to the frames' motion, as MATLAB
+ Maps the consensus position (row, col) to (row + row_shift,
+ col + col_shift) of the trial's registered frame (SILo's
+ motOutput). The loader adds a shift to the frames' motion, as MATLAB
does; any other callable is evaluated at every wanted pixel.
"""
row: float = 0.0
col: float = 0.0
- def __call__(self, rows, cols):
- """Trial-frame position of consensus points."""
+ def __call__(self, rows: npt.ArrayLike, cols: npt.ArrayLike) -> tuple[np.ndarray, np.ndarray]:
+ """Return the trial-frame position of consensus points.
+
+ Parameters
+ ----------
+ rows, cols : array-like
+ Zero-based consensus rows and columns of the points.
+
+ Returns
+ -------
+ tuple of np.ndarray
+ The points' zero-based rows and columns in the trial's
+ registered frame.
+ """
return np.asarray(rows) + self.row, np.asarray(cols) + self.col
@@ -152,24 +180,30 @@ class OnlineCompensation:
offsets : LineOffsets
Online offsets of the recording's lines.
ref_offset : ndarray
- Header offset ``[x, y]`` whose lines stay in place.
+ Header offset [x, y] whose lines stay in place.
mapping : ndarray
- ``2 x 2`` matrix taking an offset difference ``[dx; dy]`` to the
- ``[row; col]`` displacement of the samples.
+ 2 x 2 matrix taking an offset difference [dx; dy] to the
+ [row; col] displacement of the samples.
"""
offsets: LineOffsets
ref_offset: np.ndarray
mapping: np.ndarray
- def displacement(self, lines):
- """Integer ``(rows, cols)`` displacement of the samples of lines.
+ def displacement(self, lines: npt.ArrayLike) -> tuple[np.ndarray, np.ndarray]:
+ """Integer (rows, cols) displacement of the samples of lines.
Parameters
----------
lines : ndarray of int
One-based lines (any shape; clipped to the recording).
+ Returns
+ -------
+ tuple of np.ndarray
+ The row and column displacement of each line's samples, in
+ pixels, with the shape of lines.
+
Raises
------
ValueError
@@ -193,7 +227,7 @@ class TrialAlignment:
Attributes
----------
ds_frames : ndarray
- One-based line of each registered frame (``DSframes``).
+ One-based line of each registered frame (DSframes).
motion_r, motion_c : ndarray
Row and column motion of each registered frame.
align_hz : float
@@ -201,13 +235,13 @@ class TrialAlignment:
view_r, view_c : ndarray
Row and column of the trimmed raster image (one-based, before
motion) that each row and column of the registered frame reads
- (``slap2.viewR(:, 1)``, ``slap2.viewC(1, :)``).
+ (slap2.viewR(:, 1), slap2.viewC(1, :)).
trim_rows, trim_cols : ndarray of int
One-based DMD rows and columns of the trimmed raster image.
compensation : dict or None
- The ``slap2/onlineCompensation`` record when registration undid the
- online motion correction (``refOffset``, ``frameRefX``,
- ``frameRefY``, ``mapping``, ``yLead``).
+ The slap2/onlineCompensation record when registration undid the
+ online motion correction (refOffset, frameRefX,
+ frameRefY, mapping, yLead).
"""
ds_frames: np.ndarray
@@ -218,7 +252,7 @@ class TrialAlignment:
view_c: np.ndarray
trim_rows: np.ndarray
trim_cols: np.ndarray
- compensation: Optional[dict] = None
+ compensation: dict | None = None
@property
def view_shape(self) -> tuple:
@@ -227,13 +261,40 @@ def view_shape(self) -> tuple:
def _matlab_2d(ds: h5py.Dataset, row_major: bool) -> np.ndarray:
- """A 2-D dataset in MATLAB's orientation."""
+ """Return a 2-D dataset in MATLAB's orientation.
+
+ Parameters
+ ----------
+ ds : h5py.Dataset
+ The dataset.
+ row_major : bool
+ Whether the file stores arrays in row-major order (so no transpose).
+
+ Returns
+ -------
+ np.ndarray
+ The dataset as float64, transposed unless row_major.
+ """
a = np.asarray(ds[()], dtype=np.float64)
return a if row_major else a.T
-def _compensation_record(grp, row_major: bool) -> Optional[dict]:
- """The enabled ``onlineCompensation`` record of an alignment file."""
+def _compensation_record(grp: h5py.Group, row_major: bool) -> dict | None:
+ """Return the enabled onlineCompensation record of an alignment file.
+
+ Parameters
+ ----------
+ grp : h5py.Group
+ The file's slap2 group.
+ row_major : bool
+ Whether the file stores arrays in row-major order.
+
+ Returns
+ -------
+ dict or None
+ refOffset, frameRefX, frameRefY, mapping and
+ yLead; None if the record is missing or not enabled.
+ """
if "onlineCompensation" not in grp:
return None
oc = grp["onlineCompensation"]
@@ -248,13 +309,13 @@ def _compensation_record(grp, row_major: bool) -> Optional[dict]:
}
-def read_alignment(path) -> TrialAlignment:
+def read_alignment(path: str | Path) -> TrialAlignment:
"""Read the loader's part of a trial's alignment file.
Parameters
----------
path : str or Path
- ``_ALIGNMENTDATA.h5`` of MultiRoiRegistration (MATLAB or
+ _ALIGNMENTDATA.h5 of MultiRoiRegistration (MATLAB or
:mod:`giant_python.registration`). The per-frame variance factor is
not read.
@@ -281,12 +342,12 @@ def read_alignment(path) -> TrialAlignment:
def online_compensation(
alignment: TrialAlignment,
layout: RasterLayout,
- line_range,
+ line_range: tuple[float, float],
kernel_lines: int,
-):
- """The compensation registration used and the motion to interpolate.
+) -> tuple[OnlineCompensation | None, np.ndarray, np.ndarray]:
+ """Return the compensation registration used and the motion to interpolate.
- Port of ``onlineCompensation``. If registration undid the online motion
+ Port of onlineCompensation. If registration undid the online motion
correction, each registered frame's motion is relative to the DMD
coordinates of its own offset; adding that offset (mapped to rows and
columns, relative to the reference) gives the continuous tissue motion,
@@ -318,9 +379,7 @@ def online_compensation(
return None, motion_r, motion_c
margin = 2 * max(3 * kernel_lines, layout.lines_per_cycle) + 8
lead = tuple(int(v) for v in oc["yLead"])
- offsets = line_offsets(
- layout, (line_range[0] - margin, line_range[1] + margin), lead
- )
+ offsets = line_offsets(layout, (line_range[0] - margin, line_range[1] + margin), lead)
mapping = np.asarray(oc["mapping"], np.float64)
ref = np.asarray(oc["refOffset"], np.float64)
d = mapping @ (np.stack([oc["frameRefX"], oc["frameRefY"]]) - ref[:, None])
@@ -328,11 +387,13 @@ def online_compensation(
return comp, motion_r + d[0], motion_c + d[1]
-def block_compensation(comp: Optional[OnlineCompensation], lines):
+def block_compensation(
+ comp: OnlineCompensation | None, lines: npt.ArrayLike
+) -> tuple[OnlineCompensation | None, tuple[float, float]]:
"""Compensation of a block of frames, around the block's median offset.
- Port of ``blockCompensation``: forming a block around its own typical
- offset keeps the motion to apply, ``motion - shift``, as small as
+ Port of blockCompensation: forming a block around its own typical
+ offset keeps the motion to apply, motion - shift, as small as
without compensation.
Parameters
@@ -345,29 +406,43 @@ def block_compensation(comp: Optional[OnlineCompensation], lines):
Returns
-------
comp_block : OnlineCompensation or None
- ``comp`` with the block's reference offset.
+ comp with the block's reference offset.
shift : (float, float)
- ``(rows, cols)`` of the block's frame relative to the trial's
- reference frame; ``(0, 0)`` without compensation.
+ (rows, cols) of the block's frame relative to the trial's
+ reference frame; (0, 0) without compensation.
"""
if comp is None:
return None, (0.0, 0.0)
idx = np.asarray(lines, dtype=np.int64) - 1
- ref = matlab_round(
- [np.median(comp.offsets.x[idx]), np.median(comp.offsets.y_eff[idx])]
- )
+ ref = matlab_round([np.median(comp.offsets.x[idx]), np.median(comp.offsets.y_eff[idx])])
shift = comp.mapping @ (ref - comp.ref_offset)
return replace(comp, ref_offset=ref), (float(shift[0]), float(shift[1]))
def compensation_pad(
- comp: Optional[OnlineCompensation], layout: RasterLayout, times, dt: int
+ comp: OnlineCompensation | None, layout: RasterLayout, times: npt.ArrayLike, dt: int
) -> int:
"""Largest shift that compensation applies to the lines of some frames.
- Port of ``compensationPad``: samples of lines on another offset than
+ Port of compensationPad: samples of lines on another offset than
the reference move by up to this many pixels, possibly past the trimmed
raster. 0 without compensation.
+
+ Parameters
+ ----------
+ comp : OnlineCompensation or None
+ The trial's compensation.
+ layout : RasterLayout
+ The recording's layout.
+ times : array-like of int
+ One-based line times of the frames.
+ dt : int
+ Kernel time constant in lines.
+
+ Returns
+ -------
+ int
+ The largest shift in pixels.
"""
if comp is None:
return 0
@@ -384,8 +459,8 @@ def compensation_pad(
class RasterPixelFrames:
"""getImages' frames of a block of times at chosen raster pixels.
- Port of ``rawFramesAt`` (``slap2FrameSums`` with ``Boundary =
- 'exclusive'``, ``MaskInvalid = true`` and ``Pixels``): only the raster
+ Port of rawFramesAt (slap2FrameSums with Boundary =
+ 'exclusive', MaskInvalid = true and Pixels): only the raster
slots that can land on the wanted pixels are read and summed. Unlike
getImages, invalid samples are left out, so a frame's value is the mean
of each channel's valid samples.
@@ -405,7 +480,7 @@ class RasterPixelFrames:
channels : sequence of int
Zero-based file channels, in the order of the output.
comp : OnlineCompensation, optional
- Undo the online motion correction around ``comp.ref_offset``.
+ Undo the online motion correction around comp.ref_offset.
device : str or torch.device
Where sums are formed.
band : int
@@ -416,13 +491,13 @@ def __init__(
self,
layout: RasterLayout,
ids: np.ndarray,
- times,
+ times: npt.ArrayLike,
dt: int,
channels: Sequence[int],
- comp: Optional[OnlineCompensation] = None,
- device="cpu",
+ comp: OnlineCompensation | None = None,
+ device: str | torch.device = "cpu",
band: int = 16,
- ):
+ ) -> None:
"""Read the samples of the slots that land on the wanted pixels."""
times = np.asarray(times, dtype=np.int64)
self.dt = int(dt)
@@ -454,19 +529,55 @@ def __init__(
c0, c1 = (lo - 1) // p, (hi - 1) // p + 1
# samples behind the DMD curtain get no weight, as in registration
samples = read_raster_samples(sub, (c0, c1), mask_unlit=True)
- self.former = PixelFormer(
- sub, samples, c0, 1, device, exclusive=True, band=band
- )
+ self.former = PixelFormer(sub, samples, c0, 1, device, exclusive=True, band=band)
+
+ def _landing(self, rows: np.ndarray, cols: np.ndarray, dr: int, dc: int) -> np.ndarray:
+ """Index into ids of pixels moved by (dr, dc); -1 if none.
+
+ Parameters
+ ----------
+ rows, cols : ndarray of int
+ Zero-based raster rows and columns of the pixels.
+ dr, dc : int
+ Row and column shift.
- def _landing(self, rows, cols, dr: int, dc: int) -> np.ndarray:
- """Index into ``ids`` of pixels moved by ``(dr, dc)``; -1 if none."""
+ Returns
+ -------
+ np.ndarray
+ For each pixel, the index into ids of the pixel it lands on
+ after the shift; -1 where it lands on none.
+ """
n_rows, n_cols = self._shape
r, c = rows + dr, cols + dc
inside = (r >= 0) & (r < n_rows) & (c >= 0) & (c < n_cols)
return self._lut[np.where(inside, r * n_cols + c + 1, 0)]
- def _accum_shifted_w2(self, times, size, dev):
- """Accumulate shifted ``num``, ``den``, and ``den2`` across groups."""
+ def _accum_shifted_w2(
+ self, times: np.ndarray, size: tuple[int, int, int], dev: torch.device
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Accumulate shifted num, den, and den2 across groups.
+
+ Parameters
+ ----------
+ times : ndarray of int
+ One-based line times of the frames.
+ size : tuple of int
+ (channels, n_ids + 1, frames), the shape of the values.
+ dev : torch.device
+ Where the sums are formed.
+
+ Returns
+ -------
+ values : torch.Tensor of float64
+ (channels, n_ids + 1, frames) mean of each channel's valid
+ samples (NaN in the last row).
+ weight : torch.Tensor of float64
+ (n_ids + 1, frames) summed kernel weight of the first
+ channel's valid samples (NaN in the last row).
+ den2 : torch.Tensor of float64
+ (n_ids + 1, frames) summed squared weights (NaN in the last
+ row).
+ """
num = torch.zeros(size, dtype=torch.float64, device=dev)
den = torch.zeros_like(num)
den2 = torch.zeros(size[1:], dtype=torch.float64, device=dev)
@@ -500,7 +611,7 @@ def _accum_shifted_w2(self, times, size, dev):
den2[self.n_ids] = float("nan")
return values, weight, den2
- def frames(self, times, return_w2: bool = False):
+ def frames(self, times: npt.ArrayLike, return_w2: bool = False) -> tuple[torch.Tensor, ...]:
"""Frame values and weights at the wanted pixels.
Parameters
@@ -508,16 +619,16 @@ def frames(self, times, return_w2: bool = False):
times : array_like of int
One-based line times, among those given at construction.
return_w2 : bool
- Also return summed squared weights ``weight2`` ``(n_ids + 1,
- frames)``.
+ Also return summed squared weights weight2 (n_ids + 1,
+ frames).
Returns
-------
values : torch.Tensor of float64
- ``(channels, n_ids + 1, frames)``: the mean of each channel's
+ (channels, n_ids + 1, frames): the mean of each channel's
valid samples, NaN where a frame has none.
weight : torch.Tensor of float64
- ``(n_ids + 1, frames)``: the summed kernel weight of the first
+ (n_ids + 1, frames): the summed kernel weight of the first
channel's valid samples (0 where there are none).
The last row of both is NaN: it stands for a pixel outside the
@@ -529,15 +640,11 @@ def frames(self, times, return_w2: bool = False):
size = (len(self.channels), self.n_ids + 1, times.size)
if self.comp is None:
# one group: each sampled pixel's sums go to its own row
- (got,) = f.pixel_sums(
- times, self.dt, self.channels, None, return_w2
- )
+ (got,) = f.pixel_sums(times, self.dt, self.channels, None, return_w2)
s_num, s_den = got[2], got[3]
rows = torch.from_numpy(self._landing(f.rows, f.cols, 0, 0))
rows = rows.to(dev)
- values = torch.full(
- size, float("nan"), dtype=torch.float64, device=dev
- )
+ values = torch.full(size, float("nan"), dtype=torch.float64, device=dev)
weight = torch.zeros(size[1:], dtype=torch.float64, device=dev)
values.index_copy_(1, rows, s_num.div_(s_den))
weight.index_copy_(0, rows, s_den[0])
@@ -577,20 +684,47 @@ def frames(self, times, return_w2: bool = False):
return values, weight
-def _kernel_scale(
- dt: int, lines_per_cycle: int, exclusive: bool = True
-) -> float:
- """Dense-line ``sum(w) / sum(w^2)`` scaling ``F2 / D^2`` to ``1 / D``."""
+def _kernel_scale(dt: int, lines_per_cycle: int, exclusive: bool = True) -> float:
+ """Dense-line sum(w) / sum(w^2) scaling F2 / D^2 to 1 / D.
+
+ Parameters
+ ----------
+ dt : int
+ Kernel time constant in lines.
+ lines_per_cycle : int
+ Lines per scan cycle of the recording.
+ exclusive : bool
+ Whether the kernel's reach is one line shorter (exclusive boundary).
+
+ Returns
+ -------
+ float
+ sum(w) / sum(w^2) of the dense-line kernel weights w.
+ """
reach = max(3 * int(dt), int(lines_per_cycle)) - (1 if exclusive else 0)
u = np.arange(-reach, reach + 1, dtype=np.float64)
w = np.exp(-np.abs(u) / float(dt))
return float(w.sum() / (w * w).sum())
-def _freshness_scale(
- dt: int, lines_per_cycle: int, exclusive: bool = True
-) -> float:
- """Cycle-mean ``1 / mean(F2 / F1)`` scaling ``1 / D`` to ``F2 / D^2``."""
+def _freshness_scale(dt: int, lines_per_cycle: int, exclusive: bool = True) -> float:
+ """Cycle-mean 1 / mean(F2 / F1) scaling 1 / D to F2 / D^2.
+
+ Parameters
+ ----------
+ dt : int
+ Kernel time constant in lines.
+ lines_per_cycle : int
+ Lines per scan cycle of the recording.
+ exclusive : bool
+ Whether the kernel's reach is one line shorter (exclusive boundary).
+
+ Returns
+ -------
+ float
+ 1 / mean(F2 / F1) over the positions in a cycle where F1 is
+ positive; 1 where there is none.
+ """
p = max(int(lines_per_cycle), 1)
reach = max(3 * int(dt), p) - (1 if exclusive else 0)
m_max = reach // p + 1
@@ -605,25 +739,29 @@ def _freshness_scale(
def _weighted_sum(
- values, weight, neighbours, weight2=None, kernel_scale: float = 1.0
-):
+ values: torch.Tensor,
+ weight: torch.Tensor,
+ neighbours: Iterable[tuple[torch.Tensor, torch.Tensor]],
+ weight2: torch.Tensor | None = None,
+ kernel_scale: float = 1.0,
+) -> tuple[torch.Tensor, torch.Tensor]:
"""Weighted bilinear sums of frames at points.
- ``values`` is ``(channels, pixels, frames)`` and ``weight`` ``(pixels,
- frames)``. ``neighbours`` yields, for each of the four neighbours, the
- row of ``values`` and ``weight`` that holds it for every point and
- frame, ``(points, frames)``, and its bilinear coefficient (broadcast to
+ values is (channels, pixels, frames) and weight (pixels,
+ frames). neighbours yields, for each of the four neighbours, the
+ row of values and weight that holds it for every point and
+ frame, (points, frames), and its bilinear coefficient (broadcast to
that shape). The coefficient times the neighbour's weight is its share;
- the result is NaN where a neighbour is. When ``weight2`` is given,
- ``fq`` is ``kernel_scale * sum(c * weight2) / sum(c * weight)^2``
+ the result is NaN where a neighbour is. When weight2 is given,
+ fq is kernel_scale * sum(c * weight2) / sum(c * weight)^2
(pooling-conserved temporal kernel variance).
Returns
-------
y : torch.Tensor
- ``(channels, points, frames)`` values.
+ (channels, points, frames) values.
fq : torch.Tensor
- ``(points, frames)`` variance multiplier: the reciprocal of the
+ (points, frames) variance multiplier: the reciprocal of the
summed shares, or the kernel-weighted factor (NaN where undefined).
"""
n_f = values.shape[2]
@@ -660,33 +798,33 @@ def _weighted_sum(
def _interpolate(
- values,
- weight,
- tpos,
- shape,
- r_d,
- c_d,
- m_r,
- m_c,
- weight2=None,
+ values: torch.Tensor,
+ weight: torch.Tensor,
+ tpos: torch.Tensor,
+ shape: tuple[int, int],
+ r_d: torch.Tensor,
+ c_d: torch.Tensor,
+ m_r: torch.Tensor,
+ m_c: torch.Tensor,
+ weight2: torch.Tensor | None = None,
kernel_scale: float = 1.0,
-):
- """Bilinear interpolation of frames at moving points (``interpFrames``).
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Bilinear interpolation of frames at moving points (interpFrames).
- Point ``q`` is read in frame ``f`` at row ``r_d[q] + m_r[f]`` and column
- ``c_d[q] + m_c[f]`` (one-based) of the trimmed image of ``shape``. Each
+ Point q is read in frame f at row r_d[q] + m_r[f] and column
+ c_d[q] + m_c[f] (one-based) of the trimmed image of shape. Each
of the four neighbours is weighted by its bilinear coefficient times its
weight; a neighbour outside the image, or without valid samples, makes
- the result NaN. ``tpos`` maps the one-based row-major pixel index (0:
- outside) to the row of ``values`` (channels, pixels, frames) and
- ``weight`` (pixels, frames).
+ the result NaN. tpos maps the one-based row-major pixel index (0:
+ outside) to the row of values (channels, pixels, frames) and
+ weight (pixels, frames).
Returns
-------
y : torch.Tensor
- ``(channels, points, frames)`` values.
+ (channels, points, frames) values.
fq : torch.Tensor
- ``(points, frames)`` variance multiplier, the reciprocal of the
+ (points, frames) variance multiplier, the reciprocal of the
summed weights (NaN where that is 0 or undefined).
"""
n1, n2 = shape
@@ -696,8 +834,15 @@ def _interpolate(
fr, fc = r - rf, c - cf
rc, cc = torch.ceil(r), torch.ceil(c)
- def neighbours():
- """Rows and coefficients of the four neighbours."""
+ def neighbours() -> Iterator[tuple[torch.Tensor, torch.Tensor]]:
+ """Rows and coefficients of the four neighbours.
+
+ Yields
+ ------
+ tuple of torch.Tensor
+ The row of values and weight that holds the neighbour for
+ every point and frame, and its bilinear coefficient.
+ """
for rk, ck, w in (
(rf, cf, (1 - fc) * (1 - fr)),
(rf, cc, fc * (1 - fr)),
@@ -735,7 +880,16 @@ class _WholePixels:
Where frames are interpolated.
"""
- def __init__(self, tpos, shape, r_d, c_d, m_r, m_c, device):
+ def __init__(
+ self,
+ tpos: np.ndarray,
+ shape: tuple[int, int],
+ r_d: np.ndarray,
+ c_d: np.ndarray,
+ m_r: np.ndarray,
+ m_c: np.ndarray,
+ device: torch.device,
+ ) -> None:
"""Pad the table by the points' and the motion's reach."""
n1, n2 = shape
r_i, c_i = r_d.astype(np.int64), c_d.astype(np.int64)
@@ -757,33 +911,39 @@ def __init__(self, tpos, shape, r_d, c_d, m_r, m_c, device):
self.base = torch.from_numpy(base).to(device)[:, None]
def interpolate(
- self, values, weight, m_r, m_c, weight2=None, kernel_scale: float = 1.0
- ):
+ self,
+ values: torch.Tensor,
+ weight: torch.Tensor,
+ m_r: np.ndarray,
+ m_c: np.ndarray,
+ weight2: torch.Tensor | None = None,
+ kernel_scale: float = 1.0,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
""":func:`_interpolate` for these points (equal to rounding).
- ``m_r`` and ``m_c`` are NumPy arrays of the frames' motion.
+ m_r and m_c are NumPy arrays of the frames' motion.
+
+ Returns
+ -------
+ y : torch.Tensor
+ (channels, points, frames) values.
+ fq : torch.Tensor
+ (points, frames) variance multiplier.
"""
dev = values.device
lo_r, lo_c = np.floor(m_r), np.floor(m_c)
hi_r, hi_c = np.ceil(m_r), np.ceil(m_c)
fr, fc = m_r - lo_r, m_c - lo_c
- coef = np.stack(
- [(1 - fc) * (1 - fr), fc * (1 - fr), (1 - fc) * fr, fc * fr]
- )
- off = np.stack(
- [
- lo_r * self.width + lo_c,
- lo_r * self.width + hi_c,
- hi_r * self.width + lo_c,
- hi_r * self.width + hi_c,
- ]
- ).astype(np.int64)
+ coef = np.stack([(1 - fc) * (1 - fr), fc * (1 - fr), (1 - fc) * fr, fc * fr])
+ off = np.stack([
+ lo_r * self.width + lo_c,
+ lo_r * self.width + hi_c,
+ hi_r * self.width + lo_c,
+ hi_r * self.width + hi_c,
+ ]).astype(np.int64)
coef = torch.from_numpy(coef).to(dev)
off = torch.from_numpy(off).to(dev)
- neighbours = (
- (self.table[self.base + off[k][None, :]], coef[k])
- for k in range(4)
- )
+ neighbours = ((self.table[self.base + off[k][None, :]], coef[k]) for k in range(4))
return _weighted_sum(values, weight, neighbours, weight2, kernel_scale)
@@ -791,7 +951,18 @@ def _whole_pixel_frames(m_r: np.ndarray, m_c: np.ndarray) -> bool:
"""Whether whole-pixel points share their neighbours in these frames.
Not when a motion is within rounding of a whole pixel without being
- one: MATLAB's ``floor(point + motion)`` then depends on the point.
+ one: MATLAB's floor(point + motion) then depends on the point.
+
+ Parameters
+ ----------
+ m_r, m_c : ndarray
+ Row and column motion of the frames.
+
+ Returns
+ -------
+ bool
+ False if some motion is within rounding of a whole pixel without
+ being one; True otherwise.
"""
for m in (m_r, m_c):
f = m - np.floor(m)
@@ -800,14 +971,36 @@ def _whole_pixel_frames(m_r: np.ndarray, m_c: np.ndarray) -> bool:
return True
-def _mark_pixels(shape, r_d, c_d, m_r, m_c) -> np.ndarray:
- """Pixels of the trimmed image within a block's motion of each point."""
+def _mark_pixels(
+ shape: tuple[int, int],
+ r_d: np.ndarray,
+ c_d: np.ndarray,
+ m_r: np.ndarray,
+ m_c: np.ndarray,
+) -> np.ndarray:
+ """Pixels of the trimmed image within a block's motion of each point.
+
+ Parameters
+ ----------
+ shape : tuple of int
+ (rows, cols) of the trimmed image.
+ r_d, c_d : ndarray
+ One-based row and column of each point in the trimmed image.
+ m_r, m_c : ndarray
+ Motion of the block's frames.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean image of shape, True at the pixels that a neighbour of a
+ point can fall on within the block's motion.
+ """
n1, n2 = shape
mark = np.zeros(shape, dtype=bool)
r0 = np.floor(r_d + m_r.min()).astype(np.int64)
c0 = np.floor(c_d + m_c.min()).astype(np.int64)
- for dr in range(int(math.ceil(m_r.max() - m_r.min())) + 2):
- for dc in range(int(math.ceil(m_c.max() - m_c.min())) + 2):
+ for dr in range(math.ceil(m_r.max() - m_r.min()) + 2):
+ for dc in range(math.ceil(m_c.max() - m_c.min()) + 2):
r, c = r0 + dr, c0 + dc
ok = (r >= 1) & (r <= n1) & (c >= 1) & (c <= n2)
mark[r[ok] - 1, c[ok] - 1] = True
@@ -817,7 +1010,7 @@ def _mark_pixels(shape, r_d, c_d, m_r, m_c) -> np.ndarray:
def frames_at(
layout: RasterLayout,
channels: Sequence[int],
- times,
+ times: npt.ArrayLike,
dt: int,
trim_rows: np.ndarray,
trim_cols: np.ndarray,
@@ -825,19 +1018,19 @@ def frames_at(
c_d: np.ndarray,
m_r: np.ndarray,
m_c: np.ndarray,
- comp: Optional[OnlineCompensation] = None,
- device="cpu",
+ comp: OnlineCompensation | None = None,
+ device: str | torch.device = "cpu",
chunk: int = 128,
band: int = 16,
whole_pixels: bool = True,
variance_mode: str = "freshness",
-):
+) -> Iterator[tuple[slice, torch.Tensor, torch.Tensor]]:
"""Motion-corrected frames at points of the trimmed raster image.
- Port of ``slap2FramesAt``: the frames getImages returns (without its
- invalid samples), trimmed to ``trim_rows x trim_cols`` and interpolated
- as ``interpFrames`` does, at rows ``r_d + m_r[f]`` and columns ``c_d +
- m_c[f]`` of frame ``f``. Frames are formed only at the raster pixels
+ Port of slap2FramesAt: the frames getImages returns (without its
+ invalid samples), trimmed to trim_rows x trim_cols and interpolated
+ as interpFrames does, at rows r_d + m_r[f] and columns c_d +
+ m_c[f] of frame f. Frames are formed only at the raster pixels
that these points' neighbours can fall on.
Parameters
@@ -855,8 +1048,8 @@ def frames_at(
r_d, c_d : ndarray
One-based row and column of each point in the trimmed image.
m_r, m_c : ndarray
- Motion of each frame. With ``comp``, motion estimated on frames
- formed around ``comp.ref_offset``.
+ Motion of each frame. With comp, motion estimated on frames
+ formed around comp.ref_offset.
comp : OnlineCompensation, optional
Form the frames with the online motion correction undone.
device : str or torch.device
@@ -874,9 +1067,9 @@ def frames_at(
frames : slice
The frames of this part.
y : torch.Tensor of float64
- ``(channels, points, frames)`` values.
+ (channels, points, frames) values.
fq : torch.Tensor of float64
- ``(points, frames)`` variance multiplier.
+ (points, frames) variance multiplier.
"""
times = np.asarray(times, dtype=np.int64).ravel()
m_r = np.asarray(m_r, dtype=np.float64)
@@ -895,26 +1088,15 @@ def frames_at(
mark = _mark_pixels(shape, r_d, c_d, m_r, m_c)
rt, ct = np.nonzero(mark)
ids = trim_cols[ct] + layout.n_cols * (trim_rows[rt] - 1)
- raw = RasterPixelFrames(
- layout, ids, times, dt, channels, comp, device, band
- )
+ raw = RasterPixelFrames(layout, ids, times, dt, channels, comp, device, band)
dev = raw.former.device
tpos = np.full(shape[0] * shape[1] + 1, ids.size, dtype=np.int64)
tpos[np.flatnonzero(mark) + 1] = np.arange(ids.size)
whole = None
- if (
- whole_pixels
- and r_d.size
- and np.all(r_d == np.round(r_d))
- and np.all(c_d == np.round(c_d))
- ):
+ if whole_pixels and r_d.size and np.all(r_d == np.round(r_d)) and np.all(c_d == np.round(c_d)):
whole = _WholePixels(tpos, shape, r_d, c_d, m_r, m_c, dev)
use_w2 = variance_mode == "kernel"
- k_scale = (
- _kernel_scale(dt, layout.lines_per_cycle, exclusive=True)
- if use_w2
- else 1.0
- )
+ k_scale = _kernel_scale(dt, layout.lines_per_cycle, exclusive=True) if use_w2 else 1.0
tpos = torch.from_numpy(tpos).to(dev)
r_t, c_t = torch.from_numpy(r_d).to(dev), torch.from_numpy(c_d).to(dev)
for a in range(0, times.size, chunk):
@@ -925,9 +1107,7 @@ def frames_at(
values, weight = raw.frames(times[part], False)
weight2 = None
if whole is not None and _whole_pixel_frames(m_r[part], m_c[part]):
- y, fq = whole.interpolate(
- values, weight, m_r[part], m_c[part], weight2, k_scale
- )
+ y, fq = whole.interpolate(values, weight, m_r[part], m_c[part], weight2, k_scale)
else:
y, fq = _interpolate(
values,
@@ -945,7 +1125,20 @@ def frames_at(
def _linspace(a: float, b: float, n: int) -> np.ndarray:
- """MATLAB's ``linspace``: ``a + (0:n-1) * (b - a) / (n - 1)``."""
+ """MATLAB's linspace: a + (0:n-1) * (b - a) / (n - 1).
+
+ Parameters
+ ----------
+ a, b : float
+ First and last value.
+ n : int
+ Number of values.
+
+ Returns
+ -------
+ np.ndarray
+ n evenly spaced values from a to b.
+ """
if n == 1:
return np.array([float(b)])
y = a + (np.arange(n) * (b - a)) / (n - 1)
@@ -954,29 +1147,68 @@ def _linspace(a: float, b: float, n: int) -> np.ndarray:
def frame_lines(first_line: float, last_line: float, dt: float) -> np.ndarray:
- """One-based line of each extraction frame: ``ceil(first:dt:last)``."""
+ """One-based line of each extraction frame: ceil(first:dt:last).
+
+ Parameters
+ ----------
+ first_line, last_line : float
+ One-based line range of the trial.
+ dt : float
+ Lines per extraction frame.
+
+ Returns
+ -------
+ np.ndarray
+ One-based line of each frame.
+ """
return np.ceil(matlab_colon(first_line, dt, last_line)).astype(np.int64)
def block_edges(n_frames: int, block: int) -> np.ndarray:
- """First frame of each block, and ``n_frames`` (zero-based).
+ """First frame of each block, and n_frames (zero-based).
+
+ MATLAB's round(linspace(1, nFrames + 1, nBlocks + 1)).
+
+ Parameters
+ ----------
+ n_frames : int
+ Number of frames.
+ block : int
+ Frames per block (at most).
- MATLAB's ``round(linspace(1, nFrames + 1, nBlocks + 1))``.
+ Returns
+ -------
+ np.ndarray
+ Zero-based first frame of each block, followed by n_frames.
"""
- n_blocks = int(math.ceil(n_frames / block))
+ n_blocks = math.ceil(n_frames / block)
edges = matlab_round(_linspace(1, n_frames + 1, n_blocks + 1))
return edges.astype(np.int64) - 1
-def upsample_motion(ds_frames, motion, lines) -> np.ndarray:
+def upsample_motion(ds_frames: np.ndarray, motion: np.ndarray, lines: npt.ArrayLike) -> np.ndarray:
"""Motion of the registered frames interpolated to other lines.
- MATLAB's ``interp1(DSframes, motion, lines, 'pchip', 'extrap')``; the
+ MATLAB's interp1(DSframes, motion, lines, 'pchip', 'extrap'); the
motion of a single registered frame is used throughout. Registered
frames without motion (NaN: frames without samples in
:mod:`giant_python.registration`) are left out; MATLAB's registration
gives every frame a motion.
+ Parameters
+ ----------
+ ds_frames : ndarray
+ One-based line of each registered frame.
+ motion : ndarray
+ Motion of each registered frame (NaN where it has none).
+ lines : array-like
+ Lines to interpolate to.
+
+ Returns
+ -------
+ np.ndarray
+ The motion at lines, with the shape of lines.
+
Raises
------
ValueError
@@ -985,19 +1217,29 @@ def upsample_motion(ds_frames, motion, lines) -> np.ndarray:
ok = np.isfinite(motion)
lines = np.asarray(lines, dtype=np.float64)
if ok.sum() > 1:
- return PchipInterpolator(ds_frames[ok], motion[ok], extrapolate=True)(
- lines
- )
+ return PchipInterpolator(ds_frames[ok], motion[ok], extrapolate=True)(lines)
if not ok.any():
raise ValueError("the trial's registration has no motion")
return np.full(lines.shape, float(motion[ok][0]))
-def upsample_discard(discard, n_frames: int) -> np.ndarray:
+def upsample_discard(discard: npt.ArrayLike, n_frames: int) -> np.ndarray:
"""Discarded registered frames at the extraction's frames.
- MATLAB's ``interp1(1:n, double(discard), linspace(1, n, nFrames)) > 0``:
+ MATLAB's interp1(1:n, double(discard), linspace(1, n, nFrames)) > 0:
a frame is discarded if either registered frame around it is.
+
+ Parameters
+ ----------
+ discard : array-like of bool
+ Registered frames discarded for motion.
+ n_frames : int
+ Number of extraction frames.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean array of n_frames: the discarded extraction frames.
"""
d = np.asarray(discard, dtype=bool).ravel()
if d.size <= 1:
@@ -1009,24 +1251,66 @@ def upsample_discard(discard, n_frames: int) -> np.ndarray:
def medfilt3(a: np.ndarray) -> np.ndarray:
- """MATLAB's ``medfilt2(a, [3 3])``: zeros outside the image, and NaN
- wherever the window holds a NaN."""
+ """Filter an image like MATLAB's medfilt2(a, [3 3]).
+
+ Zeros outside the image count as values, and the result is NaN wherever
+ the window holds a NaN.
+
+ Parameters
+ ----------
+ a : ndarray
+ The image.
+
+ Returns
+ -------
+ np.ndarray
+ The 3 x 3 median filter of a.
+ """
p = np.pad(np.asarray(a, dtype=np.float64), 1)
win = np.lib.stride_tricks.sliding_window_view(p, (3, 3))
return np.median(win.reshape(a.shape + (9,)), axis=-1)
def labeled_pixels(mean_activity: np.ndarray) -> np.ndarray:
- """Pixels of the global trace: brighter than three times the 25th
- percentile of the median-filtered mean image of the activity channel."""
+ """Select the pixels of the global trace.
+
+ These are brighter than three times the 25th percentile of the
+ median-filtered mean image of the activity channel.
+
+ Parameters
+ ----------
+ mean_activity : ndarray
+ Mean image (rows, cols) of the activity channel.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask of the labeled pixels (False where mean_activity
+ is NaN).
+ """
lab = medfilt3(mean_activity)
with np.errstate(invalid="ignore"):
bright = lab > 3 * matlab_prctile(lab, 25)
return ~np.isnan(mean_activity) & bright
-def _fit(a: np.ndarray, shape, fill) -> np.ndarray:
- """Crop or pad the leading two axes to ``shape``, corner in place."""
+def _fit(a: np.ndarray, shape: tuple[int, int], fill: float | bool) -> np.ndarray:
+ """Crop or pad the leading two axes to shape, corner in place.
+
+ Parameters
+ ----------
+ a : ndarray
+ The array.
+ shape : tuple of int
+ (rows, cols) to fit.
+ fill : float or bool
+ Value of the padding.
+
+ Returns
+ -------
+ np.ndarray
+ a cropped or padded to shape on its first two axes.
+ """
out = np.full(tuple(shape) + a.shape[2:], fill, dtype=a.dtype)
r, c = min(shape[0], a.shape[0]), min(shape[1], a.shape[1])
out[:r, :c] = a[:r, :c]
@@ -1041,7 +1325,24 @@ def _mean_bilinear_q(
keep: np.ndarray,
block: int = 512,
) -> np.ndarray:
- """Mean 2-D bilinear variance attenuation ``Q(fr) Q(fc)`` per pixel."""
+ """Mean 2-D bilinear variance attenuation Q(fr) Q(fc) per pixel.
+
+ Parameters
+ ----------
+ r_sel, c_sel : ndarray
+ One-based row and column of each pixel.
+ mot_r, mot_c : ndarray
+ Row and column motion of each frame.
+ keep : ndarray of bool
+ Frames to average over (all frames if none is kept).
+ block : int
+ Frames processed at a time.
+
+ Returns
+ -------
+ np.ndarray
+ The attenuation of each pixel, averaged over the kept frames.
+ """
n_px = r_sel.size
if n_px == 0:
return np.zeros(0, dtype=np.float64)
@@ -1061,16 +1362,41 @@ def _mean_bilinear_q(
def _window_reach(window: float) -> tuple:
- """Frames a moving window reaches back and ahead: ``i - w/2 <= j < i +
- w/2``, as MATLAB places windows of even, odd or fractional length."""
- return int(math.floor(window / 2)), int(math.ceil(window / 2)) - 1
+ """Return the frames a moving window reaches back and ahead.
+
+ That is i - w/2 <= j < i + w/2, as MATLAB places windows of even,
+ odd or fractional length.
+
+ Parameters
+ ----------
+ window : float
+ Length of the window in frames.
+
+ Returns
+ -------
+ tuple of int
+ Frames reached back and ahead of a frame.
+ """
+ return math.floor(window / 2), math.ceil(window / 2) - 1
def movmean(a: np.ndarray, window: float) -> np.ndarray:
- """MATLAB ``smoothdata(a, 2, 'movmean', window, 'omitmissing')``.
+ """MATLAB smoothdata(a, 2, 'movmean', window, 'omitmissing').
The mean of the values in each window along the last axis; the window
shrinks at the ends; NaN where it holds no value.
+
+ Parameters
+ ----------
+ a : ndarray
+ The data, NaN where missing.
+ window : float
+ Length of the window in frames.
+
+ Returns
+ -------
+ np.ndarray
+ The moving mean of a, with its shape.
"""
back, ahead = _window_reach(window)
ok = ~np.isnan(a)
@@ -1090,6 +1416,18 @@ def movmean(a: np.ndarray, window: float) -> np.ndarray:
def _fill_passes(ok: np.ndarray, window: float) -> int:
"""Moving-mean passes until rows with these valid samples are full.
+ Parameters
+ ----------
+ ok : ndarray of bool
+ (rows, frames) valid samples.
+ window : float
+ Length of the moving mean in frames.
+
+ Returns
+ -------
+ int
+ The number of passes that fill every row.
+
Raises
------
ValueError
@@ -1120,15 +1458,40 @@ def _fill_passes(ok: np.ndarray, window: float) -> int:
def _start_at_zero(ok: np.ndarray) -> np.ndarray:
- """Valid samples of rows, a row without any starting from frame 0
- (MATLAB sets the first frame of such a pixel to 0 before filling)."""
+ """Return the valid samples of rows, starting from frame 0 where none is.
+
+ A row without any valid sample is given one at frame 0 (MATLAB sets the
+ first frame of such a pixel to 0 before filling).
+
+ Parameters
+ ----------
+ ok : ndarray of bool
+ (rows, frames) valid samples.
+
+ Returns
+ -------
+ np.ndarray
+ A copy of ok with frame 0 valid in each row that had no valid
+ sample.
+ """
ok = ok.copy()
ok[~ok.any(1), 0] = True
return ok
def _nan_std(a: np.ndarray) -> np.ndarray:
- """MATLAB ``std(a, 0, 2, 'omitmissing')`` (N - 1; 0 for one value)."""
+ """MATLAB std(a, 0, 2, 'omitmissing') (N - 1; 0 for one value).
+
+ Parameters
+ ----------
+ a : ndarray
+ (rows, frames) data, NaN where missing.
+
+ Returns
+ -------
+ np.ndarray
+ Standard deviation of each row (NaN for a row without values).
+ """
ok = ~np.isnan(a)
n = ok.sum(1)
with np.errstate(invalid="ignore", divide="ignore"):
@@ -1140,15 +1503,34 @@ def _nan_std(a: np.ndarray) -> np.ndarray:
def _threads() -> int:
- """Threads for row-wise NumPy work (which releases the GIL)."""
+ """Return the threads for row-wise NumPy work (which releases the GIL).
+
+ Returns
+ -------
+ int
+ Between 1 and 8: half the CPUs.
+ """
return max(1, min(8, (os.cpu_count() or 2) // 2))
-def _drop_outliers(part: np.ndarray, common: np.ndarray, window: float):
+def _drop_outliers(part: np.ndarray, common: np.ndarray, window: float) -> tuple[int, bool]:
"""Set a block of rows' aberrantly negative samples to NaN, in place.
- Returns the moving-mean passes that fill these rows, and whether any
- row misses only the frames that ``common`` misses.
+ Parameters
+ ----------
+ part : ndarray
+ (rows, frames) block of data; modified in place.
+ common : ndarray of bool
+ Valid samples of a row that misses only the discarded frames.
+ window : float
+ Length of the moving mean in frames.
+
+ Returns
+ -------
+ passes : int
+ The moving-mean passes that fill these rows.
+ shared : bool
+ Whether any row misses only the frames that common misses.
"""
v = part.astype(np.float64)
with np.errstate(invalid="ignore"):
@@ -1159,11 +1541,17 @@ def _drop_outliers(part: np.ndarray, common: np.ndarray, window: float):
return _fill_passes(ok[other], window), not other.all()
-def _fill_rows(part, finv_part, passes: int, window: float, fill_finv):
+def _fill_rows(
+ part: np.ndarray,
+ finv_part: np.ndarray | None,
+ passes: int,
+ window: float,
+ fill_finv: float,
+) -> None:
"""Fill a block of rows' missing samples, in place.
- ``finv_part`` (the rows' variance multiplier, or None for channels
- other than the activity channel) gets ``fill_finv`` where missing.
+ finv_part (the rows' variance multiplier, or None for channels
+ other than the activity channel) gets fill_finv where missing.
"""
nans = np.isnan(part)
if finv_part is not None:
@@ -1184,11 +1572,11 @@ def finish_pixels(
window: float,
rows: int = 512,
) -> None:
- """The end of ``loadTrial``, in place: discards, outliers, gap filling.
+ """Finish loadTrial in place: discards, outliers, gap filling.
Discarded frames and samples below minus twice the pixel's standard
deviation become missing. Missing samples are filled by repeated moving
- means over ``window`` frames (as many passes over the whole array as its
+ means over window frames (as many passes over the whole array as its
longest gap needs; a pixel without any sample starts from 0 at its
first frame), and get 1000 times the mean variance multiplier where the
activity channel is missing.
@@ -1196,9 +1584,9 @@ def finish_pixels(
Parameters
----------
y : ndarray
- ``(channels, pixels, frames)`` data, NaN where missing.
+ (channels, pixels, frames) data, NaN where missing.
finv : ndarray
- ``(pixels, frames)`` variance multiplier.
+ (pixels, frames) variance multiplier.
discard : ndarray of bool
Discarded frames.
window : float
@@ -1217,11 +1605,7 @@ def finish_pixels(
y[:, :, discard] = np.nan
if n_px == 0:
return
- blocks = [
- (ch, slice(a, a + rows))
- for ch in range(n_ch)
- for a in range(0, n_px, rows)
- ]
+ blocks = [(ch, slice(a, a + rows)) for ch in range(n_ch) for a in range(0, n_px, rows)]
# most pixels miss only the discarded frames: count their passes once
common = _start_at_zero(~np.asarray(discard, dtype=bool)[None, :])
common_passes = _fill_passes(common, window)
@@ -1258,23 +1642,23 @@ def finish_pixels(
def leading_svd(x: np.ndarray, k: int) -> tuple:
- """The ``k`` leading singular triplets of ``x``.
+ """Return the k leading singular triplets of x.
- ``numpy.linalg.svd`` computes every component, which for a soma ROI
+ numpy.linalg.svd computes every component, which for a soma ROI
(thousands of pixels by thousands of frames) takes seconds per call,
and :func:`nansvd` calls it up to ten times per ROI and channel while
using three components. Here the leading eigenvectors of the smaller
Gram matrix give the same components (to rounding, and up to their
- signs, which the callers do not depend on). Where two of the ``k + 1``
+ signs, which the callers do not depend on). Where two of the k + 1
leading singular values agree to 1e-7 of the largest, the data do not
determine how the components split between them, and an eigensolver may
split them otherwise than the SVD does; the full SVD is used then, as
for a component at the rounding level of the Gram matrix (a singular
value under 1e-7 of the largest) and for data that are not float64.
The Gram matrix squares the condition number: the reconstruction from
- the ``k`` components agrees with the full SVD's to about 1e-15 of the
+ the k components agrees with the full SVD's to about 1e-15 of the
largest singular value for well-conditioned data and to about 1e-11
- where the smallest of the ``k`` is 1e-6 of the largest.
+ where the smallest of the k is 1e-6 of the largest.
Parameters
----------
@@ -1282,7 +1666,7 @@ def leading_svd(x: np.ndarray, k: int) -> tuple:
Finite data (float64 for the Gram-matrix path; :func:`nansvd`
passes float64).
k : int
- Components, 0 to ``min(m, n)``.
+ Components, 0 to min(m, n).
Returns
-------
@@ -1292,12 +1676,7 @@ def leading_svd(x: np.ndarray, k: int) -> tuple:
vt : ndarray of shape (k, n)
"""
m, n = x.shape
- if (
- k < 1
- or k >= min(m, n)
- or min(m, n) < 64
- or np.asarray(x).dtype != np.float64
- ):
+ if k < 1 or k >= min(m, n) or min(m, n) < 64 or np.asarray(x).dtype != np.float64:
# also data of lower precision: the Gram matrix squares the
# condition number, and the limits below are those of float64
u, s, vt = np.linalg.svd(x, full_matrices=False)
@@ -1310,9 +1689,7 @@ def leading_svd(x: np.ndarray, k: int) -> tuple:
w, vec = eigh(small @ small.T, subset_by_index=[r - k - 1, r - 1])
s_more = np.sqrt(np.maximum(w[::-1], 0.0))
s, vec = s_more[:k], vec[:, ::-1][:, :k]
- if not np.all(s > s[0] * 1e-7) or np.any(
- s_more[:-1] - s_more[1:] <= s[0] * 1e-7
- ):
+ if not np.all(s > s[0] * 1e-7) or np.any(s_more[:-1] - s_more[1:] <= s[0] * 1e-7):
# a component at the rounding level of the Gram matrix, which the
# eigenvectors do not resolve; or two (nearly) equal singular
# values, whose components the eigenvectors may split otherwise
@@ -1323,21 +1700,21 @@ def leading_svd(x: np.ndarray, k: int) -> tuple:
def nansvd(
- d: np.ndarray, num_comps: int = 3, max_iter: int = 20, nan_frac=0.3
-):
- """Truncated SVD of data with gaps (``nansvd.m``).
+ d: np.ndarray, num_comps: int = 3, max_iter: int = 20, nan_frac: float = 0.3
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Compute the truncated SVD of data with gaps (nansvd.m).
- Rows and columns with at least ``nan_frac`` of their values missing are
- left out, repeatedly, until the choice no longer changes (``nansvd.m``
+ Rows and columns with at least nan_frac of their values missing are
+ left out, repeatedly, until the choice no longer changes (nansvd.m
stops when the numbers of rows and columns no longer change, which is
the same unless a pass exchanges rows or columns); a moving mean over a
fifth of the columns is subtracted; the remaining gaps are filled
- iteratively with the rank-``num_comps`` estimate.
+ iteratively with the rank-num_comps estimate.
Parameters
----------
d : ndarray
- ``(pixels, timepoints)`` data, NaN where missing.
+ (pixels, timepoints) data, NaN where missing.
num_comps : int
Number of components.
max_iter : int
@@ -1348,14 +1725,14 @@ def nansvd(
Returns
-------
u : ndarray
- ``(pixels, num_comps)`` left singular vectors, NaN in the rows left
+ (pixels, num_comps) left singular vectors, NaN in the rows left
out and in components that the data are too small for.
s : ndarray
- ``(num_comps,)`` singular values (0 for missing components).
+ (num_comps,) singular values (0 for missing components).
v : ndarray
- ``(timepoints, num_comps)`` right singular vectors.
+ (timepoints, num_comps) right singular vectors.
bg : ndarray
- ``(pixels, timepoints)`` subtracted moving mean (NaN where left
+ (pixels, timepoints) subtracted moving mean (NaN where left
out).
"""
d = np.asarray(d, dtype=np.float64)
@@ -1402,7 +1779,7 @@ def nansvd(
def roi_svd_trace(d: np.ndarray, nan_thresh: float) -> np.ndarray:
- """A user ROI's trace denoised with the SVD, as ``loadTrial`` does.
+ """Return a user ROI's trace denoised with the SVD, as loadTrial does.
Of the three leading components of the ROI's pixels, the one that
weights the pixels most evenly (times its singular value) is kept; the
@@ -1411,14 +1788,14 @@ def roi_svd_trace(d: np.ndarray, nan_thresh: float) -> np.ndarray:
Parameters
----------
d : ndarray
- ``(pixels, frames)`` data of the ROI's pixels, NaN where missing.
+ (pixels, frames) data of the ROI's pixels, NaN where missing.
nan_thresh : float
- ``nanThresh``.
+ nanThresh.
Returns
-------
ndarray
- ``(frames,)`` trace; NaN where the ROI has no usable data.
+ (frames,) trace; NaN where the ROI has no usable data.
"""
out = np.full(d.shape[1], np.nan)
if d.size == 0 or np.isnan(d).all():
@@ -1435,15 +1812,15 @@ def roi_svd_trace(d: np.ndarray, nan_thresh: float) -> np.ndarray:
@dataclass
class TrialData:
- """One trial's data for source extraction (MATLAB's ``CD``).
+ """One trial's data for source extraction (MATLAB's CD).
Attributes
----------
y : ndarray
- ``(channels, pixels, frames)`` data in counts / ``photon_scale``,
+ (channels, pixels, frames) data in counts / photon_scale,
channel 0 the activity channel; missing samples are filled in.
finv : ndarray
- ``(pixels, frames)`` variance multiplier (large where filled in).
+ (pixels, frames) variance multiplier (large where filled in).
frame_lines : ndarray of int
One-based line of each frame.
motion_r, motion_c : ndarray
@@ -1452,22 +1829,22 @@ class TrialData:
discard : ndarray of bool
Frames discarded for motion.
global_f : ndarray
- ``(channels, frames)`` global trace of the labeled pixels, in counts
- and in the file's channel order (``CD.global.F``).
+ (channels, frames) global trace of the labeled pixels, in counts
+ and in the file's channel order (CD.global.F).
roi_f, roi_fsvd : ndarray
- ``(rois, channels, frames)`` user-ROI traces, plain and denoised, in
- counts and in analysis channel order (``CD.ROIs.F``, ``Fsvd``).
+ (rois, channels, frames) user-ROI traces, plain and denoised, in
+ counts and in analysis channel order (CD.ROIs.F, Fsvd).
pixel_rc : ndarray of int
- ``(pixels, 2)`` zero-based consensus row and column of each pixel,
+ (pixels, 2) zero-based consensus row and column of each pixel,
in column-major order of the map.
trial_rc : ndarray
- ``(pixels, 2)`` zero-based position of each pixel in the trial's
+ (pixels, 2) zero-based position of each pixel in the trial's
registered frame.
photon_scale : float
- Counts per unit of ``y``.
+ Counts per unit of y.
timings : dict
- Wall time in seconds of each phase (``setup``, ``frames``,
- ``roi_svd``, ``finish``; ``layout``, the part of ``setup`` spent
+ Wall time in seconds of each phase (setup, frames,
+ roi_svd, finish; layout, the part of setup spent
reading the recording's layout).
"""
@@ -1484,26 +1861,46 @@ class TrialData:
trial_rc: np.ndarray
photon_scale: float
timings: dict = field(default_factory=dict)
- q_spatial: Optional[np.ndarray] = None
+ q_spatial: np.ndarray | None = None
kernel_scale: float = 1.0
class _Traces:
"""The global and user-ROI traces, accumulated block by block."""
- def __init__(self, mean_px, labeled, masks, order, n_frames, qpos, dev):
+ def __init__(
+ self,
+ mean_px: np.ndarray,
+ labeled: np.ndarray,
+ masks: list[np.ndarray],
+ order: list[int],
+ n_frames: int,
+ qpos: np.ndarray,
+ dev: torch.device,
+ ) -> None:
"""Index the labeled and ROI pixels among the sampled points.
- ``mean_px`` is the view's mean image ``(rows, cols, channels)`` in
- analysis channel order; ``qpos`` maps a view pixel to its point.
+ mean_px is the view's mean image (rows, cols, channels) in
+ analysis channel order; qpos maps a view pixel to its point.
"""
n_ch = mean_px.shape[2]
self.order = order
with np.errstate(invalid="ignore"):
self.sum_f = np.nansum(mean_px.reshape(-1, n_ch), 0)
- def tensor(a):
- """A NumPy array on the device."""
+ def tensor(a: np.ndarray) -> torch.Tensor:
+ """Return a NumPy array on the device.
+
+ Parameters
+ ----------
+ a : ndarray
+ The array.
+
+ Returns
+ -------
+ torch.Tensor
+ a as a tensor on dev.
+ """
return torch.from_numpy(np.ascontiguousarray(a)).to(dev)
self.q_lab = tensor(qpos[labeled])
@@ -1513,19 +1910,13 @@ def tensor(a):
self.sum_roi = [np.nansum(mean_px[m], 0) for m in masks]
self.global_f = np.full((n_ch, n_frames), np.nan)
self.roi_f = np.full((len(masks), n_ch, n_frames), np.nan)
- self.roi_px = [
- np.full((n_ch, q.numel(), n_frames), np.nan) for q in self.q_roi
- ]
+ self.roi_px = [np.full((n_ch, q.numel(), n_frames), np.nan) for q in self.q_roi]
def add(self, frames: slice, y: torch.Tensor) -> None:
- """Add the frames of one part: ``y`` is (channels, points, frames)."""
+ """Add the frames of one part: y is (channels, points, frames)."""
for k in range(y.shape[0]):
- g = _ratio(
- y[k].index_select(0, self.q_lab), self.m_lab[:, k], False
- )
- self.global_f[self.order[k], frames] = (
- g.cpu().numpy() * self.sum_f[k]
- )
+ g = _ratio(y[k].index_select(0, self.q_lab), self.m_lab[:, k], False)
+ self.global_f[self.order[k], frames] = g.cpu().numpy() * self.sum_f[k]
for r, q in enumerate(self.q_roi):
t = y[k].index_select(0, q)
f = _ratio(t, self.m_roi[r][:, k], True).cpu().numpy()
@@ -1534,7 +1925,18 @@ def add(self, frames: slice, y: torch.Tensor) -> None:
self.roi_f[r, k, frames] = f * self.sum_roi[r][k]
def roi_fsvd(self, nan_thresh: float) -> np.ndarray:
- """The ROI traces denoised by the SVD of their pixels."""
+ """Return the ROI traces denoised by the SVD of their pixels.
+
+ Parameters
+ ----------
+ nan_thresh : float
+ nanThresh.
+
+ Returns
+ -------
+ np.ndarray
+ (rois, channels, frames) denoised ROI traces.
+ """
out = np.full(self.roi_f.shape, np.nan)
for r, px in enumerate(self.roi_px):
for k in range(px.shape[0]):
@@ -1543,12 +1945,26 @@ def roi_fsvd(self, nan_thresh: float) -> np.ndarray:
def _ratio(t: torch.Tensor, m: torch.Tensor, mean_gaps: bool) -> torch.Tensor:
- """Summed data over the summed mean image of the same pixels.
+ """Return the summed data over the summed mean image of the same pixels.
- ``t`` is ``(pixels, frames)``, ``m`` the pixels' mean image. Pixels
+ t is (pixels, frames), m the pixels' mean image. Pixels
whose sample is missing are left out of both sums; a pixel whose mean
- is missing is left out of both for the ROI traces (``mean_gaps``) and
+ is missing is left out of both for the ROI traces (mean_gaps) and
only out of the mean's sum for the global trace, as in MATLAB.
+
+ Parameters
+ ----------
+ t : torch.Tensor
+ (pixels, frames) data.
+ m : torch.Tensor
+ (pixels,) mean image of the pixels.
+ mean_gaps : bool
+ Whether a pixel whose mean is missing is left out of both sums.
+
+ Returns
+ -------
+ torch.Tensor
+ (frames,) ratio of the summed data to the summed mean.
"""
gap = torch.isnan(t)
either = gap | torch.isnan(m)[:, None]
@@ -1558,16 +1974,35 @@ def _ratio(t: torch.Tensor, m: torch.Tensor, mean_gaps: bool) -> torch.Tensor:
def _continued(view: np.ndarray, n: int) -> np.ndarray:
- """The view's positions for ``n`` rows or columns of the consensus
- frame: beyond the trial's registered frame, continued by unit steps."""
+ """Return the view's positions for n rows or columns of the consensus frame.
+
+ Beyond the trial's registered frame, the positions are continued by unit
+ steps.
+
+ Parameters
+ ----------
+ view : ndarray
+ Positions of the rows or columns of the registered frame.
+ n : int
+ Number of rows or columns of the consensus frame.
+
+ Returns
+ -------
+ np.ndarray
+ n positions.
+ """
extra = np.arange(1, max(0, n - view.size) + 1)
return np.concatenate([view, view[-1] + extra])[:n]
-def _points(need, alignment: TrialAlignment, warp):
+def _points(
+ need: np.ndarray,
+ alignment: TrialAlignment,
+ warp: Callable[..., tuple[np.ndarray, np.ndarray]],
+) -> tuple[np.ndarray, np.ndarray, tuple[float, float], tuple[float, float], np.ndarray]:
"""Where the wanted pixels are read in the trimmed raster image.
- ``need`` marks the wanted pixels of the consensus frame, which shares
+ need marks the wanted pixels of the consensus frame, which shares
its top left corner with the trial's registered frame and may be
larger: a pixel beyond the registered frame is read where the frame's
grid, continued, or the warp puts it.
@@ -1581,7 +2016,13 @@ def _points(need, alignment: TrialAlignment, warp):
centre : (float, float)
Displacement that the warp adds at the image centre.
qpos : ndarray of int
- Point of each pixel of ``need`` (-1: not read).
+ Point of each pixel of need (-1: not read).
+
+ Raises
+ ------
+ ValueError
+ If the registered frame's rows or columns are not in unit steps
+ and the warp is not a :class:`RigidShift`.
"""
rq, cq = np.nonzero(need)
qpos = np.full(need.shape, -1, dtype=np.int64)
@@ -1609,22 +2050,46 @@ def _points(need, alignment: TrialAlignment, warp):
"""Recording layouts read by :func:`recording_layout` (the last few)."""
-def _layout_path(dat_path) -> str:
- """The ``.dat`` path a layout is kept under: its directory resolved
- (links followed before any ``..``, as the system opens it) and its
- name as given (the name decides whether the reader opens one file or
- the CYCLE group)."""
+def _layout_path(dat_path: str | Path) -> str:
+ """Return the .dat path a layout is kept under.
+
+ That is its directory resolved (links followed before any .., as
+ the system opens it) and its name as given (the name decides whether the
+ reader opens one file or the CYCLE group).
+
+ Parameters
+ ----------
+ dat_path : str or Path
+ The recording's .dat path.
+
+ Returns
+ -------
+ str
+ The path with its directory resolved.
+ """
folder, name = os.path.split(os.fspath(dat_path))
return os.path.join(os.path.realpath(folder or os.curdir), name)
-def _layout_inputs(dat_path) -> tuple:
- """``(name, size, modification time)`` of every file the reader of
- ``dat_path`` opens, as ``slap2_utils`` finds them: the ``.dat`` file or,
- for a CYCLE-split recording, every segment of its group (the ``.dat``
- files of its directory whose names start with its stem), and the
- metadata file of each (``.meta``); a
- missing file has size and time None."""
+def _layout_inputs(dat_path: str | Path) -> tuple:
+ """Return (name, size, modification time) of every file the reader opens.
+
+ These are the files the reader of dat_path opens, as slap2_utils
+ finds them: the .dat file or, for a CYCLE-split recording, every
+ segment of its group (the .dat files of its directory whose names
+ start with its stem), and the metadata file of each (.meta); a missing file has size and time None.
+
+ Parameters
+ ----------
+ dat_path : str or Path
+ The recording's .dat path.
+
+ Returns
+ -------
+ tuple of tuple
+ (name, size, modification time) of each file, sorted by name.
+ """
import re
from ...io.slap2 import is_cycle_split
@@ -1638,13 +2103,12 @@ def _layout_inputs(dat_path) -> tuple:
names = [
f
for f in os.listdir(folder)
- if f.lower().endswith(".dat")
- and os.path.splitext(f)[0].startswith(group)
+ if f.lower().endswith(".dat") and os.path.splitext(f)[0].startswith(group)
]
metas = set()
for f in names:
- base = re.sub(r"-TRIAL\d+", "", os.path.splitext(f)[0], flags=re.I)
- metas.add(re.sub(r"-CYCLE-?\d+", "", base, flags=re.I) + ".meta")
+ base = re.sub(r"-TRIAL\d+", "", os.path.splitext(f)[0], flags=re.IGNORECASE)
+ metas.add(re.sub(r"-CYCLE-?\d+", "", base, flags=re.IGNORECASE) + ".meta")
out = []
for f in sorted(set(names) | metas):
try:
@@ -1655,12 +2119,13 @@ def _layout_inputs(dat_path) -> tuple:
return tuple(out)
-def recording_layout(dat_path) -> RasterLayout:
- """:func:`~giant_python.io.slap2_raster.raster_layout` of a recording,
- read once per recording.
+def recording_layout(dat_path: str | Path) -> RasterLayout:
+ """Return :func:`~giant_python.io.slap2_raster.raster_layout` of a recording.
+
+ The layout is read once per recording.
The trials of a continuous (CYCLE-split) recording are line ranges of
- the same ``.dat`` file, and reading its layout opens every file of the
+ the same .dat file, and reading its layout opens every file of the
recording and parses its metadata: tens of seconds per trial on a
network mount, the same for every trial. The layout is kept for the
last few recordings, keyed by the path (its directory resolved, its
@@ -1671,8 +2136,18 @@ def recording_layout(dat_path) -> RasterLayout:
or removed file is read again. One reader at a time, so concurrent
loads of one recording read it once. The layout is read through that
absolute path, so its file names do not depend on the working
- directory. A ``.dat`` file that cannot be found is read every time (the
+ directory. A .dat file that cannot be found is read every time (the
reader reports it).
+
+ Parameters
+ ----------
+ dat_path : str or Path
+ The recording's .dat file.
+
+ Returns
+ -------
+ RasterLayout
+ The recording's layout, from the cache when the files are unchanged.
"""
if not os.path.isfile(dat_path):
return raster_layout(dat_path) # the reader reports it
@@ -1697,48 +2172,59 @@ def recording_layout(dat_path) -> RasterLayout:
def _check_layout(layout: RasterLayout) -> None:
- """Reject recordings that the loader does not support."""
+ """Reject recordings that the loader does not support.
+
+ Parameters
+ ----------
+ layout : RasterLayout
+ The recording's layout.
+
+ Raises
+ ------
+ ValueError
+ If the recording has several fast-z planes.
+ """
if layout.fast_zs.size != 1:
raise ValueError("only single-plane acquisitions are supported")
-def load_trial( # noqa: C901
- dat_path,
+def load_trial(
+ dat_path: str | Path,
first_line: float,
last_line: float,
- alignment,
+ alignment: TrialAlignment | str | Path,
sel_pix: np.ndarray,
warp: Callable,
- discard_frames,
+ discard_frames: npt.ArrayLike,
mean_image: np.ndarray,
roi_masks: Sequence[np.ndarray] = (),
- params: Optional[TrialLoadParams] = None,
- device="cpu",
- dtype=np.float32,
+ params: TrialLoadParams | None = None,
+ device: str | torch.device = "cpu",
+ dtype: npt.DTypeLike = np.float32,
) -> TrialData:
- """Read one SLAP2 trial at the selected pixels (``loadTrial``).
+ """Read one SLAP2 trial at the selected pixels (loadTrial).
Parameters
----------
dat_path : str or Path
- The trial's raw ``.dat`` file.
+ The trial's raw .dat file.
first_line, last_line : float
- One-based line range of the trial (trial table ``first_line`` and
- ``last_line``; may be fractional).
+ One-based line range of the trial (trial table first_line and
+ last_line; may be fractional).
alignment : TrialAlignment, str or Path
The trial's alignment, or its ``*_ALIGNMENTDATA.h5``.
sel_pix : ndarray of bool
- ``(rows, cols)`` selected pixels of the path, in the consensus
+ (rows, cols) selected pixels of the path, in the consensus
frame. The trial's registered frame shares its top left corner; a
selected pixel beyond it is read where the warp puts it (and is
without samples, hence filled in, if that is off the raster).
warp : RigidShift or callable
- The trial's warp: ``warp(rows, cols)`` gives the zero-based position
+ The trial's warp: warp(rows, cols) gives the zero-based position
in the trial's registered frame of zero-based consensus points.
discard_frames : array_like of bool
Registered frames discarded for motion (from localization).
mean_image : ndarray
- ``(rows, cols, channels)`` mean image of the trial aligned to the
+ (rows, cols, channels) mean image of the trial aligned to the
consensus frame, in the file's channel order (labeled pixels and
the traces' normalization).
roi_masks : sequence of ndarray of bool
@@ -1748,7 +2234,7 @@ def load_trial( # noqa: C901
device : str or torch.device
Where frames are formed and interpolated.
dtype : numpy dtype
- Precision of ``y`` and ``finv`` (float64 reproduces MATLAB to
+ Precision of y and finv (float64 reproduces MATLAB to
rounding error; float32 halves the memory).
Returns
@@ -1779,12 +2265,12 @@ def load_trial( # noqa: C901
raise ValueError(f"the mean image must have {n_ch} channels")
line_rate = 1.0 / layout.line_period_s
dt = line_rate / p.analyze_hz
- dtk = int(math.ceil(dt))
+ dtk = math.ceil(dt)
lines = frame_lines(float(first_line), float(last_line), dt)
n_f = lines.size
ds = alignment.ds_frames
- kernel = max(int(math.ceil(line_rate / alignment.align_hz)), dtk)
+ kernel = max(math.ceil(line_rate / alignment.align_hz), dtk)
comp, mot_r, mot_c = online_compensation(
alignment,
layout,
@@ -1864,9 +2350,7 @@ def load_trial( # noqa: C901
pixel_rc = np.stack([rows_s, cols_s], 1)
r_t, c_t = warp(rows_s.astype(np.float64), cols_s.astype(np.float64))
q_idx = qpos[rows_s, cols_s]
- q_sp = _mean_bilinear_q(
- r_d[q_idx], c_d[q_idx], motion_r, motion_c, ~discard
- )
+ q_sp = _mean_bilinear_q(r_d[q_idx], c_d[q_idx], motion_r, motion_c, ~discard)
return TrialData(
y=y,
finv=finv,
diff --git a/src/giant_python/extraction/raster/wmf.py b/src/giant_python/extraction/raster/wmf.py
index ca549606..09c1d2eb 100644
--- a/src/giant_python/extraction/raster/wmf.py
+++ b/src/giant_python/extraction/raster/wmf.py
@@ -1,6 +1,6 @@
"""Source seeds from whitened matched filtering of aligned raster trials.
-Port of GIAnT-MATLAB's ``findSourcesWMF.m`` at ``e61873b``. The input is
+Port of GIAnT-MATLAB's findSourcesWMF.m at e61873b. The input is
(trials, rows, columns) with NaN outside each trial's imaged area. All
positions, including anchors, are zero-based [row, column]. Ties in peak
strength follow MATLAB's column-major search order.
@@ -17,6 +17,7 @@
from dataclasses import dataclass
import numpy as np
+import numpy.typing as npt
from scipy import ndimage, sparse
from scipy.fft import fft2, ifft2
from scipy.sparse.linalg import spsolve
@@ -71,18 +72,24 @@ def find_sources_wmf(
info : dict
Full-data images Z and F, source kernel K, noise autocorrelation R
and per-seed value, n_trials and added (by deblending).
+
+ Raises
+ ------
+ ValueError
+ If act_t is not three-dimensional, a threshold is NaN or negative,
+ or exclude_mask does not match the trial image shape.
"""
act_t = np.asarray(act_t)
if act_t.ndim != 3:
raise ValueError("act_t must have shape (trials, rows, columns)")
# a NaN threshold compares false everywhere and would silently switch
# a test off; only wmf_deblend_th may be infinite (no deblending)
- given = dict(
- wmf_peak_th=wmf_peak_th,
- wmf_dip=wmf_dip,
- wmf_deblend_th=wmf_deblend_th,
- nan_thresh=nan_thresh,
- )
+ given = {
+ "wmf_peak_th": wmf_peak_th,
+ "wmf_dip": wmf_dip,
+ "wmf_deblend_th": wmf_deblend_th,
+ "nan_thresh": nan_thresh,
+ }
for name, value in given.items():
if not value >= 0:
raise ValueError(f"{name} must be nonnegative, not {value!r}")
@@ -110,10 +117,7 @@ def find_sources_wmf(
z = _combine_trials(z_t, nan_thresh)
f, k, r, flt = _wmf_image(z)
zh = (
- tuple(
- _combine_trials(z_t[ids], nan_thresh)
- for ids in (imaged[::2], imaged[1::2])
- )
+ tuple(_combine_trials(z_t[ids], nan_thresh) for ids in (imaged[::2], imaged[1::2]))
if use_halves
else ()
)
@@ -143,13 +147,27 @@ def find_sources_wmf(
seeds, values, counts, added = _finish_seeds(
seeds, values, added, anchors, z, z_a, mask, min_trials
)
- return seeds, dict(
- Z=z, F=f, K=k, R=r, value=values, n_trials=counts, added=added
- )
+ return seeds, {
+ "Z": z,
+ "F": f,
+ "K": k,
+ "R": r,
+ "value": values,
+ "n_trials": counts,
+ "added": added,
+ }
-def _trial_images(act_t):
- """Return per-trial robust z images and neighbourhood activity (zT, zA)."""
+def _trial_images(act_t: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Return per-trial robust z images and neighbourhood activity (zT, zA).
+
+ Returns
+ -------
+ z_t : np.ndarray
+ Per-trial robust z images, NaN for unmeasured trials.
+ z_a : np.ndarray
+ Per-trial maximum over the 3 x 3 neighbourhood of the smoothed z image.
+ """
z_t = np.full(act_t.shape, np.nan)
z_a = np.full(act_t.shape, -np.inf)
dy, dx = np.mgrid[-3:4, -3:4]
@@ -167,8 +185,14 @@ def _trial_images(act_t):
return z_t, z_a
-def _combine_trials(z_t, nan_thresh):
- """Robustly standardize the trial mean after the missing-coverage cut."""
+def _combine_trials(z_t: np.ndarray, nan_thresh: float) -> np.ndarray:
+ """Robustly standardize the trial mean after the missing-coverage cut.
+
+ Returns
+ -------
+ np.ndarray
+ Standardized trial-mean image, NaN where too many trials are missing.
+ """
measured = ~np.isnan(z_t)
n = measured.sum(axis=0)
sums = np.sum(z_t, axis=0, where=measured, initial=0.0)
@@ -178,15 +202,27 @@ def _combine_trials(z_t, nan_thresh):
return _robust_z(mean)
-def _robust_z(a):
- """Standardize the measured pixels by their median and robust scale."""
+def _robust_z(a: np.ndarray) -> np.ndarray:
+ """Standardize the measured pixels by their median and robust scale.
+
+ Returns
+ -------
+ np.ndarray
+ The image minus its median, divided by its robust scale.
+ """
v = a[~np.isnan(a)]
med = np.median(v) if v.size else np.nan
return (a - med) / _robust_scale(v)
-def _robust_scale(v):
- """Return the MAD scale with sample SD and unit-scale fallbacks."""
+def _robust_scale(v: np.ndarray) -> float:
+ """Return the MAD scale with sample SD and unit-scale fallbacks.
+
+ Returns
+ -------
+ float
+ The scaled median absolute deviation, or the sample SD, or 1.0.
+ """
if v.size < 2:
return 1.0
s = np.median(np.abs(v - np.median(v))) / _MAD_SCALE
@@ -195,8 +231,14 @@ def _robust_scale(v):
return s if s > 0 else 1.0
-def _filt_nan(a, k):
- """Correlate with zero padding, normalizing by the measured weights."""
+def _filt_nan(a: np.ndarray, k: np.ndarray) -> np.ndarray:
+ """Correlate with zero padding, normalizing by the measured weights.
+
+ Returns
+ -------
+ np.ndarray
+ The filtered image, NaN where a is unmeasured.
+ """
measured = ~np.isnan(a)
weights = ndimage.correlate(measured.astype(float), k, mode="constant")
values = ndimage.correlate(np.where(measured, a, 0), k, mode="constant")
@@ -204,8 +246,20 @@ def _filt_nan(a, k):
return np.divide(values, weights, out=out, where=measured)
-def _wmf_image(z):
- """Return F, K, R and the normalized frequency-domain filter for Z."""
+def _wmf_image(z: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, _Filter]:
+ """Return F, K, R and the normalized frequency-domain filter for Z.
+
+ Returns
+ -------
+ f : np.ndarray
+ Normalized matched-filter image.
+ k : np.ndarray
+ Source kernel.
+ r : np.ndarray
+ Noise autocorrelation.
+ flt : _Filter
+ Normalized frequency-domain filter.
+ """
khw, ahw = 4, 7
k = _source_kernel(z, khw)
active = ndimage.binary_dilation(z > 3, structure=disk_strel(3))
@@ -240,8 +294,20 @@ def _wmf_image(z):
return (f - flt.med) / flt.sc, k, r, flt
-def _patch_centroid(weights, rows, cols, fallback):
- """Return the weighted patch centre, or the fallback for zero mass."""
+def _patch_centroid(
+ weights: np.ndarray,
+ rows: np.ndarray,
+ cols: np.ndarray,
+ fallback: tuple[float, float],
+) -> tuple[float, float]:
+ """Return the weighted patch centre, or the fallback for zero mass.
+
+ Returns
+ -------
+ tuple[float, float]
+ Zero-based (row, column) centroid, or fallback when the weights sum
+ to zero.
+ """
# MATLAB sums these at most nine terms in column-major sequence, in
# one-based coordinates. NumPy sum may use a different reduction tree.
moments = (weights, weights * (rows[:, None] + 1), weights * (cols + 1))
@@ -251,8 +317,14 @@ def _patch_centroid(weights, rows, cols, fallback):
return fallback
-def _kernel_patch(z, row, col, x, y):
- """Sample the patch around a strong maximum at its weighted centroid."""
+def _kernel_patch(z: np.ndarray, row: int, col: int, x: np.ndarray, y: np.ndarray) -> np.ndarray:
+ """Sample the patch around a strong maximum at its weighted centroid.
+
+ Returns
+ -------
+ np.ndarray
+ The interpolated patch on the (y, x) offset grid.
+ """
rr = np.arange(row - 1, row + 2)
cc = np.arange(col - 1, col + 2)
w = z[np.ix_(rr, cc)]
@@ -261,8 +333,14 @@ def _kernel_patch(z, row, col, x, y):
return interp2_linear(z, y + cy, x + cx)
-def _source_kernel(z, hw):
- """Estimate a source patch from isolated maxima or Gaussian widths."""
+def _source_kernel(z: np.ndarray, hw: int) -> np.ndarray:
+ """Estimate a source patch from isolated maxima or Gaussian widths.
+
+ Returns
+ -------
+ np.ndarray
+ The kernel, normalized to unit sum, of shape (2 * hw + 1, 2 * hw + 1).
+ """
h, w = z.shape
axis = np.arange(-hw, hw + 1)
x, y = np.meshgrid(axis, axis)
@@ -271,9 +349,7 @@ def _source_kernel(z, hw):
cols, rows = np.nonzero(is_max.T)
v = e[rows, cols]
dy, dx = np.mgrid[-6:7, -6:7]
- near = ndimage.correlate(
- is_max.astype(np.uint8), np.hypot(dx, dy) <= 6, mode="constant"
- )
+ near = ndimage.correlate(is_max.astype(np.uint8), np.hypot(dx, dy) <= 6, mode="constant")
# MATLAB's strict 1-based interval (hw + 1, H - hw - 1).
use = (
(near[rows, cols] == 1)
@@ -302,15 +378,28 @@ def _source_kernel(z, hw):
return k / k.sum()
-def _finish_kernel(k, x, y, hw):
- """Subtract the border median, impose half-turn symmetry and truncate."""
+def _finish_kernel(k: np.ndarray, x: np.ndarray, y: np.ndarray, hw: int) -> np.ndarray:
+ """Subtract the border median, impose half-turn symmetry and truncate.
+
+ Returns
+ -------
+ np.ndarray
+ The symmetrized kernel, zero outside radius hw + 0.5.
+ """
# Concatenating all four edges counts each corner twice.
k = k - np.median(np.r_[k[0], k[-1], k[:, 0], k[:, -1]])
return (k + k[::-1, ::-1]) / 2 * (np.hypot(x, y) <= hw + 0.5)
-def _peak_widths(z):
- """Estimate Gaussian row and column widths from strong peak curvature."""
+def _peak_widths(z: np.ndarray) -> tuple[float, float] | np.ndarray:
+ """Estimate Gaussian row and column widths from strong peak curvature.
+
+ Returns
+ -------
+ tuple[float, float] or np.ndarray
+ Row and column widths, clipped to [0.4, 3]; (1.0, 1.0) when fewer than
+ five valid peaks are found.
+ """
e = np.where(np.isnan(z), -np.inf, z)
is_max = (e == ordfilt3x3(e, 9)) & (e > 10)
r, c = np.nonzero(is_max[1:-1, 1:-1])
@@ -327,16 +416,28 @@ def _peak_widths(z):
return np.clip(np.median(widths, axis=1), 0.4, 3)
-def _apply_filt(flt, z):
- """Apply an existing whitened matched filter and its normalization."""
+def _apply_filt(flt: _Filter, z: np.ndarray) -> np.ndarray:
+ """Apply an existing whitened matched filter and its normalization.
+
+ Returns
+ -------
+ np.ndarray
+ The normalized filtered image, NaN where z is unmeasured.
+ """
measured = ~np.isnan(z)
transformed = fft2(np.where(measured, z, 0), s=flt.nf)
f = ifft2(transformed * flt.ks).real[: z.shape[0], : z.shape[1]]
return np.where(measured, (f - flt.med) / flt.sc, np.nan)
-def _half_norm(flt, zh):
- """Normalize the full-data filter on a half's combined image."""
+def _half_norm(flt: _Filter, zh: np.ndarray) -> _Filter:
+ """Normalize the full-data filter on a half's combined image.
+
+ Returns
+ -------
+ _Filter
+ A copy of the filter with the half image's median and scale.
+ """
fl = _Filter(flt.ks, flt.nf, 0.0, 1.0)
f = _apply_filt(fl, zh)
values = f[~np.isnan(f)]
@@ -345,8 +446,20 @@ def _half_norm(flt, zh):
return fl
-def _candidates(f, z_a, exclude_mask, peak_th, min_trials):
- """Return eligible maxima as sorted zero-based [row, column, value]."""
+def _candidates(
+ f: np.ndarray,
+ z_a: np.ndarray,
+ exclude_mask: np.ndarray,
+ peak_th: float,
+ min_trials: int,
+) -> np.ndarray:
+ """Return eligible maxima as sorted zero-based [row, column, value].
+
+ Returns
+ -------
+ np.ndarray
+ Array of shape (n, 3), strongest first.
+ """
e = np.where(np.isnan(f), -np.inf, f)
maxima = (e == ordfilt3x3(e, 9)) & (e > peak_th)
cols, rows = np.nonzero(maxima.T) # MATLAB find visits columns first.
@@ -354,13 +467,24 @@ def _candidates(f, z_a, exclude_mask, peak_th, min_trials):
ok = ~exclude_mask[rows, cols] & (active >= min_trials)
rows, cols = rows[ok], cols[ok]
values = e[rows, cols]
- return np.column_stack((rows, cols, values))[
- np.argsort(-values, kind="stable")
- ]
+ return np.column_stack((rows, cols, values))[np.argsort(-values, kind="stable")]
-def _resolved(weak, strong, distance, f, fh, dip):
- """Check the dip between two maxima in the full image and both halves."""
+def _resolved(
+ weak: np.ndarray,
+ strong: np.ndarray,
+ distance: float,
+ f: np.ndarray,
+ fh: tuple[np.ndarray, ...],
+ dip: float,
+) -> bool:
+ """Check the dip between two maxima in the full image and both halves.
+
+ Returns
+ -------
+ bool
+ True if the dip is deep enough in every available image.
+ """
t = np.linspace(0, 1, max(3, int(np.ceil(4 * distance))))
rows = weak[0] + t * (strong[0] - weak[0])
cols = weak[1] + t * (strong[1] - weak[1])
@@ -378,8 +502,16 @@ def _resolved(weak, strong, distance, f, fh, dip):
return True
-def _keep_candidates(cand, f, fh, dip):
- """Keep separate maxima only if every available image resolves them."""
+def _keep_candidates(
+ cand: np.ndarray, f: np.ndarray, fh: tuple[np.ndarray, ...], dip: float
+) -> np.ndarray:
+ """Keep separate maxima only if every available image resolves them.
+
+ Returns
+ -------
+ np.ndarray
+ The retained rows of cand.
+ """
keep = np.ones(len(cand), dtype=bool)
for i, weak in enumerate(cand):
distances = np.hypot(cand[:i, 0] - weak[0], cand[:i, 1] - weak[1])
@@ -390,8 +522,14 @@ def _keep_candidates(cand, f, fh, dip):
return cand[keep]
-def _centroids(z, kept):
- """Return the positive-Z centroids around the retained integer maxima."""
+def _centroids(z: np.ndarray, kept: np.ndarray) -> np.ndarray:
+ """Return the positive-Z centroids around the retained integer maxima.
+
+ Returns
+ -------
+ np.ndarray
+ Zero-based [row, column] centroids, shape (n, 2).
+ """
seeds = kept[:, :2].copy()
height, width = z.shape
for p, (r, c) in zip(seeds, seeds.astype(np.intp)):
@@ -402,8 +540,29 @@ def _centroids(z, kept):
return seeds
-def _finish_seeds(seeds, values, added, anchors, z, z_a, mask, min_trials):
- """Restore gap anchors, then check final activity and soma exclusion."""
+def _finish_seeds(
+ seeds: np.ndarray,
+ values: np.ndarray,
+ added: np.ndarray,
+ anchors: np.ndarray,
+ z: np.ndarray,
+ z_a: np.ndarray,
+ mask: np.ndarray,
+ min_trials: int,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Restore gap anchors, then check final activity and soma exclusion.
+
+ Returns
+ -------
+ seeds : np.ndarray
+ Surviving seed positions.
+ values : np.ndarray
+ Their peak values.
+ n_trials : np.ndarray
+ Number of trials with activity at each surviving seed.
+ added : np.ndarray
+ Boolean flags for seeds added by deblending.
+ """
rounded = matlab_round(seeds + 1).astype(np.intp) - 1
gap = np.isnan(z[tuple(rounded.T)])
seeds = seeds.copy()
@@ -415,8 +574,31 @@ def _finish_seeds(seeds, values, added, anchors, z, z_a, mask, min_trials):
return seeds[ok], values[ok], n_trials[ok], added[ok]
-def _deblend(z, zh, seeds, values, k, flt, th, merge_px, mask, anchors):
- """Fit source positions and add reproducible nearby residual maxima."""
+def _deblend(
+ z: np.ndarray,
+ zh: tuple[np.ndarray, ...],
+ seeds: np.ndarray,
+ values: np.ndarray,
+ k: np.ndarray,
+ flt: _Filter,
+ th: float,
+ merge_px: float,
+ mask: np.ndarray,
+ anchors: np.ndarray,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Fit source positions and add reproducible nearby residual maxima.
+
+ Returns
+ -------
+ p : np.ndarray
+ Fitted seed positions, strongest first.
+ values : np.ndarray
+ Their peak values.
+ added : np.ndarray
+ Boolean flags for seeds added by deblending.
+ anchors : np.ndarray
+ Integer anchor positions of the seeds.
+ """
max_shift, min_sep = 1.5, 1.0
hw = (k.shape[0] - 1) // 2
kg = CubicInterpolant(k)
@@ -430,15 +612,11 @@ def _deblend(z, zh, seeds, values, k, flt, th, merge_px, mask, anchors):
if any(np.isnan(h.med) for h in half_filters):
attempts = 0
for _ in range(attempts):
- point, value = _residual_peak(
- _apply_filt(flt, residual), p, merge_px, min_sep, rejected
- )
+ point, value = _residual_peak(_apply_filt(flt, residual), p, merge_px, min_sep, rejected)
if value < th:
break
if not all(
- _peak_near(
- _apply_filt(hflt, _residual_fixed(half, p, kg, hw)), point
- )
+ _peak_near(_apply_filt(hflt, _residual_fixed(half, p, kg, hw)), point)
>= th / np.sqrt(2)
for half, hflt in zip(zh, half_filters)
):
@@ -462,8 +640,22 @@ def _deblend(z, zh, seeds, values, k, flt, th, merge_px, mask, anchors):
return p[order], values[order], added[order], anchors[order]
-def _residual_peak(f, p, merge_px, min_sep, rejected):
- """Find the strongest residual maximum in the allowed annular region."""
+def _residual_peak(
+ f: np.ndarray,
+ p: np.ndarray,
+ merge_px: float,
+ min_sep: float,
+ rejected: np.ndarray,
+) -> tuple[tuple[int, ...], float]:
+ """Find the strongest residual maximum in the allowed annular region.
+
+ Returns
+ -------
+ point : tuple[int, ...]
+ Zero-based (row, column) of the maximum.
+ value : float
+ Filtered residual value at that point.
+ """
f = np.where(np.isnan(f), -np.inf, f)
f[f < ordfilt3x3(f, 9)] = -np.inf
distance = np.full(f.shape, np.inf)
@@ -480,8 +672,26 @@ def _residual_peak(f, p, merge_px, min_sep, rejected):
return point, f[point]
-def _fit_seeds(z, p, p0, kg, hw, valid, max_shift):
- """Fit amplitudes and bounded positions, then return the image residual."""
+def _fit_seeds(
+ z: np.ndarray,
+ p: np.ndarray,
+ p0: np.ndarray,
+ kg: CubicInterpolant,
+ hw: int,
+ valid: np.ndarray,
+ max_shift: float,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Fit amplitudes and bounded positions, then return the image residual.
+
+ Returns
+ -------
+ p : np.ndarray
+ Fitted positions.
+ amp : np.ndarray
+ Fitted amplitudes.
+ residual : np.ndarray
+ The image minus the fitted sources.
+ """
for _ in range(6):
a, pix = _design(p, kg, hw, *z.shape, valid, deriv=True)
x = _ridge_ls(a, z.T.flat[pix]).reshape(-1, 3)
@@ -496,13 +706,29 @@ def _fit_seeds(z, p, p0, kg, hw, valid, max_shift):
return p, amp, residual
-def _residual_fixed(z, p, kg, hw):
- """Fit amplitudes at fixed positions and return the residual."""
+def _residual_fixed(z: np.ndarray, p: np.ndarray, kg: CubicInterpolant, hw: int) -> np.ndarray:
+ """Fit amplitudes at fixed positions and return the residual.
+
+ Returns
+ -------
+ np.ndarray
+ The image minus the fitted sources.
+ """
return _fit_amplitudes(z, p, kg, hw, ~np.isnan(z))[1]
-def _fit_amplitudes(z, p, kg, hw, valid):
- """Return ridge amplitudes and the image minus the fitted sources."""
+def _fit_amplitudes(
+ z: np.ndarray, p: np.ndarray, kg: CubicInterpolant, hw: int, valid: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """Return ridge amplitudes and the image minus the fitted sources.
+
+ Returns
+ -------
+ amp : np.ndarray
+ Ridge-regularized source amplitudes.
+ residual : np.ndarray
+ The image minus the fitted sources.
+ """
a, pix = _design(p, kg, hw, *z.shape, valid, deriv=False)
obs = z.T.flat[pix]
amp = _ridge_ls(a, obs)
@@ -511,8 +737,14 @@ def _fit_amplitudes(z, p, kg, hw, valid):
return amp, residual
-def _ridge_ls(a, z):
- """Solve the ridge-regularized sparse normal equations."""
+def _ridge_ls(a: sparse.csc_matrix, z: np.ndarray) -> np.ndarray:
+ """Solve the ridge-regularized sparse normal equations.
+
+ Returns
+ -------
+ np.ndarray
+ The least-squares solution, one value per column of a.
+ """
if not a.nnz:
return np.zeros(a.shape[1])
gram = (a.T @ a).tocsc()
@@ -521,17 +753,31 @@ def _ridge_ls(a, z):
return spsolve(gram, a.T @ z)
-def _design(p, kg, hw, height, width, valid, deriv):
- """Build the sparse source design and its column-major pixel list."""
+def _design(
+ p: np.ndarray,
+ kg: CubicInterpolant,
+ hw: int,
+ height: int,
+ width: int,
+ valid: np.ndarray,
+ deriv: bool,
+) -> tuple[sparse.csc_matrix, np.ndarray]:
+ """Build the sparse source design and its column-major pixel list.
+
+ Returns
+ -------
+ a : scipy.sparse.csc_matrix
+ Sparse design matrix, one column per source (and per derivative).
+ pix : np.ndarray
+ Sorted column-major linear indices of the pixels in the fitted patches.
+ """
# List the pixels in each fitted patch in MATLAB's column-major order.
offsets = np.arange(-hw, hw + 1)
dc, dr = np.meshgrid(offsets, offsets, indexing="ij")
centers = matlab_round(p + 1).astype(np.intp) - 1
rows = centers[:, 0, None] + dr.ravel()
cols = centers[:, 1, None] + dc.ravel()
- seed, offset = np.nonzero(
- (rows >= 0) & (rows < height) & (cols >= 0) & (cols < width)
- )
+ seed, offset = np.nonzero((rows >= 0) & (rows < height) & (cols >= 0) & (cols < width))
rows, cols = rows[seed, offset], cols[seed, offset]
measured = valid[rows, cols]
rows, cols, seed = rows[measured], cols[measured], seed[measured]
@@ -540,12 +786,8 @@ def _design(p, kg, hw, height, width, valid, deriv):
samples = [_nan_to_zero(kg(y, x))]
if deriv:
e = 0.25
- ky = (_nan_to_zero(kg(y + e, x)) - _nan_to_zero(kg(y - e, x))) / (
- 2 * e
- )
- kx = (_nan_to_zero(kg(y, x + e)) - _nan_to_zero(kg(y, x - e))) / (
- 2 * e
- )
+ ky = (_nan_to_zero(kg(y + e, x)) - _nan_to_zero(kg(y - e, x))) / (2 * e)
+ kx = (_nan_to_zero(kg(y, x + e)) - _nan_to_zero(kg(y, x - e))) / (2 * e)
samples.extend((ky, kx))
pix, indices = np.unique(rows + height * cols, return_inverse=True)
nb = len(samples)
@@ -559,13 +801,25 @@ def _design(p, kg, hw, height, width, valid, deriv):
return a, pix
-def _nan_to_zero(x):
- """Replace NaNs by zero in interpolated source samples."""
+def _nan_to_zero(x: np.ndarray) -> np.ndarray:
+ """Replace NaNs by zero in interpolated source samples.
+
+ Returns
+ -------
+ np.ndarray
+ The samples with NaNs set to zero.
+ """
return np.where(np.isnan(x), 0, x)
-def _window3(p, shape):
- """Slices for the image's 3 x 3 neighbourhood around a rounded point."""
+def _window3(p: npt.ArrayLike, shape: tuple[int, ...]) -> tuple[slice, slice]:
+ """Slices for the image's 3 x 3 neighbourhood around a rounded point.
+
+ Returns
+ -------
+ tuple[slice, slice]
+ Row and column slices clipped to the image.
+ """
r, c = matlab_round(np.asarray(p) + 1).astype(np.intp) - 1
return (
slice(max(r - 1, 0), max(0, min(r + 2, shape[0]))),
@@ -573,6 +827,12 @@ def _window3(p, shape):
)
-def _peak_near(f, p):
- """Return the largest measured value in a clipped 3 x 3 neighbourhood."""
+def _peak_near(f: np.ndarray, p: npt.ArrayLike) -> float:
+ """Return the largest measured value in a clipped 3 x 3 neighbourhood.
+
+ Returns
+ -------
+ float
+ The largest non-NaN value, or -inf if there is none.
+ """
return np.fmax.reduce(f[_window3(p, f.shape)].ravel(), initial=-np.inf)
diff --git a/src/giant_python/gui/parameters_gui.py b/src/giant_python/gui/parameters_gui.py
index 1fc463b2..59c4b0b7 100644
--- a/src/giant_python/gui/parameters_gui.py
+++ b/src/giant_python/gui/parameters_gui.py
@@ -1,7 +1,6 @@
"""Existing tkinter BandSILo parameter form, with lazy toolkit imports."""
from dataclasses import asdict, replace
-from typing import Optional
import numpy as np
@@ -34,11 +33,17 @@ def run_parameter_gui(
*,
execution: ExecutionInput = None,
annotations: AnnotationInput = None,
-) -> Optional[tuple[BandSiloParams, ExecutionOptions, AnnotationOptions]]:
+) -> tuple[BandSiloParams, ExecutionOptions, AnnotationOptions] | None:
"""Return split option objects, or None on cancellation, without mutation.
Retains the original form and natural-log sparse-factor control. Toolkit
code is imported only when this function is actually invoked.
+
+ Returns
+ -------
+ tuple[BandSiloParams, ExecutionOptions, AnnotationOptions] or None
+ The edited band parameters, execution options and annotation options (new instances,
+ the inputs are not mutated), or None if the dialog was closed without confirming.
"""
import tkinter as tk
from tkinter import messagebox, ttk
@@ -57,9 +62,7 @@ def run_parameter_gui(
ttk.Entry(frame, textvariable=var, width=15).grid(row=row, column=1)
entries[attr] = var
row += 1
- ttk.Label(frame, text="Sparse Factor (log):").grid(
- row=row, column=0, sticky=tk.W
- )
+ ttk.Label(frame, text="Sparse Factor (log):").grid(row=row, column=0, sticky=tk.W)
sparse_var = tk.StringVar(value=str(float(np.log(base.sparse_fac))))
ttk.Entry(frame, textvariable=sparse_var, width=15).grid(row=row, column=1)
row += 1
@@ -78,24 +81,20 @@ def run_parameter_gui(
ttk.Entry(frame, textvariable=var, width=15).grid(row=row, column=1)
entries[attr] = var
row += 1
- ttk.Label(frame, text="Debias Convolution Traces?").grid(
- row=row, column=0, sticky=tk.W
- )
+ ttk.Label(frame, text="Debias Convolution Traces?").grid(row=row, column=0, sticky=tk.W)
debias_var = tk.BooleanVar(value=base.trace_debias)
ttk.Checkbutton(frame, variable=debias_var).grid(row=row, column=1)
row += 1
- ttk.Label(frame, text="Draw User ROIs?").grid(
- row=row, column=0, sticky=tk.W
- )
+ ttk.Label(frame, text="Draw User ROIs?").grid(row=row, column=0, sticky=tk.W)
draw_rois_var = tk.BooleanVar(value=roi.enabled)
ttk.Checkbutton(frame, variable=draw_rois_var).grid(row=row, column=1)
row += 1
result: dict[
str,
- Optional[tuple[BandSiloParams, ExecutionOptions, AnnotationOptions]],
+ tuple[BandSiloParams, ExecutionOptions, AnnotationOptions] | None,
] = {"options": None}
- def on_ok():
+ def on_ok() -> None:
"""Validate controls and return a replacement parameter instance."""
try:
updates = {
@@ -109,14 +108,10 @@ def on_ok():
"peak_buffer": int(entries["peak_buffer"].get()),
"z_tol": float(entries["z_tol"].get()),
"sparse_fac": float(np.exp(float(sparse_var.get()))),
- "trace_beta_fraction": float(
- entries["trace_beta_fraction"].get()
- ),
+ "trace_beta_fraction": float(entries["trace_beta_fraction"].get()),
"trace_max_iter": int(entries["trace_max_iter"].get()),
"trace_tolerance": float(entries["trace_tolerance"].get()),
- "trace_event_threshold": float(
- entries["trace_event_threshold"].get()
- ),
+ "trace_event_threshold": float(entries["trace_event_threshold"].get()),
"trace_debias": bool(debias_var.get()),
}
result["options"] = (
@@ -128,16 +123,14 @@ def on_ok():
except ValueError as error:
messagebox.showerror("Error", f"Invalid parameter values: {error}")
- def on_cancel():
+ def on_cancel() -> None:
"""Discard edits and close the dialog."""
root.destroy()
button_frame = ttk.Frame(frame)
button_frame.grid(row=row, column=0, columnspan=2, pady=10)
ttk.Button(button_frame, text="OK", command=on_ok).pack(side=tk.LEFT)
- ttk.Button(button_frame, text="Cancel", command=on_cancel).pack(
- side=tk.LEFT
- )
+ ttk.Button(button_frame, text="Cancel", command=on_cancel).pack(side=tk.LEFT)
root.grab_set()
root.mainloop()
return result["options"]
diff --git a/src/giant_python/gui/roi_editor.py b/src/giant_python/gui/roi_editor.py
index abd5995c..382fc45c 100644
--- a/src/giant_python/gui/roi_editor.py
+++ b/src/giant_python/gui/roi_editor.py
@@ -4,6 +4,8 @@
There is no file IO here, and tkinter/cv2 are imported only on drawing paths.
"""
+from types import ModuleType
+
import numpy as np
from ..extraction.band.rois import user_roi_superpixel_lists_from_masks
@@ -14,7 +16,14 @@ def _ask_roi_label(
path_num: int,
plane_num: int,
) -> str:
- """Prompt for one ROI label, defaulting to ROI{n} on cancel or failure."""
+ """Prompt for one ROI label, defaulting to ROI{n} on cancel or failure.
+
+ Returns
+ -------
+ str
+ The stripped label the user typed, or ROI{roi_num} when the prompt
+ is cancelled, left blank or fails.
+ """
import tkinter as tk
from tkinter import simpledialog
@@ -25,8 +34,7 @@ def _ask_roi_label(
root.attributes("-topmost", True)
text = simpledialog.askstring(
"ROI label",
- f"Label for ROI {roi_num} "
- f"(Path {path_num}, fast-Z plane {plane_num}):",
+ f"Label for ROI {roi_num} (Path {path_num}, fast-Z plane {plane_num}):",
parent=root,
)
root.destroy()
@@ -38,7 +46,15 @@ def _ask_roi_label(
def run_user_roi_selection(user_roi_geo: dict, n_dmds: int) -> dict:
- """Select ROIs on reference images and return per-DMD selections."""
+ """Select ROIs on reference images and return per-DMD selections.
+
+ Returns
+ -------
+ dict
+ Keys user_roi_masks, user_roi_superpixels, user_roi_labels and
+ roi_records, each a dict keyed by "DMD" holding that DMD's
+ selected masks, superpixel lists, labels and ROI records.
+ """
import cv2
out = {
@@ -52,14 +68,10 @@ def run_user_roi_selection(user_roi_geo: dict, n_dmds: int) -> dict:
geo = user_roi_geo[key]
roi_masks, roi_records = _select_rois_for_dmd(cv2, dmd_ix, geo)
out["user_roi_masks"][key] = roi_masks
- out["user_roi_superpixels"][key] = (
- user_roi_superpixel_lists_from_masks(
- roi_masks, geo["sp_fastz"], geo["sp_rows"], geo["sp_cols"]
- )
+ out["user_roi_superpixels"][key] = user_roi_superpixel_lists_from_masks(
+ roi_masks, geo["sp_fastz"], geo["sp_rows"], geo["sp_cols"]
)
- out["user_roi_labels"][key] = [
- record["label"] for record in roi_records
- ]
+ out["user_roi_labels"][key] = [record["label"] for record in roi_records]
out["roi_records"][key] = roi_records
return out
@@ -67,7 +79,13 @@ def run_user_roi_selection(user_roi_geo: dict, n_dmds: int) -> dict:
def _normalize_plane(
plane: np.ndarray,
) -> np.ndarray:
- """Percentile-normalize a reference plane to an 8-bit image."""
+ """Percentile-normalize a reference plane to an 8-bit image.
+
+ Returns
+ -------
+ np.ndarray
+ The plane scaled between its 1st and 99.5th percentiles, as uint8.
+ """
im = np.nan_to_num(plane, nan=0.0)
vmin = np.percentile(im, 1)
vmax = np.percentile(im, 99.5)
@@ -81,8 +99,18 @@ def _normalize_plane(
return (im8 * 255).astype(np.uint8)
-def _select_rois_for_dmd(cv2, dmd_ix: int, g: dict):
- """Run the per-DMD interactive loop, returning masks and records."""
+def _select_rois_for_dmd(
+ cv2: ModuleType, dmd_ix: int, g: dict
+) -> tuple[list[np.ndarray], list[dict]]:
+ """Run the per-DMD interactive loop, returning masks and records.
+
+ Returns
+ -------
+ roi_masks : list of np.ndarray
+ One boolean mask per selected ROI, of shape ``(num_fast_z, *yx_shape)``.
+ roi_records : list of dict
+ One polygon record (type, label, position) per selected ROI.
+ """
ref = g["ref"]
num_ref_z = g["num_ref_z"]
yx_shape = g["yx_shape"]
@@ -102,11 +130,7 @@ def _select_rois_for_dmd(cv2, dmd_ix: int, g: dict):
curr_fz = 0
while True:
if has_z_trackbar:
- curr_fz = int(
- np.clip(
- cv2.getTrackbarPos("z", window_name), 0, num_fast_z - 1
- )
- )
+ curr_fz = int(np.clip(cv2.getTrackbarPos("z", window_name), 0, num_fast_z - 1))
refz = int(np.clip(z_map[curr_fz], 0, max(0, num_ref_z - 1)))
im8 = _normalize_plane(ref[best_ch, refz])
disp = _compose_display(cv2, im8, sp_mask[curr_fz], roi_union[curr_fz])
@@ -139,8 +163,16 @@ def _select_rois_for_dmd(cv2, dmd_ix: int, g: dict):
return roi_masks, roi_records
-def _compose_display(cv2, im8, sp_plane, roi_plane):
- """Overlay the superpixel mask in green and ROI union in red."""
+def _compose_display(
+ cv2: ModuleType, im8: np.ndarray, sp_plane: np.ndarray, roi_plane: np.ndarray
+) -> np.ndarray:
+ """Overlay the superpixel mask in green and ROI union in red.
+
+ Returns
+ -------
+ np.ndarray
+ The BGR display image.
+ """
disp = cv2.cvtColor(im8, cv2.COLOR_GRAY2BGR)
if np.any(sp_plane):
sp_color = np.zeros_like(disp)
@@ -154,25 +186,21 @@ def _compose_display(cv2, im8, sp_plane, roi_plane):
def _edit_rois(
- cv2,
- im8,
- sp_plane,
- curr_fz,
- dmd_ix,
- num_fast_z,
- yx_shape,
- roi_masks,
- roi_union,
- roi_records,
-):
+ cv2: ModuleType,
+ im8: np.ndarray,
+ sp_plane: np.ndarray,
+ curr_fz: int,
+ dmd_ix: int,
+ num_fast_z: int,
+ yx_shape: tuple[int, int],
+ roi_masks: list[np.ndarray],
+ roi_union: np.ndarray,
+ roi_records: list[dict],
+) -> None:
"""Append selected rectangles as polygon records and overlapping masks."""
edit_name = f"Edit ROIs z={curr_fz + 1}"
- edit_disp = _compose_display(
- cv2, im8, sp_plane, np.zeros(yx_shape, dtype=bool)
- )
- rois = cv2.selectROIs(
- edit_name, edit_disp, showCrosshair=True, fromCenter=False
- )
+ edit_disp = _compose_display(cv2, im8, sp_plane, np.zeros(yx_shape, dtype=bool))
+ rois = cv2.selectROIs(edit_name, edit_disp, showCrosshair=True, fromCenter=False)
cv2.resizeWindow(edit_name, 800, 500)
if rois is not None and len(rois) > 0:
for x, y, w, h in rois:
@@ -187,8 +215,6 @@ def _edit_rois(
[[y, x], [y, x + w], [y + h, x + w], [y + h, x]],
dtype=np.float64,
)
- roi_records.append(
- {"type": "polygon", "label": label, "position": position}
- )
+ roi_records.append({"type": "polygon", "label": label, "position": position})
print(f"Added {len(rois)} ROI(s) at fast-Z {curr_fz + 1}")
cv2.destroyWindow(edit_name)
diff --git a/src/giant_python/io/__init__.py b/src/giant_python/io/__init__.py
index ac643159..69686302 100644
--- a/src/giant_python/io/__init__.py
+++ b/src/giant_python/io/__init__.py
@@ -6,6 +6,7 @@
transposition when porting from MATLAB.
"""
+from collections.abc import Callable
from importlib import import_module
from typing import TYPE_CHECKING
@@ -34,8 +35,20 @@
}
-def __getattr__(name):
- """Load model codecs lazily, avoiding schema/model import cycles."""
+def __getattr__(name: str) -> Callable[..., object]:
+ """Load model codecs lazily, avoiding schema/model import cycles.
+
+ Returns
+ -------
+ Callable[..., object]
+ The codec function named name, imported from its submodule and cached in the
+ module namespace.
+
+ Raises
+ ------
+ AttributeError
+ If name is not one of the lazily exported codecs.
+ """
if name not in _SCHEMA_EXPORTS:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
value = getattr(import_module(_SCHEMA_EXPORTS[name], __name__), name)
diff --git a/src/giant_python/io/annotations.py b/src/giant_python/io/annotations.py
index 73e61f9d..0cf53bb8 100644
--- a/src/giant_python/io/annotations.py
+++ b/src/giant_python/io/annotations.py
@@ -1,7 +1,6 @@
"""Raw ROI records, masks and provenance IO without band geometry or UI."""
from pathlib import Path
-from typing import Optional, Union
import h5py
import numpy as np
@@ -10,7 +9,13 @@
def _h5_scalar_str(ds: h5py.Dataset) -> str:
- """Read a scalar string, including legacy one-element string arrays."""
+ """Read a scalar string, including legacy one-element string arrays.
+
+ Returns
+ -------
+ str
+ The string, decoded as UTF-8 (with replacement) when stored as bytes.
+ """
value = ds[()]
if isinstance(value, np.ndarray):
value = value.reshape(-1)[0]
@@ -19,12 +24,18 @@ def _h5_scalar_str(ds: h5py.Dataset) -> str:
return str(value)
-def read_annotations_h5(path: Union[str, Path]) -> dict:
+def read_annotations_h5(path: str | Path) -> dict:
"""Read raw Path groups including n_rois, masks, records and provenance.
No geometry validation or superpixel mapping occurs here. Missing and
unreadable files raise OSError; annotation orchestration decides policy.
The shared decoder honors row_major and leaves coordinate indexes alone.
+
+ Returns
+ -------
+ dict
+ The file's raw contents as decoded by load_struct_h5: the Path groups with
+ n_rois, masks, records and provenance.
"""
return load_struct_h5(path)
@@ -34,13 +45,18 @@ def save_annotations_h5(
roi_records_by_dmd: dict,
user_roi_masks: dict,
n_dmds: int,
- ref_files: Optional[dict] = None,
+ ref_files: dict | None = None,
) -> str:
"""Write dr/annotations.h5 and return its path, preserving the band schema.
Rectangles are polygon records with zero-based [y,x] vertices. Masks are
(fast-Z,Y,X), may overlap, and are stored as compressed uint8. The caller
owns directory creation and the decision to replace an existing file.
+
+ Returns
+ -------
+ str
+ The path of the written annotations.h5.
"""
path = str(Path(dr) / "annotations.h5")
str_dt = h5py.string_dtype(encoding="utf-8")
@@ -70,14 +86,12 @@ def save_annotations_h5(
return path
-def _write_roi_group(grp, i: int, rec: dict, mask_list: list, str_dt) -> None:
+def _write_roi_group(grp: h5py.Group, i: int, rec: dict, mask_list: list, str_dt: np.dtype) -> None:
"""Write one roi_### group with the established optional-field policy."""
group = grp.create_group(f"roi_{i:03d}")
roi_type = rec.get("type", "polygon")
group.create_dataset("type", data=roi_type, dtype=str_dt)
- group.create_dataset(
- "label", data=rec.get("label", f"ROI{i + 1}"), dtype=str_dt
- )
+ group.create_dataset("label", data=rec.get("label", f"ROI{i + 1}"), dtype=str_dt)
if i < len(mask_list):
group.create_dataset(
"mask",
@@ -86,6 +100,4 @@ def _write_roi_group(grp, i: int, rec: dict, mask_list: list, str_dt) -> None:
shuffle=True,
)
if roi_type == "polygon" and "position" in rec:
- group.create_dataset(
- "position", data=np.asarray(rec["position"], dtype=np.float64)
- )
+ group.create_dataset("position", data=np.asarray(rec["position"], dtype=np.float64))
diff --git a/src/giant_python/io/experiment_summary.py b/src/giant_python/io/experiment_summary.py
index ef5024f7..f54f800f 100644
--- a/src/giant_python/io/experiment_summary.py
+++ b/src/giant_python/io/experiment_summary.py
@@ -1,20 +1,20 @@
-"""Codec for ``experiment_summary.h5``.
+"""Codec for experiment_summary.h5.
-The canonical interface is ``write_summary(summary, path) -> None`` and
-``read_summary(path) -> ExperimentSummary``.
+The canonical interface is write_summary(summary, path) -> None and
+read_summary(path) -> ExperimentSummary.
-``read_summary`` reads the files of both extraction pipelines: BandSILo's
-(``/row_major`` 1) and raster SILo's (``/row_major`` 0, GIAnT-MATLAB's
+read_summary reads the files of both extraction pipelines: BandSILo's
+(/row_major 1) and raster SILo's (/row_major 0, GIAnT-MATLAB's
layout), whose arrays :func:`~giant_python.io.hdf5.load_struct_h5` returns
in the same dimension order. Parts that a file may lack are None (or empty)
in the model, and raster SILo's own fields are carried as the model's
optional attributes (see :mod:`~giant_python.models.experiment_summary`).
-``write_summary`` writes BandSILo's row-major schema. A model read from a
+write_summary writes BandSILo's row-major schema. A model read from a
raster SILo file is written in that schema too, with its raster fields
-(kinetics, spot annotation, rejected sources, ``F0_im``, across-trial maps,
+(kinetics, spot annotation, rejected sources, F0_im, across-trial maps,
root attributes) written beside it, so that reading the new file gives the
-same model; parts the model lacks (``Z_depths``, ``offlineZshifts``, ...)
+same model; parts the model lacks (Z_depths, offlineZshifts, ...)
are left out of the file. It refuses to add paths to a column-major file.
There is no motion-sign conversion here. Existing params/row_major are left
untouched; supplied paths are replaced, and unrelated paths are retained.
@@ -25,10 +25,10 @@
import json
from collections.abc import Iterable
from pathlib import Path
-from typing import Optional, Union
import h5py
import numpy as np
+import numpy.typing as npt
from ..models.experiment_summary import (
FRAME_INFO_KEYS,
@@ -53,14 +53,47 @@
_SPOT_ATTRS = ("labels", "settings")
-def _row(assembled: dict, key: str, j: int):
- """Row ``j`` of a per-source or per-ROI array, None without it."""
+def _row(assembled: dict, key: str, j: int) -> np.ndarray | None:
+ """Return row j of a per-source or per-ROI array, None without it.
+
+ Parameters
+ ----------
+ assembled : dict
+ Decoded arrays by name.
+ key : str
+ Name of the array in assembled.
+ j : int
+ Row index.
+
+ Returns
+ -------
+ np.ndarray or None
+ Row j of assembled[key]; None when the key is absent or j is
+ out of range.
+ """
arr = assembled.get(key)
return None if arr is None or j >= arr.shape[0] else arr[j]
-def _scalar(assembled: dict, key: str, j: int, cast):
- """Source ``j``'s value of a ``(sources, 1)`` array, None without it."""
+def _scalar(assembled: dict, key: str, j: int, cast: type[float] | type[int]) -> float | None:
+ """Return source j's value of a (sources, 1) array, None without it.
+
+ Parameters
+ ----------
+ assembled : dict
+ Decoded arrays by name.
+ key : str
+ Name of the (sources, 1) array in assembled.
+ j : int
+ Source index.
+ cast : type
+ Python type (float or int) applied to the value.
+
+ Returns
+ -------
+ float or int or None
+ Source j's value converted with cast; None when the key is absent.
+ """
arr = assembled.get(key)
if arr is None:
return None
@@ -72,12 +105,22 @@ def _decode_path(assembled: dict, path_index: int) -> PathSummary:
This schema-only adapter does not concatenate traces or compute baselines.
Empty-array templates preserve dimensions/dtypes absent from empty lists.
- Parts the file lacks are None: per-source traces, ``SNR`` (raster SILo
+ Parts the file lacks are None: per-source traces, SNR (raster SILo
writes none when no trial gave one), the raster-only fields.
+
+ Parameters
+ ----------
+ assembled : dict
+ Arrays of one path group, by name.
+ path_index : int
+ 0-based index of the path.
+
+ Returns
+ -------
+ PathSummary
+ The eager summary of the path.
"""
- n_sources = (
- assembled["profiles"].shape[0] if "profiles" in assembled else 0
- )
+ n_sources = assembled["profiles"].shape[0] if "profiles" in assembled else 0
sources = [
Source(
profile=assembled["profiles"][j],
@@ -117,20 +160,12 @@ def _decode_path(assembled: dict, path_index: int) -> PathSummary:
act_im_peaks=assembled.get("act_im_peaks"),
f0_im=assembled.get("F0_im"),
),
- frame_info=FrameInfo(
- **{key: assembled.get(key) for key in FRAME_INFO_KEYS}
- ),
+ frame_info=FrameInfo(**{key: assembled.get(key) for key in FRAME_INFO_KEYS}),
global_f=assembled.get("global_f"),
z_depths=assembled.get("Z_depths"),
- annotation_enabled=assembled.get(
- "annotation_enabled", rois is not None
- ),
+ annotation_enabled=assembled.get("annotation_enabled", rois is not None),
_empty_source_arrays=(
- {}
- if sources
- else {
- key: assembled[key] for key in _SOURCE_KEYS if key in assembled
- }
+ {} if sources else {key: assembled[key] for key in _SOURCE_KEYS if key in assembled}
),
_empty_roi_arrays=(
{key: rois[key] for key in ("mask", "F", "Fsvd") if key in rois}
@@ -143,10 +178,26 @@ def _decode_path(assembled: dict, path_index: int) -> PathSummary:
)
-def _stack_required_arrays(
- arrays: Iterable[np.ndarray | None], field: str
-) -> np.ndarray:
- """Stack arrays; identify missing fields by their 0-based index."""
+def _stack_required_arrays(arrays: Iterable[np.ndarray | None], field: str) -> np.ndarray:
+ """Stack arrays; identify missing fields by their 0-based index.
+
+ Parameters
+ ----------
+ arrays : Iterable[np.ndarray or None]
+ Per-entry arrays to stack.
+ field : str
+ Name of the field, used in the error message.
+
+ Returns
+ -------
+ np.ndarray
+ The arrays stacked along a new first axis.
+
+ Raises
+ ------
+ ValueError
+ If any entry is None.
+ """
required: list[np.ndarray] = []
for index, array in enumerate(arrays):
if array is None:
@@ -155,41 +206,88 @@ def _stack_required_arrays(
return np.stack(required)
-def _optional_array(array, reference: np.ndarray, field: str) -> np.ndarray:
- """Validate a supplied trace, or mark unavailable samples with NaNs."""
+def _optional_array(array: npt.ArrayLike | None, reference: np.ndarray, field: str) -> np.ndarray:
+ """Validate a supplied trace, or mark unavailable samples with NaNs.
+
+ Parameters
+ ----------
+ array : array_like or None
+ The supplied trace, or None when unavailable.
+ reference : np.ndarray
+ Required trace whose shape (and, for NaN filling, dtype) is matched.
+ field : str
+ Name of the field, used in the error message.
+
+ Returns
+ -------
+ np.ndarray
+ The trace as an array, or an all-NaN array shaped like reference
+ when array is None.
+
+ Raises
+ ------
+ ValueError
+ If array is supplied with a shape different from reference.
+ """
if array is None:
- dtype = (
- reference.dtype
- if np.issubdtype(reference.dtype, np.inexact)
- else np.dtype(float)
- )
+ dtype = reference.dtype if np.issubdtype(reference.dtype, np.inexact) else np.dtype(float)
return np.full(reference.shape, np.nan, dtype=dtype)
array = np.asarray(array)
if array.shape != reference.shape:
- raise ValueError(
- f"{field} must have shape {reference.shape}; got {array.shape}"
- )
+ raise ValueError(f"{field} must have shape {reference.shape}; got {array.shape}")
return array
def _stack_optional_arrays(
arrays: Iterable[np.ndarray | None], reference: np.ndarray, field: str
) -> np.ndarray:
- """Check each optional entry against its corresponding required trace."""
- return np.stack(
- [
- _optional_array(array, reference[index], f"{field}[{index}]")
- for index, array in enumerate(arrays)
- ]
- )
-
-
-def _empty_geometry(
- path: PathSummary, field: str
-) -> tuple[tuple[int, ...], np.ndarray]:
- """Infer empty tensor dimensions from the saved images and global trace
- (without a global trace, as for a raster path without frames: channels
- from ``mean_im``, frames from ``trial_num_frames``)."""
+ """Check each optional entry against its corresponding required trace.
+
+ Parameters
+ ----------
+ arrays : Iterable[np.ndarray or None]
+ Per-entry optional traces.
+ reference : np.ndarray
+ Stacked required traces; entry i is checked against reference[i].
+ field : str
+ Name of the field, used in error messages.
+
+ Returns
+ -------
+ np.ndarray
+ The entries stacked along a new first axis, NaN where an entry is None.
+ """
+ return np.stack([
+ _optional_array(array, reference[index], f"{field}[{index}]")
+ for index, array in enumerate(arrays)
+ ])
+
+
+def _empty_geometry(path: PathSummary, field: str) -> tuple[tuple[int, ...], np.ndarray]:
+ """Infer empty tensor dimensions from the saved images and global trace.
+
+ Without a global trace (as for a raster path without frames) channels come
+ from mean_im and frames from trial_num_frames.
+
+ Parameters
+ ----------
+ path : PathSummary
+ Path whose images and traces give the geometry.
+ field : str
+ Name of the empty field, used in the error message.
+
+ Returns
+ -------
+ tuple[tuple[int, ...], np.ndarray]
+ The spatial shape (fastz, rows, cols) and an empty or global
+ (channels, frames) array giving the trace shape and dtype.
+
+ Raises
+ ------
+ ValueError
+ If neither shape templates nor mean_im and global_f geometry are
+ available.
+ """
mean = np.asarray(path.visualizations.mean_im)
counts = path.frame_info.trial_num_frames
if path.global_f is None and mean.ndim == 4 and counts is not None:
@@ -197,16 +295,32 @@ def _empty_geometry(
return mean.shape[1:], np.empty((mean.shape[0], total))
global_f = np.asarray(path.global_f)
if mean.ndim != 4 or global_f.ndim != 2:
- raise ValueError(
- f"Empty {field} require shape templates or "
- "mean_im and global_f geometry"
- )
+ raise ValueError(f"Empty {field} require shape templates or mean_im and global_f geometry")
return mean.shape[1:], global_f
def _source_scalars(path: PathSummary) -> dict:
- """Raster SILo's per-source scalars as ``(sources, 1)`` arrays, for the
- fields every source has; a field only some sources have is an error."""
+ """Return raster SILo's per-source scalars as (sources, 1) arrays.
+
+ The scalars are those every source has; a field only some sources have is
+ an error.
+
+ Parameters
+ ----------
+ path : PathSummary
+ Path whose sources are read.
+
+ Returns
+ -------
+ dict
+ (sources, 1) arrays by dataset name, only for fields set on every
+ source.
+
+ Raises
+ ------
+ ValueError
+ If a field is set on only some of the sources.
+ """
out = {}
for name, _, key, dtype in _RASTER_SOURCE_FIELDS:
values = [getattr(s, name) for s in path.sources]
@@ -214,35 +328,41 @@ def _source_scalars(path: PathSummary) -> dict:
if not any(have):
continue
if not all(have):
- raise ValueError(
- f"Source.{name} must be set for every source or none"
- )
+ raise ValueError(f"Source.{name} must be set for every source or none")
out[key] = np.asarray(values, dtype=dtype).reshape(-1, 1)
return out
def _source_arrays(path: PathSummary) -> dict:
- """The populated sources' stacked arrays (and raster SILo's fields)."""
+ """Stack the populated sources' arrays (and raster SILo's fields).
+
+ Parameters
+ ----------
+ path : PathSummary
+ Path with at least one source.
+
+ Returns
+ -------
+ dict
+ Stacked source arrays by dataset name.
+
+ Raises
+ ------
+ ValueError
+ If Source.f0_core is set on only some of the sources.
+ """
out = {
- "profiles": _stack_required_arrays(
- (s.profile for s in path.sources), "Source.profile"
- ),
- "coords": _stack_required_arrays(
- (s.coords for s in path.sources), "Source.coords"
- ),
- "dF_ls": _stack_required_arrays(
- (s.df_ls for s in path.sources), "Source.df_ls"
- ),
- "F0": _stack_required_arrays(
- (s.f0 for s in path.sources), "Source.f0"
- ),
+ "profiles": _stack_required_arrays((s.profile for s in path.sources), "Source.profile"),
+ "coords": _stack_required_arrays((s.coords for s in path.sources), "Source.coords"),
+ "dF_ls": _stack_required_arrays((s.df_ls for s in path.sources), "Source.df_ls"),
+ "F0": _stack_required_arrays((s.f0 for s in path.sources), "Source.f0"),
**_source_scalars(path),
}
if not (path._snr_absent and all(s.snr is None for s in path.sources)):
# a raster file without SNR stays without it; otherwise NaN
- out["SNR"] = np.asarray(
- [np.nan if s.snr is None else s.snr for s in path.sources]
- ).reshape(-1, 1)
+ out["SNR"] = np.asarray([np.nan if s.snr is None else s.snr for s in path.sources]).reshape(
+ -1, 1
+ )
for key, field in (
("dF_denoised", "df_denoised"),
("events", "events"),
@@ -256,31 +376,37 @@ def _source_arrays(path: PathSummary) -> dict:
cores = [s.f0_core for s in path.sources]
if any(c is not None for c in cores):
if not all(c is not None for c in cores):
- raise ValueError(
- "Source.f0_core must be set for every source or none"
- )
- out["F0_core"] = _stack_optional_arrays(
- cores, out["F0"], "Source.f0_core"
- )
+ raise ValueError("Source.f0_core must be set for every source or none")
+ out["F0_core"] = _stack_optional_arrays(cores, out["F0"], "Source.f0_core")
return out
def _roi_arrays(rois: list) -> dict:
- """The ROIs' stacked arrays. Without any trace (raster SILo's path
- without frames writes labels and masks only) ``F`` and ``Fsvd`` are
- left out; a trace missing for only some ROIs is an error."""
+ """Stack the ROIs' arrays.
+
+ Without any trace (raster SILo's path without frames writes labels and
+ masks only) F and Fsvd are left out; a trace missing for only some
+ ROIs is an error.
+
+ Parameters
+ ----------
+ rois : list
+ The path's :class:`UserRoi` entries.
+
+ Returns
+ -------
+ dict
+ Stacked mask, labels and, when any trace exists, F and
+ Fsvd.
+ """
out = {
- "mask": _stack_required_arrays(
- (roi.mask for roi in rois), "UserRoi.mask"
- ),
+ "mask": _stack_required_arrays((roi.mask for roi in rois), "UserRoi.mask"),
"labels": [roi.label for roi in rois],
}
if all(roi.f is None and roi.fsvd is None for roi in rois):
return out
out["F"] = _stack_required_arrays((roi.f for roi in rois), "UserRoi.f")
- out["Fsvd"] = _stack_optional_arrays(
- (roi.fsvd for roi in rois), out["F"], "UserRoi.fsvd"
- )
+ out["Fsvd"] = _stack_optional_arrays((roi.fsvd for roi in rois), out["F"], "UserRoi.fsvd")
return out
@@ -292,6 +418,21 @@ def _encode_path(path: PathSummary) -> dict:
Missing optional traces are NaN, never inferred from other signals.
Required fields and optional shapes are checked before path replacement.
Raster SILo's fields are added when the model has them.
+
+ Parameters
+ ----------
+ path : PathSummary
+ Path to encode.
+
+ Returns
+ -------
+ dict
+ Arrays by dataset name, including the nested user_rois dict.
+
+ Raises
+ ------
+ ValueError
+ If user ROIs are present while annotation_enabled is False.
"""
out = {
"Z_depths": path.z_depths,
@@ -308,15 +449,13 @@ def _encode_path(path: PathSummary) -> dict:
out.update(path._empty_source_arrays)
else:
spatial_shape, global_f = _empty_geometry(path, "sources")
- out.update(
- {
- "profiles": np.empty((0, *spatial_shape), dtype=np.float32),
- "coords": np.empty((0, 3), dtype=np.int32),
- "dF_ls": np.empty((0, *global_f.shape), dtype=global_f.dtype),
- "F0": np.empty((0, *global_f.shape), dtype=global_f.dtype),
- "SNR": np.empty((0, 1), dtype=np.float32),
- }
- )
+ out.update({
+ "profiles": np.empty((0, *spatial_shape), dtype=np.float32),
+ "coords": np.empty((0, 3), dtype=np.int32),
+ "dF_ls": np.empty((0, *global_f.shape), dtype=global_f.dtype),
+ "F0": np.empty((0, *global_f.shape), dtype=global_f.dtype),
+ "SNR": np.empty((0, 1), dtype=np.float32),
+ })
if not path.sources:
for key in ("dF_denoised", "events"):
out[key] = _optional_array(out.get(key), out["dF_ls"], key)
@@ -337,9 +476,7 @@ def _encode_path(path: PathSummary) -> dict:
out["user_rois"] = {
**empty,
"labels": [],
- "Fsvd": _optional_array(
- empty.get("Fsvd"), empty["F"], "UserRoi.Fsvd"
- ),
+ "Fsvd": _optional_array(empty.get("Fsvd"), empty["F"], "UserRoi.Fsvd"),
}
if path.z_depths is not None:
out["Z_depths"] = np.asarray(path.z_depths).reshape(-1, 1)
@@ -347,21 +484,41 @@ def _encode_path(path: PathSummary) -> dict:
def _write_spots(sources: h5py.Group, spots: dict) -> None:
- """The spot annotation: its arrays, and ``labels`` and ``settings`` as
- JSON attributes."""
+ """Write the spot annotation.
+
+ Its arrays become datasets, and labels and settings become JSON
+ attributes.
+
+ Parameters
+ ----------
+ sources : h5py.Group
+ The path's sources group.
+ spots : dict
+ Spot annotation arrays plus labels and settings.
+ """
group = sources.create_group("spots")
for key, value in spots.items():
if key in _SPOT_ATTRS:
- group.attrs[key] = json.dumps(
- list(value) if key == "labels" else value
- )
+ group.attrs[key] = json.dumps(list(value) if key == "labels" else value)
else:
group.create_dataset(key, data=np.asarray(value))
-def _write_sources(group: h5py.Group, assembled: dict, path) -> None:
- """A path's ``sources`` group: the band schema's datasets, then raster
- SILo's fields that the model has."""
+def _write_sources(group: h5py.Group, assembled: dict, path: PathSummary) -> None:
+ """Write a path's sources group.
+
+ It holds the band schema's datasets, then raster SILo's fields that the
+ model has.
+
+ Parameters
+ ----------
+ group : h5py.Group
+ The path's group.
+ assembled : dict
+ Encoded arrays of the path.
+ path : PathSummary
+ The path being written.
+ """
sources = group.create_group("sources")
spatial = sources.create_group("spatial")
for key in ("profiles", "coords"):
@@ -396,9 +553,7 @@ def _write_path_group(f: h5py.File, path: PathSummary) -> None:
if assembled[key] is not None:
frame_group.create_dataset(key, data=assembled[key])
if assembled["global_f"] is not None:
- group.create_group("global").create_dataset(
- "F", data=assembled["global_f"]
- )
+ group.create_group("global").create_dataset("F", data=assembled["global_f"])
vis = group.create_group("visualizations")
for key in ("act_im", "mean_im", "act_im_peaks", "F0_im"):
if assembled[key] is not None:
@@ -416,7 +571,7 @@ def _write_path_group(f: h5py.File, path: PathSummary) -> None:
)
-def write_summary(summary: ExperimentSummary, path: Union[str, Path]) -> None:
+def write_summary(summary: ExperimentSummary, path: str | Path) -> None:
"""Persist models, retaining existing params, flags and unrelated paths.
Path identity comes exclusively from PathSummary.path_index. Required
@@ -424,14 +579,27 @@ def write_summary(summary: ExperimentSummary, path: Union[str, Path]) -> None:
replacing each existing path group. Disabled annotations still emit empty
ROI datasets; their state is recorded in a group attribute.
- The file is BandSILo's row-major schema (``/row_major`` 1). Raster SILo's
+ The file is BandSILo's row-major schema (/row_major 1). Raster SILo's
fields of a model read from a raster file are written beside it (see the
- module docstring), and ``summary.attrs`` become root attributes. Parts
- the model lacks (``z_depths``, frame fields, ``act_im_peaks``,
- ``global_f``, ``SNR`` that a raster file did not have) are left out.
- Adding paths to a column-major file (``/row_major`` 0: raster SILo's or
+ module docstring), and summary.attrs become root attributes. Parts
+ the model lacks (z_depths, frame fields, act_im_peaks,
+ global_f, SNR that a raster file did not have) are left out.
+ Adding paths to a column-major file (/row_major 0: raster SILo's or
GIAnT-MATLAB's) or to a nonempty file without the flag (read as
column-major) is refused, since its arrays have the other layout.
+
+ Parameters
+ ----------
+ summary : ExperimentSummary
+ Model to write.
+ path : str or Path
+ Path of the experiment_summary.h5 file.
+
+ Raises
+ ------
+ ValueError
+ If summary has duplicate path_index values, or the file is
+ column-major or has no /row_major flag while not empty.
"""
indexes = [item.path_index for item in summary.paths]
if len(set(indexes)) != len(indexes):
@@ -462,16 +630,42 @@ def write_summary(summary: ExperimentSummary, path: Union[str, Path]) -> None:
_write_path_group(f, item)
-def _decoded(value):
- """An HDF5 attribute as a plain value (bytes decoded)."""
+def _decoded(value: object) -> object:
+ """Return an HDF5 attribute as a plain value (bytes decoded).
+
+ Parameters
+ ----------
+ value : object
+ Attribute value as h5py returns it.
+
+ Returns
+ -------
+ object
+ value decoded to str when it is bytes; otherwise unchanged.
+ """
if isinstance(value, (bytes, np.bytes_)):
return value.decode("utf-8", "replace")
return value
-def _spots(arrays: Optional[dict], attrs: Optional[dict]) -> Optional[dict]:
- """The spot annotation: its arrays, plus ``labels`` (list) and
- ``settings`` (dict) from its JSON attributes; None without it."""
+def _spots(arrays: dict | None, attrs: dict | None) -> dict | None:
+ """Return the spot annotation.
+
+ It holds its arrays, plus labels (list) and settings (dict) from
+ its JSON attributes; None without it.
+
+ Parameters
+ ----------
+ arrays : dict or None
+ Datasets of the spots group.
+ attrs : dict or None
+ Attributes of the spots group.
+
+ Returns
+ -------
+ dict or None
+ The spot annotation, or None when arrays is None.
+ """
if arrays is None:
return None
out = dict(arrays)
@@ -481,24 +675,34 @@ def _spots(arrays: Optional[dict], attrs: Optional[dict]) -> Optional[dict]:
return out
-def read_summary(path: Union[str, Path]) -> ExperimentSummary:
+def read_summary(path: str | Path) -> ExperimentSummary:
"""Read an experiment summary eagerly, from BandSILo or raster SILo.
- Both layouts are read (``/row_major`` 1 or 0); arrays come back in the
+ Both layouts are read (/row_major 1 or 0); arrays come back in the
README's dimension order. Unrecognized root groups are ignored. Paths are
sorted by their numeric identity, not lexical order, and a path the file
- leaves out is not in ``paths``. Parts a raster SILo file may lack are
- None or empty: ``z_depths`` (unknown depth), ``offlineZshifts`` (no
- axial motion estimate), ``user_rois`` (no annotations), the sources and
- ``act_im_peaks`` (no kept source), ``SNR``, ``global_f`` (no frames).
+ leaves out is not in paths. Parts a raster SILo file may lack are
+ None or empty: z_depths (unknown depth), offlineZshifts (no
+ axial motion estimate), user_rois (no annotations), the sources and
+ act_im_peaks (no kept source), SNR, global_f (no frames).
Raster SILo's own fields are read into the model's optional attributes
- (``Source.f0_core``, ``kinetic_score``, ``kinetic_n_events``,
- ``spot_id``;
- ``PathSummary.rejected`` and ``spots``; ``Visualizations.f0_im``; the
- ``trial_alignment_*`` maps in ``FrameInfo``; the root attributes in
- ``ExperimentSummary.attrs``).
+ (Source.f0_core, kinetic_score, kinetic_n_events,
+ spot_id;
+ PathSummary.rejected and spots; Visualizations.f0_im; the
+ trial_alignment_* maps in FrameInfo; the root attributes in
+ ExperimentSummary.attrs).
Legacy missing optional traces remain None; without annotation metadata,
ROI group presence retains its historical enabled/disabled meaning.
+
+ Parameters
+ ----------
+ path : str or Path
+ Path of the experiment_summary.h5 file.
+
+ Returns
+ -------
+ ExperimentSummary
+ The eager summary with one entry in paths per path group.
"""
raw = load_struct_h5(path)
names = sorted(
@@ -510,20 +714,14 @@ def read_summary(path: Union[str, Path]) -> ExperimentSummary:
with h5py.File(path, "r") as f:
annotation_enabled = {
name: (
- bool(
- f[name]["user_rois"].attrs.get("annotation_enabled", True)
- )
+ bool(f[name]["user_rois"].attrs.get("annotation_enabled", True))
if "user_rois" in f[name]
else False
)
for name in names
}
spot_attrs = {
- name: (
- dict(f[f"{name}/sources/spots"].attrs)
- if f"{name}/sources/spots" in f
- else None
- )
+ name: (dict(f[f"{name}/sources/spots"].attrs) if f"{name}/sources/spots" in f else None)
for name in names
}
attrs = {key: _decoded(value) for key, value in f.attrs.items()}
@@ -545,6 +743,4 @@ def read_summary(path: Union[str, Path]) -> ExperimentSummary:
"spots": _spots(sources.get("spots"), spot_attrs[name]),
}
paths.append(_decode_path(assembled, int(name[4:]) - 1))
- return ExperimentSummary(
- paths=paths, params=raw.get("params"), attrs=attrs
- )
+ return ExperimentSummary(paths=paths, params=raw.get("params"), attrs=attrs)
diff --git a/src/giant_python/io/hdf5.py b/src/giant_python/io/hdf5.py
index 8110c8a6..336fde87 100644
--- a/src/giant_python/io/hdf5.py
+++ b/src/giant_python/io/hdf5.py
@@ -1,43 +1,57 @@
"""MATLAB-style HDF5 decoding, struct writing and parameter group writing.
This module is the foundation of MATLAB interoperability: the model
-``from_h5`` / ``to_h5`` methods build on these helpers.
+from_h5 / to_h5 methods build on these helpers.
Serialization conventions
-------------------------
Shared with GIAnT-MATLAB; see the package README.
-* Writers set ``/row_major`` to ``1`` (Python / h5py) or ``0`` (MATLAB).
-* Dimension tuples in the README match h5py ``shape`` when ``row_major=1``.
-* Vectors documented as ``1 x N`` or ``N x 1`` are written as rank-2
- datasets with those shapes (never squeezed to ``(N,)``), so downstream
+* Writers set /row_major to 1 (Python / h5py) or 0 (MATLAB).
+* Dimension tuples in the README match h5py shape when row_major=1.
+* Vectors documented as 1 x N or N x 1 are written as rank-2
+ datasets with those shapes (never squeezed to (N,)), so downstream
code can use the same size checks on either toolbox's outputs after
- consulting ``row_major``.
+ consulting row_major.
"""
from pathlib import Path
-from typing import Union, cast
+from typing import Any, cast
import h5py
import numpy as np
+import numpy.typing as npt
def _is_string_dataset(ds: h5py.Dataset) -> bool:
- """Return whether an h5py dataset holds (fixed/variable-length) strings."""
+ """Return whether an h5py dataset holds (fixed/variable-length) strings.
+
+ Returns
+ -------
+ bool
+ True if the dataset dtype is a string, bytes, unicode or object type.
+ """
if h5py.check_string_dtype(ds.dtype) is not None:
return True
return ds.dtype.kind in ("S", "U", "O")
-def _decode_one(x) -> str:
- """Decode a single bytes/str scalar to ``str``."""
+def _decode_one(x: object) -> str:
+ """Decode a single bytes/str scalar to str.
+
+ Returns
+ -------
+ str
+ The UTF-8 decoded text (undecodable bytes replaced), or str(x) for
+ non-bytes input.
+ """
if isinstance(x, (bytes, np.bytes_)):
return x.decode("utf-8", "replace")
return str(x)
-def _decode_strings(val):
- """Decode a scalar or ndarray of (variable-length) strings to ``str``.
+def _decode_strings(val: object) -> str | np.ndarray:
+ """Decode a scalar or ndarray of (variable-length) strings to str.
Parameters
----------
@@ -57,11 +71,11 @@ def _decode_strings(val):
return np.vectorize(_decode_one, otypes=[object])(arr)
-def _read_dataset(ds: h5py.Dataset, row_major: bool):
- """Read one dataset in MATLAB ``size()`` orientation.
+def _read_dataset(ds: h5py.Dataset, row_major: bool) -> object:
+ """Read one dataset in MATLAB size() orientation.
- Scalar strings/paths (e.g. ``datadr``) are returned as plain ``str``;
- string grids (e.g. ``filename``, ``fn_adata``) stay as object arrays with
+ Scalar strings/paths (e.g. datadr) are returned as plain str;
+ string grids (e.g. filename, fn_adata) stay as object arrays with
MATLAB shape. Column-major files have their 2-D+ axes transposed to recover
the README orientation.
@@ -70,12 +84,12 @@ def _read_dataset(ds: h5py.Dataset, row_major: bool):
ds : h5py.Dataset
The dataset to read.
row_major : bool
- Whether the file was written row-major (``True``) or column-major.
+ Whether the file was written row-major (True) or column-major.
Returns
-------
object
- The decoded value (``str``, scalar, or ndarray).
+ The decoded value (str, scalar, or ndarray).
"""
val = ds[()]
if _is_string_dataset(ds):
@@ -93,7 +107,14 @@ def _read_dataset(ds: h5py.Dataset, row_major: bool):
def _read_group(grp: h5py.Group, row_major: bool) -> dict:
- """Read an h5py group into a nested dict (skipping ``row_major``)."""
+ """Read an h5py group into a nested dict (skipping row_major).
+
+ Returns
+ -------
+ dict
+ Mapping of member name to its decoded dataset value or, for
+ subgroups, to a nested dict.
+ """
out = {}
for key, item in grp.items():
if key == "row_major":
@@ -105,16 +126,16 @@ def _read_group(grp: h5py.Group, row_major: bool) -> dict:
return out
-def load_struct_h5(path: Union[str, Path]) -> dict:
+def load_struct_h5(path: str | Path) -> dict:
"""Load a (possibly nested) MATLAB-style struct from an HDF5 file.
Recursively reads HDF5 groups into nested dictionaries, applying the
- ``row_major`` / axis-permutation conventions required for MATLAB
+ row_major / axis-permutation conventions required for MATLAB
compatibility. Corresponds to loadStructFromH5.m in GIAnT-MATLAB.
- Groups become nested dicts, string datasets become ``str`` (scalars) or
+ Groups become nested dicts, string datasets become str (scalars) or
object arrays (grids), and numeric datasets are returned in MATLAB
- ``size()`` orientation. The ``/row_major`` flag (absent => column-major)
+ size() orientation. The /row_major flag (absent => column-major)
selects whether 2-D+ axes are transposed.
Parameters
@@ -135,8 +156,16 @@ def load_struct_h5(path: Union[str, Path]) -> dict:
return _read_group(f, row_major)
-def to_serializable(val):
- """Convert nested NumPy values to ordinary Python parameter values."""
+def to_serializable(val: object) -> Any: # noqa: ANN401
+ """Convert nested NumPy values to ordinary Python parameter values.
+
+ Returns
+ -------
+ Any
+ A copy of val with dicts, lists and tuples converted recursively,
+ arrays turned into lists and NumPy scalars into Python scalars; other
+ values are returned unchanged.
+ """
if isinstance(val, dict):
return {k: to_serializable(v) for k, v in val.items()}
if isinstance(val, (list, tuple)):
@@ -148,7 +177,7 @@ def to_serializable(val):
return val
-def _write_preserved_array(grp: h5py.Group, key: str, value) -> None:
+def _write_preserved_array(grp: h5py.Group, key: str, value: np.ndarray | np.generic) -> None:
"""Write a NumPy value with its original shape and numeric dtype."""
arr = np.asarray(value)
if arr.dtype.kind in ("U", "S", "O"):
@@ -161,7 +190,7 @@ def _write_preserved_array(grp: h5py.Group, key: str, value) -> None:
grp.create_dataset(key, data=arr)
-def _write_sequence(grp: h5py.Group, key: str, value) -> None:
+def _write_sequence(grp: h5py.Group, key: str, value: list | tuple) -> None:
"""Skip empty sequences and preserve persisted element stringification."""
arr = np.asarray(value)
if arr.size == 0:
@@ -176,12 +205,17 @@ def _write_sequence(grp: h5py.Group, key: str, value) -> None:
grp.create_dataset(key, data=arr)
-def _matlab_array(value) -> np.ndarray:
- """A value as an array in MATLAB ``size()`` orientation (rank >= 2).
+def _matlab_array(value: npt.ArrayLike) -> np.ndarray:
+ """Convert a value to an array in MATLAB size() orientation (rank >= 2).
+
+ Python scalars become 1 x 1 (int and float as double, the
+ MATLAB default; bool as int8, as GIAnT-MATLAB writes logicals); 1-D
+ arrays become 1 x N rows.
- Python scalars become ``1 x 1`` (``int`` and ``float`` as double, the
- MATLAB default; ``bool`` as int8, as GIAnT-MATLAB writes logicals); 1-D
- arrays become ``1 x N`` rows.
+ Returns
+ -------
+ np.ndarray
+ The value as an array of rank at least 2 (booleans stored as int8).
"""
if isinstance(value, (bool, np.bool_)):
return np.array([[np.int8(value)]])
@@ -197,13 +231,13 @@ def _matlab_array(value) -> np.ndarray:
return arr
-def write_matlab_value(grp: h5py.Group, key: str, value) -> None:
- """Write one value as GIAnT-MATLAB ``saveStructToH5`` would.
+def write_matlab_value(grp: h5py.Group, key: str, value: dict | npt.ArrayLike) -> None:
+ """Write one value as GIAnT-MATLAB saveStructToH5 would.
Dictionaries become groups; strings and string arrays become variable
length UTF-8 strings; numeric and boolean arrays are given in MATLAB
orientation and stored with reversed dimensions (column-major), so
- MATLAB's ``h5read`` returns the original ``size()``. Empty values are
+ MATLAB's h5read returns the original size(). Empty values are
skipped, as MATLAB skips empty fields.
Parameters
@@ -214,7 +248,7 @@ def write_matlab_value(grp: h5py.Group, key: str, value) -> None:
Dataset or group name.
value : dict, str, bool, int, float or array_like
The value. Use NumPy dtypes to choose the stored class (e.g.
- ``np.float32`` for MATLAB single).
+ np.float32 for MATLAB single).
"""
if isinstance(value, dict):
sub = grp.create_group(key)
@@ -223,28 +257,24 @@ def write_matlab_value(grp: h5py.Group, key: str, value) -> None:
return
str_dt = h5py.string_dtype(encoding="utf-8")
if isinstance(value, str):
- grp.create_dataset(
- key, data=np.array([[value]], dtype=object), dtype=str_dt
- )
+ grp.create_dataset(key, data=np.array([[value]], dtype=object), dtype=str_dt)
return
arr = _matlab_array(value)
if arr.size == 0:
return
if arr.dtype.kind in ("U", "S", "O"):
text = np.vectorize(_decode_one, otypes=[object])(arr)
- grp.create_dataset(
- key, data=np.ascontiguousarray(text.T), dtype=str_dt
- )
+ grp.create_dataset(key, data=np.ascontiguousarray(text.T), dtype=str_dt)
return
grp.create_dataset(key, data=np.ascontiguousarray(arr.T))
-def save_struct_h5(path: Union[str, Path], struct: dict) -> None:
+def save_struct_h5(path: str | Path, struct: dict) -> None:
"""Write a nested dict as a GIAnT-MATLAB struct file (column-major).
- Counterpart of ``saveStructToH5.m``: the file is created anew and gets
- ``/row_major = 0``, so both :func:`load_struct_h5` and MATLAB's
- ``loadStructFromH5`` read the values back in MATLAB orientation.
+ Counterpart of saveStructToH5.m: the file is created anew and gets
+ /row_major = 0, so both :func:`load_struct_h5` and MATLAB's
+ loadStructFromH5 read the values back in MATLAB orientation.
Parameters
----------
diff --git a/src/giant_python/io/slap2.py b/src/giant_python/io/slap2.py
index 9513d3be..3b74b3bc 100644
--- a/src/giant_python/io/slap2.py
+++ b/src/giant_python/io/slap2.py
@@ -4,26 +4,42 @@
not this raw acquisition adapter.
"""
+from __future__ import annotations
+
from pathlib import Path
-from typing import Any, Protocol, Union
+from typing import Any, Protocol
+import h5py
import numpy as np
from .hdf5 import load_struct_h5
-def _reshape_1d(src: dict, key: str):
- """Flatten an optional raw alignment vector without altering its sign."""
+def _reshape_1d(src: dict, key: str) -> np.ndarray | None:
+ """Flatten an optional raw alignment vector without altering its sign.
+
+ Returns
+ -------
+ np.ndarray or None
+ The flat vector, or None if key is absent.
+ """
value = src.get(key)
return None if value is None else np.asarray(value).reshape(-1)
-def load_alignment_data_h5(path: Union[str, Path]) -> dict:
+def load_alignment_data_h5(path: str | Path) -> dict:
"""Read alignment vectors with the original saved displacement sign.
Flatten DS/offline/online vectors and expose numChannels/alignHz scalars.
No coordinate normalization or motion negation belongs in this reader.
Band numerical consumers must use extraction.band.inputs instead.
+
+ Returns
+ -------
+ dict
+ The flat DSframes, motionDSr, motionDSc, motionDSz, onlineYshift,
+ onlineXshift and onlineZshift vectors (None where absent), and the
+ numChannels and alignHz scalars.
"""
data = load_struct_h5(path)
online = data.get("slap2", {}) or {}
@@ -55,35 +71,47 @@ class Slap2Reader(Protocol):
lineSuperPixelIDs: Any
lineFastZIdxs: Any
- def getLineData(self, line_indices, cycle_indices, channels=None):
+ def getLineData(
+ self, line_indices: np.ndarray, cycle_indices: np.ndarray, channels: int | None = None
+ ) -> None:
"""Read a batch using the vendor reader's unchanged contract."""
-def is_cycle_split(path: Union[str, Path]) -> bool:
- """Whether a ``.dat`` file name marks one file of a CYCLE-split recording.
+def is_cycle_split(path: str | Path) -> bool:
+ """Whether a .dat file name marks one file of a CYCLE-split recording.
- SLAP2 writes long recordings as ``-CYCLE-.dat`` files.
- The hyphen after ``CYCLE`` is optional, as in the ``-CYCLE-?[0-9]+$``
- suffix that ``MultiDataFiles`` (MATLAB and slap2_utils) strips to find
+ SLAP2 writes long recordings as -CYCLE-.dat files.
+ The hyphen after CYCLE is optional, as in the -CYCLE-?[0-9]+$
+ suffix that MultiDataFiles (MATLAB and slap2_utils) strips to find
the other files.
+
+ Returns
+ -------
+ bool
+ True if the file name ends with the CYCLE suffix and a cycle number.
"""
import re
- return (
- re.search(r"CYCLE-?\d+$", Path(path).stem, re.IGNORECASE) is not None
- )
+ return re.search(r"CYCLE-?\d+$", Path(path).stem, re.IGNORECASE) is not None
_LINE_MAGIC = 322379495
-"""``magicNumber`` field of every SLAP2 line header."""
+"""magicNumber field of every SLAP2 line header."""
+
+class _DatFileLike(Protocol):
+ """The parts of a slap2_utils DataFile that the first-line read uses."""
+
+ header: dict
+ datFileName: str
-def first_line_timestamp(datafile) -> int:
- """FPGA clock tick of the first line of a ``slap2_utils`` ``DataFile``.
+
+def first_line_timestamp(datafile: _DatFileLike) -> int:
+ """FPGA clock tick of the first line of a slap2_utils DataFile.
Line headers hold the tick as a uint64 at bytes 24-31; the first line's
- header starts the file's first cycle (``firstCycleOffsetBytes``). This is
- GIAnT-MATLAB's reader's ``firstLineTimestamp``.
+ header starts the file's first cycle (firstCycleOffsetBytes). This is
+ GIAnT-MATLAB's reader's firstLineTimestamp.
Parameters
----------
@@ -94,6 +122,12 @@ def first_line_timestamp(datafile) -> int:
-------
int
The tick count.
+
+ Raises
+ ------
+ ValueError
+ If the file has no complete line header at the first cycle, or the
+ header's magic number is wrong.
"""
offset = int(datafile.header["firstCycleOffsetBytes"])
with open(datafile.datFileName, "rb") as f:
@@ -115,6 +149,11 @@ def _mcos_property_sets(blob: bytes, start: int, end: int) -> list:
Each set is a uint32 count followed by (name, type, value) triples,
padded to 8 bytes.
+
+ Returns
+ -------
+ list
+ One (n, 3) int array of (name, type, value) triples per property set.
"""
words = np.frombuffer(blob[start:end], " list:
return sets
-def _mcos_object_properties(h, object_id: int) -> dict:
- """Saved properties of one MCOS object of an open v7.3 MAT file.
+def _mcos_object_properties(h: h5py.File, object_id: int) -> dict:
+ """Read the saved properties of one MCOS object of an open v7.3 MAT file.
- The ``FileWrapper__`` blob (first cell of ``#subsystem#/MCOS``) holds a
+ The ``FileWrapper__`` blob (first cell of #subsystem#/MCOS) holds a
string table and segments for classes, objects and property sets; each
object row gives the indexes of its two property sets.
@@ -139,6 +178,11 @@ def _mcos_object_properties(h, object_id: int) -> dict:
dict
Property name -> its value: an array for values saved as cells,
a string or an integer for values saved inline.
+
+ Raises
+ ------
+ ValueError
+ If `object_id` does not match exactly one object in the file.
"""
import struct
@@ -167,8 +211,14 @@ def _mcos_object_properties(h, object_id: int) -> dict:
return props
-def _wall_clock_ms(ms: float, tz: str):
- """UTC milliseconds since 1970 as the wall clock of time zone ``tz``."""
+def _wall_clock_ms(ms: float, tz: str) -> float | None:
+ """UTC milliseconds since 1970 as the wall clock of time zone tz.
+
+ Returns
+ -------
+ float or None
+ The wall-clock milliseconds since 1970 in tz, or None if tz is unknown.
+ """
import datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
@@ -182,41 +232,45 @@ def _wall_clock_ms(ms: float, tz: str):
return wall / datetime.timedelta(milliseconds=1)
-def _text(value) -> str:
- """A MATLAB char array (uint16 codes) or string as ``str``."""
+def _text(value: object) -> str:
+ """Convert a MATLAB char array (uint16 codes) or string to str.
+
+ Returns
+ -------
+ str
+ The text, empty for an empty array.
+ """
if isinstance(value, np.ndarray):
return "".join(map(chr, value.ravel())) if value.size else ""
return str(value)
-def read_mat_datetime_ms(
- path: Union[str, Path], name: str, offset_ms: float = 0.0
-):
- """A MATLAB ``datetime`` saved in a v7.3 MAT file, as wall-clock ms.
+def read_mat_datetime_ms(path: str | Path, name: str, offset_ms: float = 0.0) -> float | None:
+ """Read a MATLAB datetime saved in a v7.3 MAT file, as wall-clock ms.
- MATLAB stores a ``datetime`` as an MCOS object whose ``data`` property is
+ MATLAB stores a datetime as an MCOS object whose data property is
milliseconds since 1970-01-01 (a complex double: whole and fractional
- parts) and whose ``tz`` property, when set, names the time zone in which
- ``data`` is UTC.
+ parts) and whose tz property, when set, names the time zone in which
+ data is UTC.
Parameters
----------
path : str or Path
- The MAT (v7.3, HDF5) file, e.g. a SLAP2 ``.meta`` file.
+ The MAT (v7.3, HDF5) file, e.g. a SLAP2 .meta file.
name : str
- Top-level variable name, e.g. ``"fpgaTimeReference"``.
+ Top-level variable name, e.g. "fpgaTimeReference".
offset_ms : float
Elapsed milliseconds to add first. For a zoned value they are added
in UTC, before the conversion to wall-clock time, so an offset that
crosses a daylight-saving change is exact, as MATLAB's
- ``datetime + seconds(...)`` is.
+ datetime + seconds(...) is.
Returns
-------
float or None
Milliseconds since 1970-01-01 of the local (wall-clock) time, which
- MATLAB's ``datenum`` of the value uses; None when the value is
- missing, not a scalar, or not a ``datetime`` this reader
+ MATLAB's datenum of the value uses; None when the value is
+ missing, not a scalar, or not a datetime this reader
understands.
"""
import struct
@@ -252,13 +306,19 @@ def read_mat_datetime_ms(
return _wall_clock_ms(ms, tz) if tz else ms
-def open_slap2_file(path: Union[str, Path]) -> Slap2Reader:
+def open_slap2_file(path: str | Path) -> Slap2Reader:
"""Lazily open DataFile/MultiDataFiles; return ownership to the caller.
A file of a CYCLE-split recording opens the whole recording (all its
files), so line and cycle indexes run over the recording, as in
GIAnT-MATLAB. Keeps the module reload. No reads, close, copying, or early
resource disposal are performed here.
+
+ Returns
+ -------
+ Slap2Reader
+ A slap2_utils.MultiDataFiles for a CYCLE-split recording, else a
+ slap2_utils.DataFile, which the caller owns.
"""
import importlib
diff --git a/src/giant_python/io/slap2_raster.py b/src/giant_python/io/slap2_raster.py
index 47d9ba1c..b4ac071d 100644
--- a/src/giant_python/io/slap2_raster.py
+++ b/src/giant_python/io/slap2_raster.py
@@ -1,41 +1,42 @@
"""Raster sample layout, raw sample reads and line headers of SLAP2 files.
-The vendor reader (``slap2_utils``) parses the file header and parse plan;
+The vendor reader (slap2_utils) parses the file header and parse plan;
this module turns them into flat tables for reading every raster sample of a
-range of cycles at once, as GIAnT-MATLAB's ``slap2FrameSums`` does with its
+range of cycles at once, as GIAnT-MATLAB's slap2FrameSums does with its
file reader, and decodes the online-motion fields of line headers, as
-``getOnlineMotion`` does.
+getOnlineMotion does.
-Conventions: line indices within a cycle (``slot_line``) and global line
+Conventions: line indices within a cycle (slot_line) and global line
numbers are one-based, as in MATLAB. Cycle indices are zero-based. Pixel IDs
-are one-based and row-major over the DMD (``(row - 1) * n_cols + col``).
+are one-based and row-major over the DMD ((row - 1) * n_cols + col).
Samples behind the DMD curtain
------------------------------
The acquisition software blanks the DMD mirrors outside the acquisition
-path's curtain (``dmdCurtain``, fractions of the DMD width, sheared per DMD
-row by the DMD's ``lineShear``). The blanking is fixed on the DMD, while the
+path's curtain (dmdCurtain, fractions of the DMD width, sheared per DMD
+row by the DMD's lineShear). The blanking is fixed on the DMD, while the
online motion correction moves the pattern by each line's offsets, and the
DMD has no motion padding in x. A raster superpixel that the x offset moves
behind the curtain is still sampled, but receives no light: its samples are
valid and near 0. :func:`unlit_samples` finds them with the software's own
mask (before it is rounded to DMD mask blocks): the mirror at zero-based
-column ``m`` and row ``r`` is lit when ``c1 + 1/N <= m/(N - 1) - shear[r]/N
-<= c2 - 1/N`` (``N`` DMD columns), and a sample of the pixel at zero-based
-``(row, col)`` on a line with online offsets ``(x, y)`` sits at ``m = col +
-x``, ``r = row + y`` (the header's x, the y on the DMD).
-:func:`read_raster_samples` (``mask_unlit=True``) marks them invalid, so
+column m and row r is lit when c1 + 1/N <= m/(N - 1) - shear[r]/N
+<= c2 - 1/N (N DMD columns), and a sample of the pixel at zero-based
+(row, col) on a line with online offsets (x, y) sits at m = col +
+x, r = row + y (the header's x, the y on the DMD).
+:func:`read_raster_samples` (mask_unlit=True) marks them invalid, so
that frames give them no weight.
"""
import logging
+from collections.abc import Iterator, Sequence
from dataclasses import dataclass
from pathlib import Path
-from typing import Optional, Sequence, Tuple, Union
import numpy as np
+from numpy.typing import ArrayLike
-from .slap2 import open_slap2_file
+from .slap2 import Slap2Reader, open_slap2_file
log = logging.getLogger(__name__)
@@ -43,7 +44,7 @@
"""Raw value marking a sample the acquisition did not record."""
_PLACEHOLDER_Z = -10203
-"""First entry of ``slap2_utils`` ``fastZs`` for old-format metadata."""
+"""First entry of slap2_utils fastZs for old-format metadata."""
@dataclass(frozen=True)
@@ -61,10 +62,10 @@ class RasterLayout:
words_per_cycle : int
Words per cycle, identical in every file.
lines_per_cycle : int
- Lines per cycle (``P``).
+ Lines per cycle (P).
n_rows, n_cols : int
- DMD image rows (``dmdPixelsPerColumn``) and columns
- (``dmdPixelsPerRow``).
+ DMD image rows (dmdPixelsPerColumn) and columns
+ (dmdPixelsPerRow).
num_channels : int
Recorded channels.
line_period_s : float
@@ -88,15 +89,15 @@ class RasterLayout:
slot_pixel : ndarray of int
One-based DMD pixel ID of each raster slot.
dmd_curtain : ndarray of float, optional
- ``[c1, c2]``: the acquisition path's curtain (``dmdCurtain``) as
+ [c1, c2]: the acquisition path's curtain (dmdCurtain) as
fractions of the DMD width; mirrors outside it are blanked. None when
the metadata do not record it (no sample is then taken as unlit).
line_shear : ndarray of float, optional
- Shear of each DMD row in pixels (the DMD's ``lineShear``), which the
+ Shear of each DMD row in pixels (the DMD's lineShear), which the
curtain follows; zeros when the metadata do not record it.
"""
- files: Tuple[str, ...]
+ files: tuple[str, ...]
file_cycles: np.ndarray
file_offset_words: np.ndarray
words_per_cycle: int
@@ -114,8 +115,8 @@ class RasterLayout:
slot_line: np.ndarray
slot_pos: np.ndarray
slot_pixel: np.ndarray
- dmd_curtain: Optional[np.ndarray] = None
- line_shear: Optional[np.ndarray] = None
+ dmd_curtain: np.ndarray | None = None
+ line_shear: np.ndarray | None = None
@property
def num_cycles(self) -> int:
@@ -128,11 +129,21 @@ def total_lines(self) -> int:
return self.num_cycles * self.lines_per_cycle
-def _line_ids(ids, n_samples: int) -> np.ndarray:
+def _line_ids(ids: ArrayLike, n_samples: int) -> np.ndarray:
"""Superpixel IDs of one line, checked against its sample count.
- ``slap2_utils`` decodes an empty MATLAB array of the parse plan as its
- dimensions (``[0, 1]``); a line without samples has no superpixels.
+ slap2_utils decodes an empty MATLAB array of the parse plan as its
+ dimensions ([0, 1]); a line without samples has no superpixels.
+
+ Returns
+ -------
+ np.ndarray
+ The superpixel IDs as a flat int64 array; empty when the line has no samples.
+
+ Raises
+ ------
+ ValueError
+ If the number of superpixel IDs differs from the line's sample count.
"""
ids = np.asarray(ids).ravel().astype(np.int64)
if n_samples == 0:
@@ -145,13 +156,26 @@ def _line_ids(ids, n_samples: int) -> np.ndarray:
return ids
-def _data_files(reader) -> list:
- """The ``DataFile`` objects of a reader, in cycle order."""
+def _data_files(reader: Slap2Reader) -> list:
+ """List the DataFile objects of a reader, in cycle order.
+
+ Returns
+ -------
+ list
+ The reader's hDataFiles, or the reader itself as a one-element list when it
+ has none.
+ """
return list(getattr(reader, "hDataFiles", None) or [reader])
-def _text(value) -> str:
- """A metadata string; ``slap2_utils`` gives some as character codes."""
+def _text(value: object) -> str:
+ """Decode a metadata string; slap2_utils gives some as character codes.
+
+ Returns
+ -------
+ str
+ The decoded string; empty when value is None.
+ """
if isinstance(value, str):
return value
if value is None:
@@ -159,19 +183,24 @@ def _text(value) -> str:
return "".join(chr(int(c)) for c in np.asarray(value).ravel())
-def _dmd_curtain(meta, n_rows: int):
- """The acquisition path's curtain and its DMD's line shear.
+def _dmd_curtain(meta: object, n_rows: int) -> tuple[np.ndarray | None, np.ndarray | None]:
+ """Read the acquisition path's curtain and its DMD's line shear.
- Returns ``(None, None)`` when the metadata do not record a curtain;
- the shear is zeros when the DMD's ``lineShear`` is missing or does not
+ Returns (None, None) when the metadata do not record a curtain;
+ the shear is zeros when the DMD's lineShear is missing or does not
have one value per DMD row.
+
+ Returns
+ -------
+ curtain : np.ndarray or None
+ The two-element dmdCurtain of the acquisition path, or None when not recorded.
+ shear : np.ndarray or None
+ The DMD line shear with one value per DMD row, or None when curtain is None.
"""
config = {}
for device in getattr(meta, "machineConfiguration", None) or []:
if isinstance(device, dict):
- config[_text(device.get("instanceName"))] = (
- device.get("configuration") or {}
- )
+ config[_text(device.get("instanceName"))] = device.get("configuration") or {}
path = config.get(_text(getattr(meta, "acquisitionPathName", "")))
if not isinstance(path, dict) or "dmdCurtain" not in path:
return None, None
@@ -188,20 +217,25 @@ def _dmd_curtain(meta, n_rows: int):
return curtain, shear
-def raster_layout(path: Union[str, Path]) -> RasterLayout:
+def raster_layout(path: str | Path) -> RasterLayout:
"""Read the raster sample layout of a SLAP2 recording.
Parameters
----------
path : str or Path
- A ``.dat`` file; CYCLE-split recordings are opened as one recording,
- as ``open_slap2_file`` does.
+ A .dat file; CYCLE-split recordings are opened as one recording,
+ as open_slap2_file does.
Returns
-------
RasterLayout
The layout; only raster superpixels (IDs within the DMD) are listed,
- as with ``getImage(..., spTypeFlag = 1)``.
+ as with getImage(..., spTypeFlag = 1).
+
+ Raises
+ ------
+ ValueError
+ If the recording has interleaved channels, or if its files differ in layout.
"""
reader = open_slap2_file(path)
files = _data_files(reader)
@@ -239,9 +273,7 @@ def raster_layout(path: Union[str, Path]) -> RasterLayout:
return RasterLayout(
files=tuple(str(df.datFileName) for df in files),
file_cycles=np.array([int(df.numCycles) for df in files]),
- file_offset_words=np.array(
- [int(df.header["firstCycleOffsetBytes"]) // 2 for df in files]
- ),
+ file_offset_words=np.array([int(df.header["firstCycleOffsetBytes"]) // 2 for df in files]),
words_per_cycle=words,
lines_per_cycle=p,
n_rows=n_rows,
@@ -262,8 +294,20 @@ def raster_layout(path: Union[str, Path]) -> RasterLayout:
)
-def _file_spans(layout: RasterLayout, c0: int, c1: int):
- """Yield (file index, first local cycle, count, output offset)."""
+def _file_spans(layout: RasterLayout, c0: int, c1: int) -> Iterator[tuple[int, int, int, int]]:
+ """Yield (file index, first local cycle, count, output offset).
+
+ Yields
+ ------
+ file : int
+ Index of the file.
+ first : int
+ First cycle to read, local to the file.
+ count : int
+ Number of cycles to read from the file.
+ offset : int
+ Offset of those cycles in the output.
+ """
ends = np.cumsum(layout.file_cycles)
starts = ends - layout.file_cycles
for f, (s, e) in enumerate(zip(starts, ends)):
@@ -274,8 +318,8 @@ def _file_spans(layout: RasterLayout, c0: int, c1: int):
def read_raster_samples(
layout: RasterLayout,
- cycles: Tuple[int, int],
- slots: Union[np.ndarray, None] = None,
+ cycles: tuple[int, int],
+ slots: np.ndarray | None = None,
chunk_cycles: int = 256,
mask_unlit: bool = False,
) -> np.ndarray:
@@ -286,21 +330,26 @@ def read_raster_samples(
layout : RasterLayout
The recording's layout.
cycles : (int, int)
- Zero-based cycle range ``[c0, c1)``.
+ Zero-based cycle range [c0, c1).
slots : ndarray of int, optional
Raster slots to read (default: all).
chunk_cycles : int
Cycles read from a file at a time, bounding temporary memory.
mask_unlit : bool
Set the samples taken behind the DMD curtain (see
- :func:`unlit_samples`) to ``INVALID_SAMPLE`` in every channel, so
+ :func:`unlit_samples`) to INVALID_SAMPLE in every channel, so
that frames formed from them give them no weight. Default: the raw
values.
Returns
-------
ndarray of int16
- Samples, shaped ``(channels, slots, cycles)``.
+ Samples, shaped (channels, slots, cycles).
+
+ Raises
+ ------
+ ValueError
+ If the cycle range is not within the recording.
"""
c0, c1 = int(cycles[0]), int(cycles[1])
if not 0 <= c0 <= c1 <= layout.num_cycles:
@@ -309,9 +358,7 @@ def read_raster_samples(
slots = np.arange(layout.slot_line.size)
lines = layout.slot_line[slots] - 1
word = [
- layout.row_base[lines]
- + ch * layout.n_per_channel[lines]
- + layout.slot_pos[slots]
+ layout.row_base[lines] + ch * layout.n_per_channel[lines] + layout.slot_pos[slots]
for ch in range(layout.num_channels)
]
out = np.empty((layout.num_channels, slots.size, c1 - c0), dtype=np.int16)
@@ -335,8 +382,7 @@ def read_raster_samples(
out[:, s, c] = INVALID_SAMPLE
if s.size:
log.debug(
- "%d samples of %d slots in cycles %d-%d are behind the DMD "
- "curtain",
+ "%d samples of %d slots in cycles %d-%d are behind the DMD curtain",
s.size,
np.unique(s).size,
c0,
@@ -347,11 +393,11 @@ def read_raster_samples(
def read_line_offsets(
layout: RasterLayout, lines: Sequence[int]
-) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Online-motion offsets recorded in the headers of given lines.
- Line header layout (bytes): 20-21 ``xOffset_pix`` (int16), 22-23
- ``yOffset_pix`` (int16), 32-35 ``zOffset_um`` (float32, present only
+ Line header layout (bytes): 20-21 xOffset_pix (int16), 22-23
+ yOffset_pix (int16), 32-35 zOffset_um (float32, present only
when headers are longer than 32 bytes; 0 otherwise).
Parameters
@@ -364,7 +410,12 @@ def read_line_offsets(
Returns
-------
x, y, z : ndarray of float
- Offsets of each line, as GIAnT-MATLAB ``getOnlineMotion`` returns.
+ Offsets of each line, as GIAnT-MATLAB getOnlineMotion returns.
+
+ Raises
+ ------
+ ValueError
+ If a line number is not within the recording.
"""
lines = np.asarray(lines, dtype=np.int64).ravel()
p = layout.lines_per_cycle
@@ -396,13 +447,13 @@ def read_line_offsets(
return x, y, z
-def lit_mirrors(layout: RasterLayout, rows, cols) -> np.ndarray:
+def lit_mirrors(layout: RasterLayout, rows: ArrayLike, cols: ArrayLike) -> np.ndarray:
"""Whether the DMD curtain leaves mirrors lit.
Parameters
----------
layout : RasterLayout
- The recording's layout, with ``dmd_curtain`` set.
+ The recording's layout, with dmd_curtain set.
rows, cols : array_like of int
Zero-based DMD rows and columns (broadcast together); rows outside
the DMD take the shear of the nearest row.
@@ -410,9 +461,9 @@ def lit_mirrors(layout: RasterLayout, rows, cols) -> np.ndarray:
Returns
-------
ndarray of bool
- True where ``c1 + 1/N <= col/(N - 1) - shear[row]/N <= c2 - 1/N``,
+ True where c1 + 1/N <= col/(N - 1) - shear[row]/N <= c2 - 1/N,
the acquisition software's curtain mask before it is rounded to DMD
- mask blocks (``N`` DMD columns).
+ mask blocks (N DMD columns).
"""
n = layout.n_cols
c1, c2 = (float(v) for v in layout.dmd_curtain)
@@ -426,18 +477,18 @@ def lit_mirrors(layout: RasterLayout, rows, cols) -> np.ndarray:
def unlit_samples(
layout: RasterLayout,
- cycles: Tuple[int, int],
- slots: Union[np.ndarray, None] = None,
+ cycles: tuple[int, int],
+ slots: np.ndarray | None = None,
block_slots: int = 2048,
-) -> Tuple[np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray]:
"""Raster samples that the online offsets put behind the DMD curtain.
- A sample of the pixel at zero-based ``(row, col)`` on a line with
- online offsets ``(x, y)`` was taken through the mirror at ``(row + y,
- col + x)``; it is unlit where :func:`lit_mirrors` is False there. x is
+ A sample of the pixel at zero-based (row, col) on a line with
+ online offsets (x, y) was taken through the mirror at (row + y,
+ col + x); it is unlit where :func:`lit_mirrors` is False there. x is
the header's (it reaches the DMD on the line whose header first records
it); y is the one on the DMD, which switches 2-6 lines before the
- header records it (``y_eff`` of
+ header records it (y_eff of
:func:`giant_python.registration.compensation.line_offsets`). y only
selects the row's shear.
@@ -446,7 +497,7 @@ def unlit_samples(
layout : RasterLayout
The recording's layout.
cycles : (int, int)
- Zero-based cycle range ``[c0, c1)``.
+ Zero-based cycle range [c0, c1).
slots : ndarray of int, optional
Raster slots (default: all).
block_slots : int
@@ -455,7 +506,7 @@ def unlit_samples(
Returns
-------
slot, cycle : ndarray of int
- Positions in ``slots`` and cycles relative to ``c0`` of the unlit
+ Positions in slots and cycles relative to c0 of the unlit
samples; empty when the layout records no curtain.
"""
empty = np.zeros(0, dtype=np.int64)
@@ -496,9 +547,7 @@ def unlit_samples(
hi = int(np.min(layout.n_cols - 1 - np.argmax(grid[:, ::-1], 1)))
else: # a row without lit mirrors: test every slot
lo, hi = layout.n_cols, -1
- near = np.flatnonzero(
- (cols + x.min(0)[lines] < lo) | (cols + x.max(0)[lines] > hi)
- )
+ near = np.flatnonzero((cols + x.min(0)[lines] < lo) | (cols + x.max(0)[lines] > hi))
out_s, out_c = [], []
for a in range(0, near.size, block_slots):
idx = near[a : a + block_slots]
diff --git a/src/giant_python/io/tiff.py b/src/giant_python/io/tiff.py
index 43625f6f..f5dc9268 100644
--- a/src/giant_python/io/tiff.py
+++ b/src/giant_python/io/tiff.py
@@ -1,16 +1,20 @@
"""Native TIFF array reading without acquisition-specific transformations."""
from pathlib import Path
-from typing import Union
import numpy as np
-def read_tiff(path: Union[str, Path]) -> np.ndarray:
+def read_tiff(path: str | Path) -> np.ndarray:
"""Read a TIFF eagerly, preserving native dtype, rank and page ordering.
Reference intensity scaling, channel reshaping and PSF cropping are
caller policies, not generic TIFF decoding. Import tifffile only on use.
+
+ Returns
+ -------
+ np.ndarray
+ The TIFF pages as read by tifffile.imread, with native dtype.
"""
import tifffile
diff --git a/src/giant_python/io/trial_table.py b/src/giant_python/io/trial_table.py
index bc2b3f38..cb4ee590 100644
--- a/src/giant_python/io/trial_table.py
+++ b/src/giant_python/io/trial_table.py
@@ -1,17 +1,22 @@
"""Faithful trial-table schema decoding, without runtime file discovery."""
from pathlib import Path
-from typing import Optional, Union
import numpy as np
+from ..models.trial_table import Slap2Info, TrialTable
from .hdf5 import load_struct_h5
-def slap2_info_from_raw(slap2: Optional[dict]):
- """Decode recognized SLAP2 metadata; keep absent metadata absent."""
- from ..models.trial_table import Slap2Info
+def slap2_info_from_raw(slap2: dict | None) -> Slap2Info | None:
+ """Decode recognized SLAP2 metadata; keep absent metadata absent.
+ Returns
+ -------
+ Slap2Info | None
+ Decoded metadata holding the recognized keys present in `slap2`, or None when `slap2`
+ is None or empty.
+ """
if not slap2:
return None
names = (
@@ -24,21 +29,23 @@ def slap2_info_from_raw(slap2: Optional[dict]):
return Slap2Info(**{key: slap2[key] for key in names if key in slap2})
-def read_trial_table(path: Union[str, Path]):
+def read_trial_table(path: str | Path) -> TrialTable:
"""Return an eager TrialTable with source provenance, no path resolution.
- ``source_path`` records the input filename and is not part of disk data.
+ source_path records the input filename and is not part of disk data.
Numeric ranks are retained; the filename string grid is always rank two.
- """
- from ..models.trial_table import TrialTable
+ Returns
+ -------
+ TrialTable
+ Trial table decoded from the HDF5 file at `path`, with source_path set to the
+ absolute input path.
+ """
raw = load_struct_h5(path)
return TrialTable(
datadr=Path(raw["datadr"]) if raw.get("datadr") else None,
savedr=Path(raw["savedr"]) if raw.get("savedr") else None,
- filename=np.atleast_2d(
- np.asarray(raw.get("filename", []), dtype=object)
- ),
+ filename=np.atleast_2d(np.asarray(raw.get("filename", []), dtype=object)),
true_trial_ix=raw.get("true_trial_ix", []),
epoch=raw.get("epoch", []),
slap2_info=slap2_info_from_raw(raw.get("slap2_info")),
diff --git a/src/giant_python/models/__init__.py b/src/giant_python/models/__init__.py
index 69c7f197..97680e44 100644
--- a/src/giant_python/models/__init__.py
+++ b/src/giant_python/models/__init__.py
@@ -33,9 +33,6 @@
"FrameInfo",
"MultiRoiRegistrationParams",
"PathSummary",
- "resolve_band_options",
- "resolve_registration_options",
- "resolve_silo_options",
"SiloExecution",
"SiloParams",
"Slap2Info",
@@ -43,4 +40,7 @@
"TrialTable",
"UserRoi",
"Visualizations",
+ "resolve_band_options",
+ "resolve_registration_options",
+ "resolve_silo_options",
]
diff --git a/src/giant_python/models/experiment_summary.py b/src/giant_python/models/experiment_summary.py
index b118ce29..b7a9a349 100644
--- a/src/giant_python/models/experiment_summary.py
+++ b/src/giant_python/models/experiment_summary.py
@@ -1,19 +1,18 @@
-"""Experiment summary model (``exptSummary`` / experiment_summary.h5).
+"""Experiment summary model (exptSummary / experiment_summary.h5).
The model holds what BandSILo and raster SILo write. Fields that only raster
SILo writes are optional and None (or empty) for BandSILo output: per
-source ``kinetic_score``, ``kinetic_n_events`` and ``spot_id``; per path
-``rejected``, ``spots``, ``visualizations.f0_im`` and the across-trial maps
-in ``frame_info``; the file's root attributes in ``ExperimentSummary.attrs``.
+source kinetic_score, kinetic_n_events and spot_id; per path
+rejected, spots, visualizations.f0_im and the across-trial maps
+in frame_info; the file's root attributes in ExperimentSummary.attrs.
Arrays have the dimension order of the README's field table (MATLAB's
-``size()``), whichever program wrote the file.
+size()), whichever program wrote the file.
"""
from __future__ import annotations
from dataclasses import dataclass, field, fields
from pathlib import Path
-from typing import Optional, Union
import numpy as np
@@ -22,74 +21,74 @@
class Source:
"""A single extracted source (bouton/spine) with spatial + temporal data.
- Mirrors one entry of the ``sources`` struct array in GIAnT-MATLAB.
+ Mirrors one entry of the sources struct array in GIAnT-MATLAB.
Attributes
----------
profile : ndarray or None
- Spatial profile, shaped ``(fastz, rows, cols)``.
+ Spatial profile, shaped (fastz, rows, cols).
coords : ndarray or None
- 0-indexed ``[z, y, x]`` location.
+ 0-indexed [z, y, x] location.
df_ls, df_denoised, events : ndarray or None
Least-squares dF after baseline re-estimation, the fitted convolution
trace (without another baseline subtraction), and nonnegative event
- amplitudes, shaped ``(channels, frames)``. Missing observations and
+ amplitudes, shaped (channels, frames). Missing observations and
unprocessed channels are NaN. Events exclude each trial's initial
state.
f0 : ndarray or None
Per-channel baseline.
f0_core : ndarray or None
Raster SILo's baseline of the source's core in footprint units
- (``sources/temporal/F0_core``), shaped ``(channels, frames)``:
- ``df_ls / f0_core`` is the dF/F of the 3 x 3 pixels around the
+ (sources/temporal/F0_core), shaped (channels, frames):
+ df_ls / f0_core is the dF/F of the 3 x 3 pixels around the
footprint's peak, which does not depend on the footprint's support.
None in files without it.
snr : float or None
Signal-to-noise ratio.
kinetic_score, kinetic_n_events : float, int or None
- Raster SILo's kinetics test (``sources/temporal/kinetic_score``,
- ``kinetic_n_events``).
+ Raster SILo's kinetics test (sources/temporal/kinetic_score,
+ kinetic_n_events).
spot_id : int or None
- Raster SILo's spot annotation (``sources/spatial/spot_id``): the
- spot, numbered from 1 as in the file (row ``spot_id - 1`` of the
- path's ``spots``).
+ Raster SILo's spot annotation (sources/spatial/spot_id): the
+ spot, numbered from 1 as in the file (row spot_id - 1 of the
+ path's spots).
"""
- profile: Optional[np.ndarray] = None
- coords: Optional[np.ndarray] = None
- df_ls: Optional[np.ndarray] = None
- df_denoised: Optional[np.ndarray] = None
- events: Optional[np.ndarray] = None
- f0: Optional[np.ndarray] = None
- f0_core: Optional[np.ndarray] = None
- snr: Optional[Union[float, np.floating]] = None
- kinetic_score: Optional[float] = None
- kinetic_n_events: Optional[int] = None
- spot_id: Optional[int] = None
+ profile: np.ndarray | None = None
+ coords: np.ndarray | None = None
+ df_ls: np.ndarray | None = None
+ df_denoised: np.ndarray | None = None
+ events: np.ndarray | None = None
+ f0: np.ndarray | None = None
+ f0_core: np.ndarray | None = None
+ snr: float | np.floating | None = None
+ kinetic_score: float | None = None
+ kinetic_n_events: int | None = None
+ spot_id: int | None = None
@dataclass
class UserRoi:
"""A manually drawn ROI (annotations.h5) and its extracted traces.
- Mirrors one entry of the ``Path{n}/roi_###`` group in ``annotations.h5``
- (geometry) together with the corresponding ``user_rois`` entry in
- ``experiment_summary.h5`` (traces).
+ Mirrors one entry of the Path{n}/roi_### group in annotations.h5
+ (geometry) together with the corresponding user_rois entry in
+ experiment_summary.h5 (traces).
Attributes
----------
type : str
- ``"polygon"``, ``"circle"``, or ``"ellipse"``.
+ "polygon", "circle", or "ellipse".
label : str
- User label (e.g. ``"SOMA"``).
+ User label (e.g. "SOMA").
mask : ndarray or None
- Binary mask. 2-D ``(rows, cols)`` in annotations.h5; ``(fastz, rows,
- cols)`` in experiment_summary.h5.
+ Binary mask. 2-D (rows, cols) in annotations.h5; (fastz, rows,
+ cols) in experiment_summary.h5.
position : ndarray or None
- Polygon vertices ``[y, x]`` (polygon ROIs); 0-indexed when the source
- file sets ``coords_zero_indexed``.
+ Polygon vertices [y, x] (polygon ROIs); 0-indexed when the source
+ file sets coords_zero_indexed.
center : ndarray or None
- Center ``[y, x]`` (circle/ellipse ROIs).
+ Center [y, x] (circle/ellipse ROIs).
radius : float or None
Radius (circle ROIs).
semi_axes : ndarray or None
@@ -97,50 +96,50 @@ class UserRoi:
rotation_angle : float or None
Rotation angle (ellipse ROIs).
fsvd : ndarray or None
- ROI signal after SVD / projection, shaped ``(channels, total frames)``
- (``experiment_summary.h5`` ``user_rois/Fsvd``). Band extraction does
+ ROI signal after SVD / projection, shaped (channels, total frames)
+ (experiment_summary.h5 user_rois/Fsvd). Band extraction does
not compute this signal; the writer uses NaN when unavailable.
f : ndarray or None
Raw or baseline-corrected ROI fluorescence, shaped
- ``(channels, total frames)``
- (``experiment_summary.h5`` ``user_rois/F``).
+ (channels, total frames)
+ (experiment_summary.h5 user_rois/F).
"""
type: str = "polygon"
label: str = ""
- mask: Optional[np.ndarray] = None
- position: Optional[np.ndarray] = None
- center: Optional[np.ndarray] = None
- radius: Optional[float] = None
- semi_axes: Optional[np.ndarray] = None
- rotation_angle: Optional[float] = None
- fsvd: Optional[np.ndarray] = None
- f: Optional[np.ndarray] = None
+ mask: np.ndarray | None = None
+ position: np.ndarray | None = None
+ center: np.ndarray | None = None
+ radius: float | None = None
+ semi_axes: np.ndarray | None = None
+ rotation_angle: float | None = None
+ fsvd: np.ndarray | None = None
+ f: np.ndarray | None = None
@dataclass
class Visualizations:
- """Summary images for QC/display (``exptSummary.visualizations``).
+ """Summary images for QC/display (exptSummary.visualizations).
Attributes
----------
mean_im : ndarray or None
- Mean registered image, shaped ``(channels, fastz, rows, cols)``.
+ Mean registered image, shaped (channels, fastz, rows, cols).
act_im : ndarray or None
- Activity / localization summary image, shaped ``(fastz, rows, cols)``.
+ Activity / localization summary image, shaped (fastz, rows, cols).
act_im_peaks : ndarray or None
- Activity-image peak locations, shaped ``(peaks, 3)`` as 0-indexed
- ``[z_loc, y_loc, x_loc]``; raster SILo writes none without kept
+ Activity-image peak locations, shaped (peaks, 3) as 0-indexed
+ [z_loc, y_loc, x_loc]; raster SILo writes none without kept
sources.
f0_im : ndarray or None
- Raster SILo's baseline image (``F0_im``), shaped ``(channels, fastz,
- rows, cols)``.
+ Raster SILo's baseline image (F0_im), shaped (channels, fastz,
+ rows, cols).
"""
- mean_im: Optional[np.ndarray] = None
- act_im: Optional[np.ndarray] = None
- act_im_peaks: Optional[np.ndarray] = None
- f0_im: Optional[np.ndarray] = None
+ mean_im: np.ndarray | None = None
+ act_im: np.ndarray | None = None
+ act_im_peaks: np.ndarray | None = None
+ f0_im: np.ndarray | None = None
@dataclass
@@ -150,31 +149,38 @@ class FrameInfo:
Offline shifts carry saved MATLAB displacement, NOT private band
reference offsets. No conversion occurs in this model or its codec.
Frame line indexes remain 1-based; emitted vectors retain rank two.
- ``to_dict`` returns a shallow mapping, sharing the original arrays.
- A field the file lacks is None: raster SILo writes ``offlineZshifts``
+ to_dict returns a shallow mapping, sharing the original arrays.
+ A field the file lacks is None: raster SILo writes offlineZshifts
only when the registration estimated axial motion, and only raster SILo
- writes ``trial_alignment_affine`` ``(trials, 2, 3)`` and, with
- patchwise alignment, ``trial_alignment_displacement`` ``(trials, 2,
- rows, cols)``. Raster SILo writes ``trial_frame_offset`` ``(trials, 2)``
+ writes trial_alignment_affine (trials, 2, 3) and, with
+ patchwise alignment, trial_alignment_displacement (trials, 2,
+ rows, cols). Raster SILo writes trial_frame_offset (trials, 2)
(rows, columns) only when the trials' registered images start at
different raster positions (the ROIs changed between acquisitions).
"""
- trial_num_frames: Optional[np.ndarray] = None
- discard_frames: Optional[np.ndarray] = None
- frame_line_idxs: Optional[np.ndarray] = None
- offlineXshifts: Optional[np.ndarray] = None
- offlineYshifts: Optional[np.ndarray] = None
- offlineZshifts: Optional[np.ndarray] = None
- onlineXshifts: Optional[np.ndarray] = None
- onlineYshifts: Optional[np.ndarray] = None
- onlineZshifts: Optional[np.ndarray] = None
- trial_alignment_affine: Optional[np.ndarray] = None
- trial_alignment_displacement: Optional[np.ndarray] = None
- trial_frame_offset: Optional[np.ndarray] = None
+ trial_num_frames: np.ndarray | None = None
+ discard_frames: np.ndarray | None = None
+ frame_line_idxs: np.ndarray | None = None
+ offlineXshifts: np.ndarray | None = None
+ offlineYshifts: np.ndarray | None = None
+ offlineZshifts: np.ndarray | None = None
+ onlineXshifts: np.ndarray | None = None
+ onlineYshifts: np.ndarray | None = None
+ onlineZshifts: np.ndarray | None = None
+ trial_alignment_affine: np.ndarray | None = None
+ trial_alignment_displacement: np.ndarray | None = None
+ trial_frame_offset: np.ndarray | None = None
def to_dict(self) -> dict:
- """Return all frame fields without copying or changing their arrays."""
+ """Return all frame fields without copying or changing their arrays.
+
+ Returns
+ -------
+ dict
+ Mapping from each frame field's name to its array (or None), sharing
+ the original arrays.
+ """
return {item.name: getattr(self, item.name) for item in fields(self)}
@@ -186,21 +192,21 @@ class PathSummary:
"""All eager output for one imaging path, identified by a 0-based index.
Arrays remain NumPy-backed in memory; Source/UserRoi entries may be views
- of assembled arrays. ``annotation_enabled`` distinguishes disabled from
+ of assembled arrays. annotation_enabled distinguishes disabled from
enabled-but-empty annotations (saved as an ROI group attribute). Private
empty-array templates retain dimensions and dtypes that cannot be inferred
from empty lists; they never duplicate populated source or ROI tensors.
- Raster SILo's per-path extras are kept as the file has them: ``rejected``
- holds ``sources/rejected`` (``seed_coords`` ``(removed, 3)``,
- ``kinetic_score``, ``kinetic_n_events`` and, with the evidence test,
- ``weak``, ``SNR``, ``event_rate``, each ``(removed, 1)``), empty when no
- source was removed; ``spots`` holds ``sources/spots`` (each array
- ``(spots, 1)``) with its attributes as ``labels`` (list of names) and
- ``settings`` (dict), None without the annotation. ``global_f`` and
- ``z_depths`` are None when the file lacks them (raster SILo without
+ Raster SILo's per-path extras are kept as the file has them: rejected
+ holds sources/rejected (seed_coords (removed, 3),
+ kinetic_score, kinetic_n_events and, with the evidence test,
+ weak, SNR, event_rate, each (removed, 1)), empty when no
+ source was removed; spots holds sources/spots (each array
+ (spots, 1)) with its attributes as labels (list of names) and
+ settings (dict), None without the annotation. global_f and
+ z_depths are None when the file lacks them (raster SILo without
frames, or with an unknown depth). A private flag records that a file's
- sources had no ``SNR`` dataset (raster SILo when no trial gave one), so
+ sources had no SNR dataset (raster SILo when no trial gave one), so
that writing the path again leaves it out instead of writing NaN.
"""
@@ -209,24 +215,25 @@ class PathSummary:
user_rois: list[UserRoi] = field(default_factory=list)
visualizations: Visualizations = field(default_factory=Visualizations)
frame_info: FrameInfo = field(default_factory=FrameInfo)
- global_f: Optional[np.ndarray] = None
- z_depths: Optional[np.ndarray] = None
+ global_f: np.ndarray | None = None
+ z_depths: np.ndarray | None = None
annotation_enabled: bool = False
_empty_source_arrays: dict = field(default_factory=dict, repr=False)
_empty_roi_arrays: dict = field(default_factory=dict, repr=False)
_snr_absent: bool = field(default=False, repr=False)
rejected: dict = field(default_factory=dict)
- spots: Optional[dict] = None
+ spots: dict | None = None
- def __post_init__(self):
- """Validate path identity without copying any numerical arrays."""
- if (
- not isinstance(self.path_index, (int, np.integer))
- or self.path_index < 0
- ):
- raise ValueError(
- "path_index must be a nonnegative, 0-based integer"
- )
+ def __post_init__(self) -> None:
+ """Validate path identity without copying any numerical arrays.
+
+ Raises
+ ------
+ ValueError
+ If path_index is not a nonnegative integer.
+ """
+ if not isinstance(self.path_index, (int, np.integer)) or self.path_index < 0:
+ raise ValueError("path_index must be a nonnegative, 0-based integer")
@dataclass
@@ -234,28 +241,48 @@ class ExperimentSummary:
"""Eager, in-memory extraction output with explicit per-path ownership.
This is not a lazy or disk-backed model. All imaging data belongs to
- entries in ``paths``; only extraction parameters are shared. ``attrs``
+ entries in paths; only extraction parameters are shared. attrs
holds the file's root attributes (raster SILo's baseline records:
- ``baseline_source``, ``baseline_mode``, ``localization_baseline`` and
- the JSON strings ``network_baseline``, ``localization_network_baseline``).
+ baseline_source, baseline_mode, localization_baseline and
+ the JSON strings network_baseline, localization_network_baseline).
"""
paths: list[PathSummary] = field(default_factory=list)
- params: Optional[dict] = None
+ params: dict | None = None
attrs: dict = field(default_factory=dict)
@classmethod
- def from_h5(cls, path: Union[str, Path]) -> "ExperimentSummary":
- """Read an experiment summary eagerly, from BandSILo (``row_major``
- 1) or raster SILo (``row_major`` 0); see
- :func:`~giant_python.io.experiment_summary.read_summary`."""
+ def from_h5(cls, path: str | Path) -> ExperimentSummary:
+ """Read an experiment summary eagerly.
+
+ The file comes from BandSILo (row_major 1) or raster SILo
+ (row_major 0); see
+ :func:`~giant_python.io.experiment_summary.read_summary`.
+
+ Parameters
+ ----------
+ path : str or Path
+ Path of the experiment_summary.h5 file.
+
+ Returns
+ -------
+ ExperimentSummary
+ The experiment summary read from the file.
+ """
from ..io.experiment_summary import read_summary
return read_summary(path)
- def to_h5(self, path: Union[str, Path]) -> None:
- """Write band-schema output using the shared IO codec; return None
- (see :func:`~giant_python.io.experiment_summary.write_summary`)."""
+ def to_h5(self, path: str | Path) -> None:
+ """Write band-schema output using the shared IO codec; return None.
+
+ See :func:`~giant_python.io.experiment_summary.write_summary`.
+
+ Parameters
+ ----------
+ path : str or Path
+ Path of the experiment_summary.h5 file to write.
+ """
from ..io.experiment_summary import write_summary
write_summary(self, path)
diff --git a/src/giant_python/models/params.py b/src/giant_python/models/params.py
index a70e99d5..f339bac6 100644
--- a/src/giant_python/models/params.py
+++ b/src/giant_python/models/params.py
@@ -1,8 +1,8 @@
"""Scientific configuration and independent execution and annotation policy.
-``BandSiloParams`` contains only band science; ``SiloParams`` is the science
-of raster SILo (SLAP2 multi-ROI) and ``SiloExecution`` how it runs.
-``ExecutionOptions`` controls scheduling/debug limits; ``AnnotationOptions``
+BandSiloParams contains only band science; SiloParams is the science
+of raster SILo (SLAP2 multi-ROI) and SiloExecution how it runs.
+ExecutionOptions controls scheduling/debug limits; AnnotationOptions
controls ROI use and GUI policy. Resolution copies inputs without retuning
the existing algorithm.
"""
@@ -13,13 +13,26 @@
import re
from dataclasses import asdict, dataclass, fields
from numbers import Integral, Real
-from typing import Optional, Union
+from typing import TYPE_CHECKING, Optional
import numpy as np
+if TYPE_CHECKING:
+ from ..extraction.raster.localization import RasterLocalizationParams
+ from ..extraction.raster.plan import PlanParams
+ from ..extraction.raster.solver import SolverOptions
+ from ..extraction.raster.solver_setup import SolverParams
+ from ..extraction.raster.trial_data import TrialLoadParams
+
def _positive(name: str, value: object, *, integer: bool = False) -> None:
- """Reject nonfinite, nonpositive, boolean, or nonnumeric values."""
+ """Reject nonfinite, nonpositive, boolean, or nonnumeric values.
+
+ Raises
+ ------
+ ValueError
+ If value is not a positive finite number (a positive integer if integer).
+ """
kind = Integral if integer else Real
if (
isinstance(value, bool)
@@ -32,7 +45,13 @@ def _positive(name: str, value: object, *, integer: bool = False) -> None:
def _nonnegative(name: str, value: object) -> None:
- """Reject nonfinite, negative, boolean, or nonnumeric values."""
+ """Reject nonfinite, negative, boolean, or nonnumeric values.
+
+ Raises
+ ------
+ ValueError
+ If value is not a finite nonnegative number.
+ """
if (
isinstance(value, bool)
or not isinstance(value, Real)
@@ -116,7 +135,13 @@ class BandSiloParams:
random_seed: int = 0
def __post_init__(self) -> None:
- """Validate values supported by the existing numerical path."""
+ """Validate values supported by the existing numerical path.
+
+ Raises
+ ------
+ ValueError
+ If a setting is outside what the band algorithm supports.
+ """
for name in (
"analyze_hz",
"decay_tau_s",
@@ -148,8 +173,8 @@ class MultiRoiRegistrationParams:
"""Scientific settings for SLAP2 raster registration.
Field meanings and defaults follow GIAnT-MATLAB
- ``setParams('MultiRoiRegistration')``; they are saved under their MATLAB
- names in the trial table's ``motion_correction/align_params``.
+ setParams('MultiRoiRegistration'); they are saved under their MATLAB
+ names in the trial table's motion_correction/align_params.
Attributes
----------
@@ -168,7 +193,7 @@ class MultiRoiRegistrationParams:
this one), and registered again if not.
save_tif : bool
Save the registered movie as TIFF, as GIAnT-MATLAB does by default.
- Otherwise (the default) it is a deflated HDF5 ``/data``, about 7x
+ Otherwise (the default) it is a deflated HDF5 /data, about 7x
smaller, which GIAnT-MATLAB SILo also reads.
ref_stack_template, is_revolt, include_integration_rois : bool
MATLAB options not yet ported; must be False.
@@ -183,29 +208,29 @@ class MultiRoiRegistrationParams:
min_samples : int
Contributions a template pixel needs (MATLAB minSamps: 15).
schedule : str
- ``'sequential'`` (MATLAB's frame loop, the default) or ``'grow'``
+ 'sequential' (MATLAB's frame loop, the default) or 'grow'
(batched growth from seed frames, see
:mod:`giant_python.registration.growth`).
frames_per_front : int
- ``grow``: frames taken from each island edge per sub-round.
+ grow: frames taken from each island edge per sub-round.
min_fronts : int
- ``grow``: add seeds when fewer fronts remain.
+ grow: add seeds when fewer fronts remain.
seed_accept_quantile : float
- ``grow``: a seed's peak correlation and margin must reach this
+ grow: a seed's peak correlation and margin must reach this
quantile of the aligned frames'.
junction_jump_px : float or None
- ``grow``: motion jump at a junction that triggers realignment
- (``None``: max(1, 99.9th percentile of per-frame steps)).
+ grow: motion jump at a junction that triggers realignment
+ (None: max(1, 99.9th percentile of per-frame steps)).
polish : bool
- ``grow``: rematch every frame to the final template without itself.
+ grow: rematch every frame to the final template without itself.
polish_radius : int
- ``grow``: search radius of the polish pass.
+ grow: search radius of the polish pass.
var_factor_deflate : int
- Deflate level (0-9) of ``varFacDS`` in the alignment file; 0 stores
- it uncompressed, as MATLAB does. MATLAB's ``h5read`` decompresses
+ Deflate level (0-9) of varFacDS in the alignment file; 0 stores
+ it uncompressed, as MATLAB does. MATLAB's h5read decompresses
transparently.
movie_deflate : int
- Deflate level (0-9) of HDF5 movies (``save_tif=False``, the
+ Deflate level (0-9) of HDF5 movies (save_tif=False, the
default); MATLAB writes 4.
"""
@@ -226,14 +251,22 @@ class MultiRoiRegistrationParams:
frames_per_front: int = 1
min_fronts: int = 16
seed_accept_quantile: float = 0.1
- junction_jump_px: Optional[float] = None
+ junction_jump_px: float | None = None
polish: bool = False
polish_radius: int = 2
var_factor_deflate: int = 1
movie_deflate: int = 1
def __post_init__(self) -> None:
- """Validate values and reject options that are not ported."""
+ """Validate values and reject options that are not ported.
+
+ Raises
+ ------
+ ValueError
+ If a setting is invalid.
+ NotImplementedError
+ If a MATLAB option that is not ported is True.
+ """
_positive("align_hz", self.align_hz)
for name in (
"maxshift",
@@ -265,12 +298,16 @@ def __post_init__(self) -> None:
"include_integration_rois",
):
if getattr(self, name):
- raise NotImplementedError(
- f"{name}=True is not supported yet in GIAnT-Python"
- )
+ raise NotImplementedError(f"{name}=True is not supported yet in GIAnT-Python")
def _validate_growth_and_output(self) -> None:
- """Validate the growth-schedule and output-compression settings."""
+ """Validate the growth-schedule and output-compression settings.
+
+ Raises
+ ------
+ ValueError
+ If a setting is invalid.
+ """
if self.schedule not in ("sequential", "grow"):
raise ValueError("schedule must be 'sequential' or 'grow'")
if not 0 <= self.seed_accept_quantile < 1:
@@ -279,15 +316,17 @@ def _validate_growth_and_output(self) -> None:
_positive("junction_jump_px", self.junction_jump_px)
for name in ("var_factor_deflate", "movie_deflate"):
value = getattr(self, name)
- if (
- isinstance(value, bool)
- or not isinstance(value, Integral)
- or not 0 <= value <= 9
- ):
+ if isinstance(value, bool) or not isinstance(value, Integral) or not 0 <= value <= 9:
raise ValueError(f"{name} must be an integer from 0 to 9")
def to_matlab(self) -> dict:
- """The parameters under GIAnT-MATLAB's ``align_params`` names."""
+ """Return the parameters under GIAnT-MATLAB's align_params names.
+
+ Returns
+ -------
+ dict
+ MATLAB's parameter names and their values (numbers as float).
+ """
return {
"alignHz": float(self.align_hz),
"maxshift": float(self.maxshift),
@@ -307,9 +346,7 @@ def to_matlab(self) -> dict:
"minFronts": float(self.min_fronts),
"seedAcceptQuantile": float(self.seed_accept_quantile),
"junctionJumpPx": (
- float("nan")
- if self.junction_jump_px is None
- else float(self.junction_jump_px)
+ float("nan") if self.junction_jump_px is None else float(self.junction_jump_px)
),
"polish": self.polish,
"polishRadius": float(self.polish_radius),
@@ -329,10 +366,10 @@ class ExecutionOptions:
verbose : bool
Enable stage messages and progress bars.
max_trials : int or None
- Positive debug limit per DMD. ``None`` processes all trials.
+ Positive debug limit per DMD. None processes all trials.
device : str
- Torch device for registration: ``'auto'`` (CUDA when available),
- ``'cpu'``, ``'cuda'`` or ``'cuda:N'``. Band extraction ignores it.
+ Torch device for registration: 'auto' (CUDA when available),
+ 'cpu', 'cuda' or 'cuda:N'. Band extraction ignores it.
gpu_workers : int
Trials registered at once on one CUDA device, each in its own
process (default 1). Each process keeps to an equal share of the
@@ -343,12 +380,18 @@ class ExecutionOptions:
max_workers: int = 6
verbose: bool = False
- max_trials: Optional[int] = None
+ max_trials: int | None = None
device: str = "auto"
gpu_workers: int = 1
def __post_init__(self) -> None:
- """Validate scheduling and debug limits."""
+ """Validate scheduling and debug limits.
+
+ Raises
+ ------
+ ValueError
+ If a setting is invalid.
+ """
_positive("max_workers", self.max_workers, integer=True)
_positive("gpu_workers", self.gpu_workers, integer=True)
if self.max_trials is not None:
@@ -370,42 +413,62 @@ class AnnotationOptions:
enabled : bool
Include user ROIs during extraction.
interactive : bool or None
- Allow or forbid drawing; ``None`` retains backend auto-detection.
+ Allow or forbid drawing; None retains backend auto-detection.
"""
enabled: bool = False
- interactive: Optional[bool] = None
+ interactive: bool | None = None
def __post_init__(self) -> None:
- """Validate the explicit and automatic annotation policies."""
+ """Validate the explicit and automatic annotation policies.
+
+ Raises
+ ------
+ ValueError
+ If a setting is invalid.
+ """
if not isinstance(self.enabled, bool):
raise ValueError("enabled must be a bool")
- if self.interactive is not None and not isinstance(
- self.interactive, bool
- ):
+ if self.interactive is not None and not isinstance(self.interactive, bool):
raise ValueError("interactive must be a bool or None")
-BandParamsInput = Optional[Union[BandSiloParams, dict]]
-ExecutionInput = Optional[Union[ExecutionOptions, dict]]
-AnnotationInput = Optional[Union[AnnotationOptions, dict]]
-RegistrationParamsInput = Optional[Union[MultiRoiRegistrationParams, dict]]
+BandParamsInput = Optional[BandSiloParams | dict]
+ExecutionInput = Optional[ExecutionOptions | dict]
+AnnotationInput = Optional[AnnotationOptions | dict]
+RegistrationParamsInput = Optional[MultiRoiRegistrationParams | dict]
def _option_values(
option: object,
model: type[
- Union[
- BandSiloParams,
- ExecutionOptions,
- AnnotationOptions,
- MultiRoiRegistrationParams,
- SiloParams,
- SiloExecution,
- ]
+ BandSiloParams
+ | ExecutionOptions
+ | AnnotationOptions
+ | MultiRoiRegistrationParams
+ | SiloParams
+ | SiloExecution
],
) -> dict:
- """Copy a typed option or validate a strictly scoped dictionary."""
+ """Copy a typed option or validate a strictly scoped dictionary.
+
+ Parameters
+ ----------
+ option : object
+ An instance of model, a dict of its fields, or None.
+ model : type
+ The options class.
+
+ Returns
+ -------
+ dict
+ The field values of option; empty for None.
+
+ Raises
+ ------
+ TypeError
+ If a dict has unknown fields, or option is neither model, dict nor None.
+ """
if option is None:
return {}
if isinstance(option, model):
@@ -430,7 +493,7 @@ def resolve_band_options(
----------
params : BandSiloParams, dict or None
Scientific settings only. Routing, execution, annotation and unknown
- fields raise ``TypeError`` rather than being dispatched elsewhere.
+ fields raise TypeError rather than being dispatched elsewhere.
execution : ExecutionOptions, dict or None
Run options or a dictionary containing only execution fields.
annotations : AnnotationOptions, dict or None
@@ -458,7 +521,7 @@ def resolve_registration_options(
Parameters
----------
params : MultiRoiRegistrationParams, dict or None
- Scientific settings only; unknown fields raise ``TypeError``.
+ Scientific settings only; unknown fields raise TypeError.
execution : ExecutionOptions, dict or None
Run options.
@@ -468,9 +531,7 @@ def resolve_registration_options(
Fresh validated objects.
"""
return (
- MultiRoiRegistrationParams(
- **_option_values(params, MultiRoiRegistrationParams)
- ),
+ MultiRoiRegistrationParams(**_option_values(params, MultiRoiRegistrationParams)),
ExecutionOptions(**_option_values(execution, ExecutionOptions)),
)
@@ -479,13 +540,25 @@ def resolve_registration_options(
def _odd(name: str, value: int) -> None:
- """Reject an even integer."""
+ """Reject an even integer.
+
+ Raises
+ ------
+ ValueError
+ If value is even.
+ """
if value % 2 == 0:
raise ValueError(f"{name} must be odd, not {value}")
def _choice(name: str, value: object, allowed: tuple) -> None:
- """Reject a value that is not one of ``allowed``."""
+ """Reject a value that is not one of allowed.
+
+ Raises
+ ------
+ ValueError
+ If value is not in allowed.
+ """
if value not in allowed:
raise ValueError(f"{name} must be one of {allowed}, not {value!r}")
@@ -496,40 +569,40 @@ class SiloParams:
One parameter set for every stage of source extraction (localization,
plan, trial loading, subproblem solving, collection). The defaults are
- GIAnT-MATLAB main's ``setParams('SILo')`` for SLAP2 (``isSLAP2``), with
- its modality defaults resolved (``peakth`` 3, ``minKineticScore`` 0.2,
- ``photonScale`` 25); the footprint fit's variance term is the solver's
- default (``footprint_variance='model'`` gives MATLAB's loss), the
- footprints' support is 5 x 5 (``valid_kernel=3`` is MATLAB's), and the
- summaries hold per-trial F0 images (``f0_im_trim_s=None`` leaves them
+ GIAnT-MATLAB main's setParams('SILo') for SLAP2 (isSLAP2), with
+ its modality defaults resolved (peakth 3, minKineticScore 0.2,
+ photonScale 25); the footprint fit's variance term is the solver's
+ default (footprint_variance='model' gives MATLAB's loss), the
+ footprints' support is 5 x 5 (valid_kernel=3 is MATLAB's), and the
+ summaries hold per-trial F0 images (f0_im_trim_s=None leaves them
out, as MATLAB main does). MATLAB's names are given in brackets;
- :meth:`to_matlab` returns the ``params`` struct that SILo saves. The
+ :meth:`to_matlab` returns the params struct that SILo saves. The
stages' own parameter types are derived with :meth:`plan_params`,
:meth:`load_params`, :meth:`solver_params` and
:meth:`localization_params`.
- ``baseline_source`` chooses the baseline of the whole run, and with it
+ baseline_source chooses the baseline of the whole run, and with it
the defaults of the settings that go with it (each can still be set):
============================ =============== =====================
- setting ``'median'`` ``'network'``
+ setting 'median' 'network'
============================ =============== =====================
- ``localization_baseline`` ``'median'`` ``'network'``
- ``localization_surround`` True False
- ``localization_null`` ``'none'`` ``'bootstrap'``
- ``peak_th`` 3 3
- ``min_source_event_rate`` 0 2
- ``baseline_mode`` ``'fit'`` (R0) ``'gain'`` (N1)
+ localization_baseline 'median' 'network'
+ localization_surround True False
+ localization_null 'none' 'bootstrap'
+ peak_th 3 3
+ min_source_event_rate 0 2
+ baseline_mode 'fit' (R0) 'gain' (N1)
============================ =============== =====================
- ``'median'`` is MATLAB's SILo. ``'network'`` uses the F0 network's
- baselines (``slap2-f0 predict-registered``): localization with the
+ 'median' is MATLAB's SILo. 'network' uses the F0 network's
+ baselines (slap2-f0 predict-registered): localization with the
settings recommended in slap2-F0-network#6 (no surround, the bootstrap
- null, the variance floor kept), seeding at ``peak_th`` 3 with the
- evidence test ``min_source_event_rate`` 2 events per minute for the
- sources seeded below ``peak_th`` + ``evidence_margin`` (2)
- (GIAnT-Python#51: more of the dim sources; until 2026-11-28 ``peak_th``
- was 8 with no evidence test, ``peak_th=8, min_source_event_rate=0``),
+ null, the variance floor kept), seeding at peak_th 3 with the
+ evidence test min_source_event_rate 2 events per minute for the
+ sources seeded below peak_th + evidence_margin (2)
+ (GIAnT-Python#51: more of the dim sources; until 2026-11-28 peak_th
+ was 8 with no evidence test, peak_th=8, min_source_event_rate=0),
and
extraction with the network's baseline times one gain per pixel (N1),
the variant that the baseline test of the SILo port (WP6) found within
@@ -543,114 +616,114 @@ class SiloParams:
files are given at run time. Sets the defaults above. Not a MATLAB
option.
activity_channel : int
- One-based channel of the activity signal (``activityChannel``).
+ One-based channel of the activity signal (activityChannel).
analyze_hz : float
- Frame rate of extraction (``analyzeHz``).
+ Frame rate of extraction (analyzeHz).
sigma_px : float
- Gaussian sigma of the PSF, pixels (``sigma_px``).
+ Gaussian sigma of the PSF, pixels (sigma_px).
d_xy : float
- How large sources can be, pixels (``dXY``); the selected disk around
- a source has radius ``ceil(2 d_xy)`` (``selRadius``).
+ How large sources can be, pixels (dXY); the selected disk around
+ a source has radius ceil(2 d_xy) (selRadius).
valid_kernel : int
Side of the square around each source where the footprint fit may
- put intensity (odd; default 5; MATLAB's ``validKernel``, which
+ put intensity (odd; default 5; MATLAB's validKernel, which
MATLAB hard-codes as 3 x 3). One setting for the whole run: it
sets the
- plan's grouping zones (radius ``ceil(1.5 sigma_px +
- (valid_kernel - 1) / 2)``, :class:`PlanParams`) and the solver's
- footprints (``SolverParams.valid_kernel``) together. The footprint
- is ``hfilter`` blurring that support, so its width lies between
- 0.9 ``sigma_px`` and ``sqrt((0.9 sigma_px)**2 + r**2)``,
- r = (valid_kernel - 1) / 2: 1.20 to 1.56 px with 3 at ``sigma_px``
+ plan's grouping zones (radius ceil(1.5 sigma_px +
+ (valid_kernel - 1) / 2), :class:`PlanParams`) and the solver's
+ footprints (SolverParams.valid_kernel) together. The footprint
+ is hfilter blurring that support, so its width lies between
+ 0.9 sigma_px and sqrt((0.9 sigma_px)**2 + r**2),
+ r = (valid_kernel - 1) / 2: 1.20 to 1.56 px with 3 at sigma_px
1.33, up to 2.33 px with 5. 3 is the setting to compare with
MATLAB.
tau_s, tau2_s : float
Decay time constants of the activity channel and of channel 2
- (``tau_s``, ``tau2_s``).
+ (tau_s, tau2_s).
baseline_window_s : float
- Timescale of the baseline (``baselineWindow_Glu_s``).
+ Timescale of the baseline (baselineWindow_Glu_s).
baseline_window_ca_s : float
- ``baselineWindow_Ca_s``; recorded only, as in MATLAB's SILo.
+ baselineWindow_Ca_s; recorded only, as in MATLAB's SILo.
denoise_window_s : float
- Timescale over which signals may be smoothed (``denoiseWindow_s``).
+ Timescale over which signals may be smoothed (denoiseWindow_s).
vif : float
- Variance inflation factor of localization (``VIF``).
+ Variance inflation factor of localization (VIF).
motion_thresh : float
Registered frames whose motion error exceeds this are discarded
- (``motionThresh``).
+ (motionThresh).
discard_initial_s : float
- Seconds discarded at the start of each trial (``discardInitial_s``).
+ Seconds discarded at the start of each trial (discardInitial_s).
nan_thresh : float
Largest share of missing samples of an included pixel
- (``nanThresh``).
+ (nanThresh).
peak_th : float or None
- Seed threshold, robust SDs of the activity image (``peakth``; 3 for
+ Seed threshold, robust SDs of the activity image (peakth; 3 for
SLAP2). Used by the plan's seeding and, unless
- ``localization_peak_th`` is set, by the per-trial peaks. None takes
- the default of ``baseline_source`` (3 with both; it was 8 with the
+ localization_peak_th is set, by the per-trial peaks. None takes
+ the default of baseline_source (3 with both; it was 8 with the
network until 2026-11-28).
min_peak_distance : int
- Minimum Chebyshev distance of seeds (``minPeakDistance``).
+ Minimum Chebyshev distance of seeds (minPeakDistance).
localization_baseline : {'median', 'network'} or None
Baseline of localization: MATLAB's moving median, or the F0
- network's ``*_BASELINE-80Hz.h5`` files (``slap2-f0
- predict-registered``), whose folder is given at run time. Not a
- MATLAB option. None takes ``baseline_source``.
+ network's ``*_BASELINE-80Hz.h5`` files (slap2-f0
+ predict-registered), whose folder is given at run time. Not a
+ MATLAB option. None takes baseline_source.
localization_surround : bool or None
Subtract the surround in the localization score (MATLAB's). None
- takes the default of ``baseline_source`` (True, or False with the
+ takes the default of baseline_source (True, or False with the
network).
localization_null : {'none', 'bootstrap'} or None
Null calibration of the localization score. None takes the default
- of ``baseline_source`` ('none', or 'bootstrap' with the network).
+ of baseline_source ('none', or 'bootstrap' with the network).
localization_null_draws, localization_null_seed : int
Noise movies per trial of the bootstrap null, and the first seed.
localization_null_scale : {'tail', 'sd'}
Calibration of the bootstrap null.
localization_variance_floor : bool
- Add the variance floor ``Vb`` to the score's variance (MATLAB's).
+ Add the variance floor Vb to the score's variance (MATLAB's).
localization_score : {'squared_maxima', 'soft_threshold'}
- Localization score (MATLAB's: ``'squared_maxima'``).
+ Localization score (MATLAB's: 'squared_maxima').
localization_soft_th : float
Threshold of the soft-threshold score, robust SDs.
localization_peak_th : float or None
- Threshold of the per-trial peaks; None uses ``peak_th``.
+ Threshold of the per-trial peaks; None uses peak_th.
localization_sd : bool
- Use ``/sd`` from ``*_BASELINE-80Hz.h5`` (scaled by
- ``sqrt(varFacDS_t / mean_t(varFacDS))``) in localization when
- present (default True; False keeps the fitted ``Vk`` slope).
+ Use /sd from ``*_BASELINE-80Hz.h5`` (scaled by
+ sqrt(varFacDS_t / mean_t(varFacDS))) in localization when
+ present (default True; False keeps the fitted Vk slope).
localization_keep_null : bool or None
Keep each trial's calibrated null images (the bootstrap null's
activity images) in its localization file, for the null seed
thresholds. Each trial-path's null movies are then drawn with its
- own seed (``localization_null_seed`` plus a trial-path offset,
+ own seed (localization_null_seed plus a trial-path offset,
:func:`~giant_python.pipeline.silo.trial_null_seed`), so that the
trials' nulls are independent; the calibration differs from a run
without kept nulls only by that random draw. None: kept exactly when
- ``seed_acceptance`` is not 'image'. Not a MATLAB option.
+ seed_acceptance is not 'image'. Not a MATLAB option.
trial_peaks : bool
Fit each trial's peaks (Gaussians at the per-trial activity image's
maxima). They feed only the per-trial summary's
- ``per_trial_act_im_peaks`` and ``per_trial_num_peaks``; False
+ per_trial_act_im_peaks and per_trial_num_peaks; False
leaves those out of the file.
inter_trial_alignment : {'rigid', 'affine', 'patchwise'}
- Across-trial alignment (``interTrialAlignment``): a shift per
+ Across-trial alignment (interTrialAlignment): a shift per
trial, refined for the valid trials to an affine map or to a
patchwise displacement field (see
:mod:`~giant_python.extraction.raster.alignment`). With
- ``'patchwise'`` (the default; MATLAB's default is ``'rigid'``) the
+ 'patchwise' (the default; MATLAB's default is 'rigid') the
localize stage also stores each trial's half images.
align_patch_px : int
- Imaged pixels per patch of the patchwise field (``alignPatchPx``).
+ Imaged pixels per patch of the patchwise field (alignPatchPx).
peak_method : {'getactimpeaks', 'wmf'}
Seed the combined activity image with Gaussian fits or the aligned
- trials with a whitened matched filter (``peakMethod``). WMF falls
+ trials with a whitened matched filter (peakMethod). WMF falls
back to Gaussian seeding with fewer than four imaged valid trials.
seed_fit : {'local', 'matlab'}, optional
Gaussian fits of the seeding and of the per-trial peaks: local fits
- run to convergence (``'local'``, the default: seconds per path
+ run to convergence ('local', the default: seconds per path
instead of minutes, sources nearer MATLAB's own), or MATLAB's
- capped joint fits (``'matlab'``). See
+ capped joint fits ('matlab'). See
:func:`~giant_python.extraction.raster.peaks.get_act_im_peaks`.
None takes the plan stage's default
(:class:`~giant_python.extraction.raster.plan.PlanParams`).
@@ -660,15 +733,15 @@ class SiloParams:
from being seeded two or three times; 0 is MATLAB's rule only).
None takes the plan stage's default.
seed_acceptance : {'image', 'null', 'null_sd'}
- How the Gaussian seed threshold is set: ``peak_th`` robust SDs of the
+ How the Gaussian seed threshold is set: peak_th robust SDs of the
combined activity image ('image', MATLAB's); from the null of the
- combined image so that ``seed_false_per_field`` false seeds are
- expected per path ('null'; ``peak_th`` then sets only the per-trial
- peaks); or ``peak_th`` robust SDs of that null ('null_sd'). Both
- null modes need ``localization_null='bootstrap'``. Not a MATLAB
+ combined image so that seed_false_per_field false seeds are
+ expected per path ('null'; peak_th then sets only the per-trial
+ peaks); or peak_th robust SDs of that null ('null_sd'). Both
+ null modes need localization_null='bootstrap'. Not a MATLAB
option.
seed_false_per_field : float
- Expected false seeds per path with ``seed_acceptance='null'``.
+ Expected false seeds per path with seed_acceptance='null'.
seed_amplitude_rule : {'matlab', 'pixel'}
The plan's final test of each fitted seed (see
:func:`~giant_python.extraction.raster.peaks.get_act_im_peaks`):
@@ -676,113 +749,113 @@ class SiloParams:
value on its own pixel ('pixel', not in MATLAB).
wmf_peak_th, wmf_dip, wmf_deblend_th : float
Minimum WMF peak, intervening dip and deblending residual peak in
- robust SDs (``wmfPeakth``, ``wmfDip``, ``wmfDeblendth``). Set
- ``wmf_deblend_th`` to positive infinity to skip the fit.
+ robust SDs (wmfPeakth, wmfDip, wmfDeblendth). Set
+ wmf_deblend_th to positive infinity to skip the fit.
photon_scale : float
- Raw counts per unit of the data (``photonScale``; 25 for SLAP2).
+ Raw counts per unit of the data (photonScale; 25 for SLAP2).
lam : float
- L1 penalty of the activity fit (``lambda``).
+ L1 penalty of the activity fit (lambda).
phi : float
- Share of ``lam`` kept in the debias refit (``phi``).
+ Share of lam kept in the debias refit (phi).
nmf_iter : int
- Outer iterations of the solver (``nmfIter``).
+ Outer iterations of the solver (nmfIter).
min_baseline : float
- Lower bound of the baseline, normalized units (``minBaseline``).
+ Lower bound of the baseline, normalized units (minBaseline).
baseline_mode : {'fit', 'fixed', 'gain', 'gain_shared', 'fit_from'} or None
How the solver finds the activity channel's baseline
- (``SolverParams.baseline_mode``): 'fit' is MATLAB's own fit (R0);
+ (SolverParams.baseline_mode): 'fit' is MATLAB's own fit (R0);
the others start from the network's baseline (N0-N3 of the baseline
- test). None takes the default of ``baseline_source`` ('fit', or
+ test). None takes the default of baseline_source ('fit', or
'gain' with the network). Not a MATLAB option.
debias_variance : {'fixed', 'model'}
- Variance term of the debias refit (``debiasVariance``).
+ Variance term of the debias refit (debiasVariance).
footprint_variance : {'fixed', 'model'} or None
Variance term of the footprint fit: held at the fit's start
('fixed') or following the model as in MATLAB ('model'). Not a
MATLAB option. None (the default) takes the solver's default,
- ``SolverParams.footprint_variance`` ('fixed' since
+ SolverParams.footprint_variance ('fixed' since
GIAnT-Python#23); the resolved value is what the object holds.
baseline_knot_factor, baseline_penalty : float
The solver's baseline spline (MATLAB's fixed values).
min_kinetic_score : float
Sources whose transients score below this in the kinetics test are
- removed after extraction (``minKineticScore``; 0 keeps all).
+ removed after extraction (minKineticScore; 0 keeps all).
min_source_snr : float
The evidence test (not in MATLAB; 0, the default, turns it off):
sources whose SNR (the solver's, averaged over the extracted
trials) is below this are removed after extraction with those the
kinetics test rejects. Meant for permissive seeding (a lower
- ``peak_th`` or a larger ``seed_false_per_field``).
+ peak_th or a larger seed_false_per_field).
min_source_event_rate : float or None
The evidence test's other criterion (0: off; not in MATLAB):
sources whose trace has fewer kinetics-test events per minute than
this (events over the minutes of the trace's frames that were not
discarded) are removed. A rate, so that it means the same in short
- and long recordings. None takes the default of ``baseline_source``
+ and long recordings. None takes the default of baseline_source
(0, or 2 with the network, where it goes with the seed threshold).
evidence_margin : float or None
- The evidence test judges only the sources seeded below ``peak_th``
- + ``evidence_margin`` robust SDs (their seed height,
+ The evidence test judges only the sources seeded below peak_th
+ + evidence_margin robust SDs (their seed height,
:func:`~giant_python.extraction.raster.seeding.seed_heights`):
stronger seeds are kept whatever their evidence. Default 2; None
judges every source, as do WMF and the null seed thresholds
- (``seed_acceptance`` 'null' or 'null_sd'). Matters only
+ (seed_acceptance 'null' or 'null_sd'). Matters only
when the evidence test is on. Not a MATLAB option.
spot_link_px, spot_split_corr, spot_event_test, spot_min_snr,
spot_min_events, spot_min_power, spot_compact_px
The spot annotation that collect adds to the summary
(:mod:`~giant_python.pipeline.silo_spots`,
:mod:`~giant_python.extraction.raster.spots`): kept sources within
- ``spot_link_px`` form a spot. With ``spot_event_test`` single
- events of each multi-source spot (peaks ``spot_min_snr`` robust
+ spot_link_px form a spot. With spot_event_test single
+ events of each multi-source spot (peaks spot_min_snr robust
SDs high) are localized in the registered movie; with at least
- ``spot_min_events`` (at least 5) of them their positions decide
+ spot_min_events (at least 5) of them their positions decide
between
separate clusters ('close_pair') and one cloud. A spot is 'merge'
(one source cut in two) when its sources' event trains correlate at
- ``spot_split_corr`` or more or its one cloud is no wider than
- ``spot_compact_px``; 'continuum' when one cloud was found although
- the test had ``spot_min_power`` to see the sources as separate
+ spot_split_corr or more or its one cloud is no wider than
+ spot_compact_px; 'continuum' when one cloud was found although
+ the test had spot_min_power to see the sources as separate
points; 'undecided' otherwise. The annotation does not change the
sources or their traces. Not MATLAB options.
min_frames : int
Trials with fewer frames are loaded but not source-extracted
- (MATLAB's ``minFrames``).
+ (MATLAB's minFrames).
f0_im_trim_s : float or None
Per-trial F0 images: each selected pixel's final baseline averaged
over the trial's kept frames, leaving out this many seconds at
each end, where the baseline fit is biased (a trial too short for
the trim is averaged whole). The summaries then hold
- ``visualizations/per_trial_F0_im`` and ``F0_im`` and the user
- ROIs' ``per_trial_F0`` (GIAnT-MATLAB's spine-size branch,
- ``F0imTrim_s``), the resting brightness that spine sizes are read
+ visualizations/per_trial_F0_im and F0_im and the user
+ ROIs' per_trial_F0 (GIAnT-MATLAB's spine-size branch,
+ F0imTrim_s), the resting brightness that spine sizes are read
from. None: no F0 images (GIAnT-MATLAB main). Default 1.
user_rois : bool
- Read the session's ``annotations/annotations.h5`` (soma masks and
- user ROIs; ``drawUserRois``). ROIs are never drawn here: without a
+ Read the session's annotations/annotations.h5 (soma masks and
+ user ROIs; drawUserRois). ROIs are never drawn here: without a
file the session has no user ROIs, as MATLAB's SILo without the
GUI.
variance_mode : {'freshness', 'kernel'}
- Per-sample variance multiplier ``finv`` in 200 Hz extraction:
- pooling-conserved exponential-kernel variance ``F2 / D^2``
- (``'kernel'``, the default) or MATLAB's ``1 / D`` (``'freshness'``).
+ Per-sample variance multiplier finv in 200 Hz extraction:
+ pooling-conserved exponential-kernel variance F2 / D^2
+ ('kernel', the default) or MATLAB's 1 / D ('freshness').
snr_mode : {'diagonal', 'projected'}
- Trace noise SD in ``activity_noise``: WLS-projected residuals
+ Trace noise SD in activity_noise: WLS-projected residuals
capturing spatial bilinear and short-lag temporal correlations
- (``'projected'``, the default) or MATLAB's diagonal normal matrix
- (``'diagonal'``).
+ ('projected', the default) or MATLAB's diagonal normal matrix
+ ('diagonal').
warp_interp : {'linear', 'cubic', 'cubic_clamped'}
Spatial interpolation when warping trial images into the consensus
frame and mapping 80 Hz network baselines: monotonicity-clamped
- Keys' bicubic (``'cubic_clamped'``, the default), unclamped
- ``'cubic'``, or MATLAB's ``'linear'``.
+ Keys' bicubic ('cubic_clamped', the default), unclamped
+ 'cubic', or MATLAB's 'linear'.
solver_sd : bool
- Scale ``finv`` by pooling-deattenuated network ``/sd`` when
- extracting with a network baseline that has ``/sd``. Default
- False: the solver's event penalty ``lam`` is tuned to its own
- variance model in units of ``photon_scale``, and with the
+ Scale finv by pooling-deattenuated network /sd when
+ extracting with a network baseline that has /sd. Default
+ False: the solver's event penalty lam is tuned to its own
+ variance model in units of photon_scale, and with the
network's larger variance on bright pixels it drops real events
- there (see ``docs/source/variance_and_interpolation.rst``).
+ there (see docs/source/variance_and_interpolation.rst).
"""
activity_channel: int = 1
@@ -799,27 +872,27 @@ class SiloParams:
motion_thresh: float = 2.0
discard_initial_s: float = 0.0
nan_thresh: float = 0.33
- peak_th: Optional[float] = None
+ peak_th: float | None = None
min_peak_distance: int = 1
baseline_source: str = "median"
- localization_baseline: Optional[str] = None
- localization_surround: Optional[bool] = None
- localization_null: Optional[str] = None
+ localization_baseline: str | None = None
+ localization_surround: bool | None = None
+ localization_null: str | None = None
localization_null_draws: int = 1
localization_null_seed: int = 0
localization_null_scale: str = "tail"
localization_variance_floor: bool = True
localization_score: str = "squared_maxima"
localization_soft_th: float = 2.0
- localization_peak_th: Optional[float] = None
+ localization_peak_th: float | None = None
localization_sd: bool = True
- localization_keep_null: Optional[bool] = None
+ localization_keep_null: bool | None = None
trial_peaks: bool = True
inter_trial_alignment: str = "patchwise"
align_patch_px: int = 1500
peak_method: str = "getactimpeaks"
- seed_fit: Optional[str] = None
- seed_merge_px: Optional[float] = None
+ seed_fit: str | None = None
+ seed_merge_px: float | None = None
seed_acceptance: str = "image"
seed_false_per_field: float = 1.0
seed_amplitude_rule: str = "matlab"
@@ -831,15 +904,15 @@ class SiloParams:
phi: float = 0.0
nmf_iter: int = 2
min_baseline: float = 0.01
- baseline_mode: Optional[str] = None
+ baseline_mode: str | None = None
debias_variance: str = "fixed"
- footprint_variance: Optional[str] = None
+ footprint_variance: str | None = None
baseline_knot_factor: float = 0.5
baseline_penalty: float = 30.0
min_kinetic_score: float = 0.2
min_source_snr: float = 0.0
- min_source_event_rate: Optional[float] = None
- evidence_margin: Optional[float] = 2.0
+ min_source_event_rate: float | None = None
+ evidence_margin: float | None = 2.0
spot_link_px: float = 2.5
spot_split_corr: float = 0.3
spot_event_test: bool = True
@@ -848,7 +921,7 @@ class SiloParams:
spot_min_power: float = 0.8
spot_compact_px: float = 0.45
min_frames: int = 100
- f0_im_trim_s: Optional[float] = 1.0
+ f0_im_trim_s: float | None = 1.0
user_rois: bool = True
variance_mode: str = "kernel"
snr_mode: str = "projected"
@@ -856,7 +929,13 @@ class SiloParams:
solver_sd: bool = False
def __post_init__(self) -> None:
- """Validate values; reject modes that are not ported."""
+ """Validate values; reject modes that are not ported.
+
+ Raises
+ ------
+ ValueError
+ If a setting is invalid.
+ """
self._baseline_defaults()
for name in (
"analyze_hz",
@@ -947,29 +1026,27 @@ def __post_init__(self) -> None:
self.solver_params()
def _check_spots(self) -> None:
- """Checks of the spot annotation's settings."""
+ """Check the spot annotation's settings.
+
+ Raises
+ ------
+ ValueError
+ If a spot setting is invalid.
+ """
for name in ("spot_link_px", "spot_min_snr", "spot_compact_px"):
_positive(name, getattr(self, name))
_positive("spot_min_events", self.spot_min_events, integer=True)
if self.spot_min_events < 5:
- raise ValueError(
- "spot_min_events must be at least 5 (a cloud's fit)"
- )
+ raise ValueError("spot_min_events must be at least 5 (a cloud's fit)")
for name in ("spot_split_corr", "spot_min_power"):
v = getattr(self, name)
- if (
- isinstance(v, bool)
- or not isinstance(v, Real)
- or not 0 <= v <= 1
- ):
+ if isinstance(v, bool) or not isinstance(v, Real) or not 0 <= v <= 1:
raise ValueError(f"{name} must lie in [0, 1]")
def _baseline_defaults(self) -> None:
- """Fill the settings left at None from ``baseline_source``."""
+ """Fill the settings left at None from baseline_source."""
_choice("baseline_source", self.baseline_source, ("median", "network"))
- for name, value in BASELINE_SOURCE_DEFAULTS[
- self.baseline_source
- ].items():
+ for name, value in BASELINE_SOURCE_DEFAULTS[self.baseline_source].items():
if getattr(self, name) is None:
object.__setattr__(self, name, value)
@@ -979,7 +1056,13 @@ def _check_f0_images(self) -> None:
_nonnegative("f0_im_trim_s", self.f0_im_trim_s)
def _seed_defaults(self) -> None:
- """Take the seed fit's defaults from the plan stage (one default)."""
+ """Take the seed fit's defaults from the plan stage (one default).
+
+ Raises
+ ------
+ ValueError
+ If a seeding setting is invalid or inconsistent with the localization null.
+ """
from ..extraction.raster.plan import PlanParams
from ..extraction.raster.seeding import SEEDING_METHODS
@@ -1009,17 +1092,14 @@ def _seed_defaults(self) -> None:
if not isinstance(self.localization_keep_null, bool):
raise ValueError("localization_keep_null must be a bool")
null_seeding = self.seed_acceptance != "image"
- if (
- self.localization_keep_null or null_seeding
- ) and self.localization_null != "bootstrap":
+ if (self.localization_keep_null or null_seeding) and self.localization_null != "bootstrap":
raise ValueError(
"seed_acceptance 'null' or 'null_sd' and "
"localization_keep_null need localization_null='bootstrap'"
)
if null_seeding and not self.localization_keep_null:
raise ValueError(
- f"seed_acceptance={self.seed_acceptance!r} needs "
- "localization_keep_null"
+ f"seed_acceptance={self.seed_acceptance!r} needs localization_keep_null"
)
def _solver_defaults(self) -> None:
@@ -1027,15 +1107,17 @@ def _solver_defaults(self) -> None:
if self.footprint_variance is None:
from ..extraction.raster.solver_setup import SolverParams
- object.__setattr__(
- self, "footprint_variance", SolverParams.footprint_variance
- )
- _choice(
- "footprint_variance", self.footprint_variance, ("model", "fixed")
- )
+ object.__setattr__(self, "footprint_variance", SolverParams.footprint_variance)
+ _choice("footprint_variance", self.footprint_variance, ("model", "fixed"))
def _check_localization(self) -> None:
- """Checks of the localization options that their type cannot do."""
+ """Check the localization options that their type cannot do.
+
+ Raises
+ ------
+ ValueError
+ If a localization option is invalid.
+ """
_choice(
"localization_baseline",
self.localization_baseline,
@@ -1043,36 +1125,30 @@ def _check_localization(self) -> None:
)
if not isinstance(self.localization_sd, bool):
raise ValueError("localization_sd must be a bool")
- if (
- not self.localization_variance_floor
- and self.localization_baseline != "network"
- ):
+ if not self.localization_variance_floor and self.localization_baseline != "network":
# localization needs an external baseline without the floor
raise ValueError(
- "localization_variance_floor=False needs "
- "localization_baseline='network'"
+ "localization_variance_floor=False needs localization_baseline='network'"
)
seed = self.localization_null_seed
- if (
- isinstance(seed, bool)
- or not isinstance(seed, Integral)
- or seed < 0
- ):
- raise ValueError(
- "localization_null_seed must be a nonnegative integer"
- )
+ if isinstance(seed, bool) or not isinstance(seed, Integral) or seed < 0:
+ raise ValueError("localization_null_seed must be a nonnegative integer")
@property
def evidence_test(self) -> bool:
- """Whether the evidence test runs (``min_source_snr`` or
- ``min_source_event_rate`` above 0)."""
+ """Whether the evidence test runs.
+
+ True when min_source_snr or min_source_event_rate is above 0.
+ """
return self.min_source_snr > 0 or self.min_source_event_rate > 0
@property
- def evidence_judge_below(self) -> Optional[float]:
- """Seed height below which the evidence test judges a source
- (``peak_th + evidence_margin``); None judges every source: without
- a margin, with WMF, or with the null seed thresholds."""
+ def evidence_judge_below(self) -> float | None:
+ """Seed height below which the evidence test judges a source.
+
+ The height is peak_th + evidence_margin; None judges every source: without
+ a margin, with WMF, or with the null seed thresholds.
+ """
if (
self.evidence_margin is None
or self.peak_method == "wmf"
@@ -1083,12 +1159,17 @@ def evidence_judge_below(self) -> Optional[float]:
@property
def sel_radius(self) -> int:
- """Radius of a source's selected pixels (``selRadius``)."""
+ """Radius of a source's selected pixels (selRadius)."""
return math.ceil(2 * self.d_xy)
- def plan_params(self):
- """The plan stage's parameters
- (:class:`~giant_python.extraction.raster.plan.PlanParams`)."""
+ def plan_params(self) -> PlanParams:
+ """Return the plan stage's parameters.
+
+ Returns
+ -------
+ PlanParams
+ The parameters (:class:`~giant_python.extraction.raster.plan.PlanParams`).
+ """
from ..extraction.raster.plan import PlanParams
return PlanParams(
@@ -1112,9 +1193,14 @@ def plan_params(self):
warp_interp=self.warp_interp,
)
- def load_params(self):
- """The trial loader's parameters
- (:class:`~giant_python.extraction.raster.trial_data.TrialLoadParams`).
+ def load_params(self) -> TrialLoadParams:
+ """Return the trial loader's parameters.
+
+ Returns
+ -------
+ TrialLoadParams
+ The parameters
+ (:class:`~giant_python.extraction.raster.trial_data.TrialLoadParams`).
"""
from ..extraction.raster.trial_data import TrialLoadParams
@@ -1127,9 +1213,14 @@ def load_params(self):
variance_mode=self.variance_mode,
)
- def solver_params(self):
- """The subproblem solver's parameters
- (:class:`~giant_python.extraction.raster.solver_setup.SolverParams`).
+ def solver_params(self) -> SolverParams:
+ """Return the subproblem solver's parameters.
+
+ Returns
+ -------
+ SolverParams
+ The parameters
+ (:class:`~giant_python.extraction.raster.solver_setup.SolverParams`).
"""
from ..extraction.raster.solver_setup import SolverParams
@@ -1157,21 +1248,25 @@ def solver_params(self):
@property
def needs_network_baseline(self) -> bool:
- """Whether a stage of the run reads the network's baselines
- (localization, or the solver's baseline mode)."""
- return (
- self.localization_baseline == "network"
- or self.baseline_mode != "fit"
- )
+ """Whether a stage of the run reads the network's baselines.
- def localization_params(self, align_hz: float):
- """The per-trial localization's parameters (a
- :class:`~giant_python.extraction.raster.localization.RasterLocalizationParams`).
+ That is localization, or the solver's baseline mode.
+ """
+ return self.localization_baseline == "network" or self.baseline_mode != "fit"
+
+ def localization_params(self, align_hz: float) -> RasterLocalizationParams:
+ """Return the per-trial localization's parameters.
Parameters
----------
align_hz : float
Frame rate of the registered movies (from the alignment files).
+
+ Returns
+ -------
+ RasterLocalizationParams
+ The parameters
+ (a :class:`~giant_python.extraction.raster.localization.RasterLocalizationParams`).
"""
from ..extraction.raster.localization import RasterLocalizationParams
@@ -1198,7 +1293,7 @@ def localization_params(self, align_hz: float):
)
def stage_settings(self, stage: str) -> dict:
- """The settings one stage's outputs depend on.
+ """Return the settings one stage's outputs depend on.
Each stage records a hash of these (with its inputs' identities),
so that a rerun keeps outputs made with the same settings.
@@ -1253,34 +1348,34 @@ def to_matlab(
end_time: str = "",
save_subproblems_dir: str = "",
) -> dict:
- """The ``params`` struct that GIAnT-MATLAB's SILo saves.
+ """Return the params struct that GIAnT-MATLAB's SILo saves.
- Names, values and classes as in ``experiment_summary.h5``'s
- ``/params`` (and the trial table's
- ``source_extraction/analysis_params``), including the fields that
- SILo and ``setParamsExtractTrial`` derive (filters, kernels,
+ Names, values and classes as in experiment_summary.h5's
+ /params (and the trial table's
+ source_extraction/analysis_params), including the fields that
+ SILo and setParamsExtractTrial derive (filters, kernels,
windows in frames). Numbers are doubles, logicals ``np.bool_``
- (saved as int8), strings ``str``; arrays are in MATLAB's
+ (saved as int8), strings str; arrays are in MATLAB's
orientation. A setting without a MATLAB name is added (in
camelCase) when it differs from MATLAB's algorithm, so that a run
with MATLAB's algorithm has MATLAB's fields exactly. With the
- defaults that is ``footprintVariance`` alone while the solver's
- default is ``'fixed'``. ``validKernel`` is MATLAB's own field and
+ defaults that is footprintVariance alone while the solver's
+ default is 'fixed'. validKernel is MATLAB's own field and
has the run's size (5 x 5 by default; MATLAB's is 3 x 3).
Parameters
----------
num_channels : int
- Channels of the recording (``numChannels``).
+ Channels of the recording (numChannels).
align_hz : float
- Frame rate of the registered movies (``alignHz``).
+ Frame rate of the registered movies (alignHz).
n_workers : int
- ``nWorkers`` (recorded).
+ nWorkers (recorded).
start_time, end_time : str
- ``startTime`` and ``endTime`` (ISO 8601 with milliseconds and
+ startTime and endTime (ISO 8601 with milliseconds and
the UTC offset, as MATLAB writes them).
save_subproblems_dir : str
- ``saveSubproblemsDir``.
+ saveSubproblemsDir.
Returns
-------
@@ -1330,18 +1425,14 @@ def to_matlab(
"tau_full": float(sp.tau_frames),
"tau2_samps": float(sp.tau2_frames),
"baselineWindow_samps": float(sp.baseline_window),
- "denoiseWindow_samps": float(
- self.denoise_window_s * self.analyze_hz
- ),
+ "denoiseWindow_samps": float(self.denoise_window_s * self.analyze_hz),
"k": np.asarray(sp.k, dtype=np.float64),
"k2": np.asarray(sp.k2, dtype=np.float64),
"Hfilter": np.asarray(sp.hfilter, dtype=np.float64),
# MATLAB's Bfilter is size x size x 3
"Bfilter": np.ascontiguousarray(sp.bfilter.transpose(1, 2, 0)),
# MATLAB's name; MATLAB itself always has 3 x 3
- "validKernel": np.ones(
- (self.valid_kernel, self.valid_kernel), dtype=np.bool_
- ),
+ "validKernel": np.ones((self.valid_kernel, self.valid_kernel), dtype=np.bool_),
}
if self.evidence_test:
margin = self.evidence_margin
@@ -1538,16 +1629,16 @@ class SiloExecution:
Processes that localize trials at once (each holds one registered
trial in memory: a few GB for a 30-s SLAP2 trial). 1 also keeps
the plan stage in this process, without child processes; with
- more, ``silo.run_silo`` plans each path in a process of its own and
- ``silo.plan`` plans the paths in up to this many processes (one
+ more, silo.run_silo plans each path in a process of its own and
+ silo.plan plans the paths in up to this many processes (one
path: in this one), and each path's patchwise alignment refits
- its trials in up to 8 more (``silo.refine_workers``; for a single
- path planned by ``silo.plan`` only with its
- ``workers_from_here``, which ``giant silo-plan`` sets).
+ its trials in up to 8 more (silo.refine_workers; for a single
+ path planned by silo.plan only with its
+ workers_from_here, which giant silo-plan sets).
solver_workers : int
Processes that solve subproblems at once.
solver_threads : int
- Threads of each solver process (``OMP_NUM_THREADS`` and torch's);
+ Threads of each solver process (OMP_NUM_THREADS and torch's);
with several processes, 4 to 8 each.
device : str
Torch device of the solver ('cpu', 'cuda', 'cuda:N').
@@ -1566,15 +1657,15 @@ class SiloExecution:
load_workers : int
Trials the streamed run loads at once (threads of this process;
default 4): 1 loads each trial while the previous one is solved, as
- MATLAB's ``processAllTrials_Async``; more load later trials ahead,
+ MATLAB's processAllTrials_Async; more load later trials ahead,
so that loading no longer sets the pace while the solver keeps up
(on 32 cores 4 shortened extraction 1.8-2.3x; 8 gained nothing
more, GIAnT-Python#52). Each
loaded trial waiting for the solver holds its data (about
- ``(channels + 1) * pixels * frames * 4`` bytes, twice while its
+ (channels + 1) * pixels * frames * 4 bytes, twice while its
subproblems are cut out). The prepare stage loads one at a time.
load_memory_gb : float or None
- With ``load_workers`` above 1: load ahead only while the trials
+ With load_workers above 1: load ahead only while the trials
loaded and not yet handed to the solver are estimated below this
many GB (from the bytes per line of the extracted trials loaded so
far; until one has been, and always when none waits, one trial
@@ -1588,15 +1679,15 @@ class SiloExecution:
with the selected pixels).
trial_workers : int
Processes that solve trials at once, each solving one trial's
- subproblems one after another with ``solver_threads`` threads. 0
+ subproblems one after another with solver_threads threads. 0
(the default): one trial at a time, its subproblems spread over
- ``solver_workers`` processes. Each process holds one trial's
+ solver_workers processes. Each process holds one trial's
container.
- ``giant silo`` runs the stages on this machine instead of streaming
- when ``prepare_workers`` or ``trial_workers`` is above 0 (the one left
+ giant silo runs the stages on this machine instead of streaming
+ when prepare_workers or trial_workers is above 0 (the one left
at 0 takes the other's value): trials are prepared ahead in
- ``prepare_workers`` processes and solved in ``trial_workers``
+ prepare_workers processes and solved in trial_workers
processes as their containers arrive
(:func:`~giant_python.pipeline.silo.stream_local`).
@@ -1609,17 +1700,23 @@ class SiloExecution:
solver_threads: int = 4
device: str = "cpu"
dtype: str = "float64"
- batch_bytes: Optional[float] = None
+ batch_bytes: float | None = None
loader_device: str = "cpu"
overwrite: bool = False
verbose: bool = False
load_workers: int = 4
- load_memory_gb: Optional[float] = None
+ load_memory_gb: float | None = None
prepare_workers: int = 0
trial_workers: int = 0
def __post_init__(self) -> None:
- """Validate the options."""
+ """Validate the options.
+
+ Raises
+ ------
+ ValueError
+ If an option is invalid.
+ """
for name in (
"workers",
"solver_workers",
@@ -1629,20 +1726,14 @@ def __post_init__(self) -> None:
_positive(name, getattr(self, name), integer=True)
for name in ("prepare_workers", "trial_workers"):
value = getattr(self, name)
- if (
- isinstance(value, bool)
- or not isinstance(value, Integral)
- or value < 0
- ):
+ if isinstance(value, bool) or not isinstance(value, Integral) or value < 0:
raise ValueError(f"{name} must be a nonnegative integer")
if self.load_memory_gb is not None:
_positive("load_memory_gb", self.load_memory_gb)
for name in ("device", "loader_device"):
value = getattr(self, name)
if not isinstance(value, str) or not _DEVICE.fullmatch(value):
- raise ValueError(
- f"{name} must be 'cpu', 'cuda' or 'cuda:N', not {value!r}"
- )
+ raise ValueError(f"{name} must be 'cpu', 'cuda' or 'cuda:N', not {value!r}")
_choice("dtype", self.dtype, ("float64", "float32"))
if self.batch_bytes is not None:
_positive("batch_bytes", self.batch_bytes)
@@ -1650,34 +1741,40 @@ def __post_init__(self) -> None:
if not isinstance(getattr(self, name), bool):
raise ValueError(f"{name} must be a bool")
- def solver_options(self):
- """The solver's options
- (:class:`~giant_python.extraction.raster.solver.SolverOptions`)."""
+ def solver_options(self) -> SolverOptions:
+ """Return the solver's options.
+
+ Returns
+ -------
+ SolverOptions
+ The options (:class:`~giant_python.extraction.raster.solver.SolverOptions`).
+ """
from ..extraction.raster.solver import SolverOptions
- return SolverOptions(
- device=self.device, dtype=self.dtype, batch_bytes=self.batch_bytes
- )
+ return SolverOptions(device=self.device, dtype=self.dtype, batch_bytes=self.batch_bytes)
@property
def local_stages(self) -> bool:
- """Whether ``giant silo`` prepares and solves whole trials in
- processes of this machine instead of streaming (``prepare_workers``
- or ``trial_workers`` above 0)."""
+ """Whether giant silo prepares and solves whole trials in processes of this machine.
+
+ That is instead of streaming (prepare_workers or trial_workers above 0).
+ """
return self.prepare_workers > 0 or self.trial_workers > 0
@property
def local_workers(self) -> tuple:
- """``(prepare processes, solver processes)`` of the local staged
- run: an option left at 0 takes the other's value."""
+ """The (prepare processes, solver processes) of the local staged run.
+
+ An option left at 0 takes the other's value.
+ """
return (
self.prepare_workers or self.trial_workers,
self.trial_workers or self.prepare_workers,
)
-SiloParamsInput = Optional[Union[SiloParams, dict]]
-SiloExecutionInput = Optional[Union[SiloExecution, dict]]
+SiloParamsInput = Optional[SiloParams | dict]
+SiloExecutionInput = Optional[SiloExecution | dict]
def resolve_silo_options(
@@ -1689,9 +1786,9 @@ def resolve_silo_options(
Parameters
----------
params : SiloParams, dict or None
- Scientific settings; unknown fields raise ``TypeError``.
+ Scientific settings; unknown fields raise TypeError.
execution : SiloExecution, dict or None
- Run options; unknown fields raise ``TypeError``.
+ Run options; unknown fields raise TypeError.
Returns
-------
diff --git a/src/giant_python/models/trial_table.py b/src/giant_python/models/trial_table.py
index ea96baec..d94c9135 100644
--- a/src/giant_python/models/trial_table.py
+++ b/src/giant_python/models/trial_table.py
@@ -1,10 +1,9 @@
-"""Trial table model (``trialTable`` struct / trial_table.h5)."""
+"""Trial table model (trialTable struct / trial_table.h5)."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Optional, Union
import numpy as np
@@ -13,7 +12,7 @@
class Slap2Info:
"""SLAP2-specific trial metadata stored alongside the trial table.
- Corresponds to the ``slap2_info`` sub-struct in GIAnT-MATLAB. Holds the
+ Corresponds to the slap2_info sub-struct in GIAnT-MATLAB. Holds the
reference stack(s), per-trial line ranges, and inferred timing.
Attributes
@@ -28,23 +27,19 @@ class Slap2Info:
"""
ref_stack: dict = field(default_factory=dict)
- first_line: Union[np.ndarray, list] = field(default_factory=list)
- last_line: Union[np.ndarray, list] = field(default_factory=list)
- trial_start_time_inferred: Union[np.ndarray, list] = field(
- default_factory=list
- )
- trial_end_time_from_pc: Union[np.ndarray, list] = field(
- default_factory=list
- )
+ first_line: np.ndarray | list = field(default_factory=list)
+ last_line: np.ndarray | list = field(default_factory=list)
+ trial_start_time_inferred: np.ndarray | list = field(default_factory=list)
+ trial_end_time_from_pc: np.ndarray | list = field(default_factory=list)
@dataclass
class TrialTable:
"""Trial table: the metadata that threads through the whole pipeline.
- Mirrors the ``trialTable`` struct and its trial_table.h5 serialization in
+ Mirrors the trialTable struct and its trial_table.h5 serialization in
GIAnT-MATLAB. The motion-correction and source-extraction stages append
- their groups (``motion_correction``, ``source_extraction``) to this same
+ their groups (motion_correction, source_extraction) to this same
structure, so it is the shared state held by :class:`~giant_python.\
pipeline.pipeline.Pipeline`.
@@ -55,13 +50,13 @@ class TrialTable:
savedr : Path or None
Directory in which results are written.
filename : ndarray or list
- File names, shaped ``(n_dmds, n_trials)``.
+ File names, shaped (n_dmds, n_trials).
true_trial_ix : ndarray or list
- Trial indices, shaped ``(n_dmds, n_trials)``.
+ Trial indices, shaped (n_dmds, n_trials).
epoch : ndarray or list
- Epoch numbers, shaped ``(n_dmds, n_trials)``.
+ Epoch numbers, shaped (n_dmds, n_trials).
slap2_info : Slap2Info or None
- SLAP2-only metadata (``None`` for Bergamo).
+ SLAP2-only metadata (None for Bergamo).
motion_correction : dict or None
Populated by the registration stage (registered filenames, alignment
data filenames, per-trial failure flags, and registration parameters).
@@ -69,30 +64,28 @@ class TrialTable:
Populated by the extraction stage (analysis params, raw input files).
"""
- datadr: Optional[Path] = None
- savedr: Optional[Path] = None
- filename: Union[np.ndarray, list] = field(default_factory=list)
- true_trial_ix: Union[np.ndarray, list] = field(default_factory=list)
- epoch: Union[np.ndarray, list] = field(default_factory=list)
- slap2_info: Optional[Slap2Info] = None
- motion_correction: Optional[dict] = None
- source_extraction: Optional[dict] = None
+ datadr: Path | None = None
+ savedr: Path | None = None
+ filename: np.ndarray | list = field(default_factory=list)
+ true_trial_ix: np.ndarray | list = field(default_factory=list)
+ epoch: np.ndarray | list = field(default_factory=list)
+ slap2_info: Slap2Info | None = None
+ motion_correction: dict | None = None
+ source_extraction: dict | None = None
# Provenance only; never a trial-table HDF5 field.
- source_path: Optional[Path] = field(
- default=None, repr=False, compare=False
- )
+ source_path: Path | None = field(default=None, repr=False, compare=False)
@classmethod
- def from_h5(cls, path: Union[str, Path]) -> "TrialTable":
+ def from_h5(cls, path: str | Path) -> TrialTable:
"""Load a trial table from a MATLAB-compatible trial_table.h5 file.
Faithful deserialization: the on-disk group hierarchy (README
- ``trial_table.h5`` schema) is mirrored into the model with no path
- resolution or file probing. ``slap2_info`` becomes a
- :class:`Slap2Info`; ``motion_correction`` / ``source_extraction`` stay
+ trial_table.h5 schema) is mirrored into the model with no path
+ resolution or file probing. slap2_info becomes a
+ :class:`Slap2Info`; motion_correction / source_extraction stay
as nested dicts (present only once those stages have run). Callers that
- need a runtime view (absolute ``fn_adata`` paths, kept-trial mask, per-
- DMD ``alignHz``) resolve it separately.
+ need a runtime view (absolute fn_adata paths, kept-trial mask, per-
+ DMD alignHz) resolve it separately.
Parameters
----------
diff --git a/src/giant_python/numerics/baseline.py b/src/giant_python/numerics/baseline.py
index 67b56b08..e187cd52 100644
--- a/src/giant_python/numerics/baseline.py
+++ b/src/giant_python/numerics/baseline.py
@@ -1,25 +1,23 @@
"""Shared baseline (F0) estimation and dF/F assembly.
-Ported from ``extractSLAP2IntegrationSources.py`` (``_movmean_nan`` /
-``computeF0`` ref 217-305, and the dF/F assembly ref 2972-2978).
+Ported from extractSLAP2IntegrationSources.py (_movmean_nan /
+computeF0 ref 217-305, and the dF/F assembly ref 2972-2978).
:func:`compute_f0` estimates a slowly-varying fluorescence baseline via a
rolling median plus a decimated-grid rolling-min ("convex-hull"-like)
envelope, interpolated back to the full time grid with PCHIP.
:func:`assemble_dff` combines the per-trial
-least-squares traces into ``F``, re-estimates ``F0``, and forms ``dF``/``dFF``.
+least-squares traces into F, re-estimates F0, and forms dF/dFF.
"""
from __future__ import annotations
-from typing import Tuple
-
import numpy as np
import pandas as pd
from scipy.interpolate import PchipInterpolator
def _movmean_nan(x: np.ndarray, window: int) -> np.ndarray:
- """Centered, NaN-ignoring moving mean (like MATLAB ``smoothdata movmean``).
+ """Centered, NaN-ignoring moving mean (like MATLAB smoothdata movmean).
Uses partial windows at the edges and returns NaN where a window contains
no valid samples.
@@ -61,15 +59,18 @@ def _compute_f0_column(
Builds a set of decimated-grid interpolations of the trace, takes their
per-sample minimum (the rolling-min envelope), discards samples with too
few contributions, smooths/fills the gaps, and PCHIP-interpolates the
- envelope back onto the full ``total_frames`` grid.
+ envelope back onto the full total_frames grid.
+
+ Returns
+ -------
+ np.ndarray
+ The baseline of the trace column, of length total_frames.
"""
f00 = np.full((sample_times.shape[0], n_samps_in_hull), np.nan)
for dix in range(n_samps_in_hull, 0, -1):
start = dix - 1
xi = sample_times[start::n_samps_in_hull]
- f00[:, dix - 1] = np.interp(
- sample_times, xi, f0_col[xi], left=np.nan, right=np.nan
- )
+ f00[:, dix - 1] = np.interp(sample_times, xi, f0_col[xi], left=np.nan, right=np.nan)
ff = np.nanmin(f00, axis=1)
doubt = np.sum(~np.isnan(f00), axis=1) < int(np.ceil(n_samps_in_hull / 2))
@@ -90,12 +91,10 @@ def _compute_f0_column(
return pchip(np.arange(total_frames))
-def compute_f0(
- f_in: np.ndarray, denoise_window: int, hull_window: int
-) -> np.ndarray:
- """Estimate a slowly-varying fluorescence baseline ``F0``.
+def compute_f0(f_in: np.ndarray, denoise_window: int, hull_window: int) -> np.ndarray:
+ """Estimate a slowly-varying fluorescence baseline F0.
- Port of ``computeF0``: (1) a centered rolling-median denoise, (2) a
+ Port of computeF0: (1) a centered rolling-median denoise, (2) a
rolling convex-hull-like min envelope on decimated grids, (3) discard of
doubtful samples near NaNs, smoothing/filling, and PCHIP back to the full
time grid.
@@ -112,7 +111,7 @@ def compute_f0(
Returns
-------
ndarray
- The baseline ``F0``, same shape as ``f_in``.
+ The baseline F0, same shape as f_in.
"""
f = np.asarray(f_in)
orig_shape = f.shape
@@ -123,22 +122,19 @@ def compute_f0(
total_frames = f.shape[0]
if total_frames < 4:
- return np.ones_like(f_in, dtype=float) * np.nanmean(
- f_in, axis=0, keepdims=True
- )
+ return np.ones_like(f_in, dtype=float) * np.nanmean(f_in, axis=0, keepdims=True)
hull_window = int(min(hull_window, total_frames // 4))
delta_des = max(4.0, denoise_window / 6.0)
sample_times = np.rint(
- np.linspace(
- 0, total_frames - 1, num=int(np.ceil(total_frames / delta_des) + 1)
- )
+ np.linspace(0, total_frames - 1, num=int(np.ceil(total_frames / delta_des) + 1))
).astype(int)
n_samps_in_hull = int(np.ceil(hull_window / delta_des))
f0 = (
- pd.DataFrame(f)
+ pd
+ .DataFrame(f)
.rolling(window=denoise_window, center=True, min_periods=1)
.median()
.to_numpy()
@@ -150,9 +146,7 @@ def compute_f0(
for cix in range(f0.shape[1]):
if np.all(np.isnan(f0[:, cix])):
continue
- f0[:, cix] = _compute_f0_column(
- f0[:, cix], sample_times, n_samps_in_hull, total_frames
- )
+ f0[:, cix] = _compute_f0_column(f0[:, cix], sample_times, n_samps_in_hull, total_frames)
return f0.reshape(orig_shape)
@@ -162,20 +156,20 @@ def assemble_dff(
f0_ls: np.ndarray,
denoise_window: int,
hull_window: int,
-) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
- """Assemble ``F``, re-estimate ``F0``, and form ``dF``/``dFF``.
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Assemble F, re-estimate F0, and form dF/dFF.
- Reconstructs total fluorescence ``F = dF_ls + F0_ls`` from the per-motion
+ Reconstructs total fluorescence F = dF_ls + F0_ls from the per-motion
source traces (least squares or weighted averages) and background terms
(for band extraction, the backprojected background plus the backprojected
fit residual), re-estimates the baseline with
- :func:`compute_f0`, and computes ``dF = F - F0`` and ``dFF = dF /
- clip(F0, 1e-4, inf)``.
+ :func:`compute_f0`, and computes dF = F - F0 and dFF = dF /
+ clip(F0, 1e-4, inf).
Parameters
----------
d_f_ls : ndarray of shape (T, n_sources)
- Concatenated per-source dF traces (``phi``).
+ Concatenated per-source dF traces (phi).
f0_ls : ndarray of shape (T, n_sources)
Concatenated per-source background terms in the same extraction scale.
denoise_window, hull_window : int
diff --git a/src/giant_python/numerics/interpolation.py b/src/giant_python/numerics/interpolation.py
index 5933975a..2e67f59d 100644
--- a/src/giant_python/numerics/interpolation.py
+++ b/src/giant_python/numerics/interpolation.py
@@ -3,10 +3,8 @@
import numpy as np
-def nearest_interp(
- x: np.ndarray, xp: np.ndarray, yp: np.ndarray
-) -> np.ndarray:
- """Nearest-neighbor interpolation (MATLAB ``interp1(...,'nearest')``).
+def nearest_interp(x: np.ndarray, xp: np.ndarray, yp: np.ndarray) -> np.ndarray:
+ """Nearest-neighbor interpolation (MATLAB interp1(...,'nearest')).
Parameters
----------
@@ -15,12 +13,12 @@ def nearest_interp(
xp : ndarray
Sample positions (assumed sorted ascending).
yp : ndarray
- Sample values aligned with ``xp``.
+ Sample values aligned with xp.
Returns
-------
ndarray
- ``yp`` sampled at the nearest ``xp`` for each ``x``.
+ yp sampled at the nearest xp for each x.
"""
if len(xp) == 1:
return yp
diff --git a/src/giant_python/numerics/morphology.py b/src/giant_python/numerics/morphology.py
index 4e4abbb3..372478ad 100644
--- a/src/giant_python/numerics/morphology.py
+++ b/src/giant_python/numerics/morphology.py
@@ -2,21 +2,19 @@
from __future__ import annotations
-from typing import Optional
-
import numpy as np
def fast_dilation(
mask: np.ndarray,
- kernel: Optional[np.ndarray] = None,
+ kernel: np.ndarray | None = None,
iterations: int = 1,
) -> np.ndarray:
- """Binary-dilate the trailing two axes of ``mask``.
+ """Binary-dilate the trailing two axes of mask.
The common 3x3 / single-iteration case is handled with a pure-numpy shift
accumulation (fast, no OpenCV); other cases fall back to per-slice
- ``cv2.dilate`` over all leading axes.
+ cv2.dilate over all leading axes.
Parameters
----------
diff --git a/src/giant_python/numerics/peaks.py b/src/giant_python/numerics/peaks.py
index 4c637152..f6cf3f3f 100644
--- a/src/giant_python/numerics/peaks.py
+++ b/src/giant_python/numerics/peaks.py
@@ -1,8 +1,8 @@
"""Shared Gaussian peak detection in the activity image.
Ported from the peak-detection kernels of
-``extractSLAP2IntegrationSources.py`` (ref 307-712, originally
-``getActImPeaks.m``). :func:`get_act_im_peaks` finds source seeds in the 3-D
+extractSLAP2IntegrationSources.py (ref 307-712, originally
+getActImPeaks.m). :func:`get_act_im_peaks` finds source seeds in the 3-D
(Z, H, W) activity image produced by
:mod:`giant_python.extraction.band.summary_images`; those seeds initialize the
Phase-6 NMF localization.
@@ -16,17 +16,17 @@
under-amplitude peaks are removed. An optional exclusion mask (e.g. user soma
ROIs) suppresses detection in masked regions.
-The reference's nested helpers (``_make_bounds``/``_peak_mask``/
-``_buffer_mask`` and the per-component new-peak step) are lifted to
+The reference's nested helpers (_make_bounds/_peak_mask/
+_buffer_mask and the per-component new-peak step) are lifted to
module-level functions for independent reuse.
"""
from __future__ import annotations
-from typing import Tuple, cast
+from typing import cast
import numpy as np
-import scipy.ndimage as ndimage
+from scipy import ndimage
from scipy.special import erf
# Amplitude rescale applied to raw activity-image peak values when seeding the
@@ -41,7 +41,13 @@
def _validate_theta(theta: np.ndarray) -> None:
- """Require explicit amplitude, center and both axis-width columns."""
+ """Require explicit amplitude, center and both axis-width columns.
+
+ Raises
+ ------
+ ValueError
+ If theta does not have shape (N, 5).
+ """
if theta.ndim != 2 or theta.shape[1] != 5:
raise ValueError(
"Gaussian parameters must have shape (N, 5): "
@@ -50,27 +56,25 @@ def _validate_theta(theta: np.ndarray) -> None:
)
-def gaussian_peaks_integrated(
- theta: np.ndarray, yxdata: np.ndarray
-) -> np.ndarray:
+def gaussian_peaks_integrated(theta: np.ndarray, yxdata: np.ndarray) -> np.ndarray:
"""Evaluate integrated axis-aligned 2-D Gaussians at selected pixels.
Each Gaussian is integrated over unit pixels on a regular grid (port of
- ``gaussianPeaksIntegrated``). Only the ``M`` requested pixels are evaluated
+ gaussianPeaksIntegrated). Only the M requested pixels are evaluated
(the full grid is never materialized).
Parameters
----------
theta : ndarray of shape (N, 5)
- Per-Gaussian ``[amp, mu_y, mu_x, sigma_y, sigma_x]``. Equal widths
+ Per-Gaussian [amp, mu_y, mu_x, sigma_y, sigma_x]. Equal widths
must be supplied explicitly in both width columns.
yxdata : ndarray of shape (M, 2)
- Pixel-center ``[y, x]`` coordinates.
+ Pixel-center [y, x] coordinates.
Returns
-------
ndarray of shape (M,)
- Predicted value at each pixel: ``sum_n A_n * Iy[y, n] * Ix[x, n]``.
+ Predicted value at each pixel: sum_n A_n * Iy[y, n] * Ix[x, n].
"""
_validate_theta(theta)
x_int = yxdata[:, 1].astype(np.intp)
@@ -120,26 +124,26 @@ def gaussian_peaks_integrated(
def _gaussian_peaks_integrated_val_jac(
theta: np.ndarray, yxdata: np.ndarray
-) -> Tuple[np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray]:
"""Integrated Gaussians with their analytical Jacobian.
Shares the integrated-profile intermediates between the forward value and
the Jacobian so the LM solver needs one evaluation per iteration instead of
- ``P*N`` finite differences, where ``P`` is the number of parameters.
+ P*N finite differences, where P is the number of parameters.
Parameters
----------
theta : ndarray of shape (N, 5)
- Per-Gaussian ``[amp, mu_y, mu_x, sigma_y, sigma_x]``.
+ Per-Gaussian [amp, mu_y, mu_x, sigma_y, sigma_x].
yxdata : ndarray of shape (M, 2)
- Pixel-center ``[y, x]`` coordinates.
+ Pixel-center [y, x] coordinates.
Returns
-------
val : ndarray of shape (M,)
Forward value at each pixel.
jac : ndarray of shape (M, 5*N)
- Derivatives in the same order as ``theta.ravel()``.
+ Derivatives in the same order as theta.ravel().
"""
_validate_theta(theta)
x_int = yxdata[:, 1].astype(np.intp)
@@ -200,12 +204,8 @@ def _gaussian_peaks_integrated_val_jac(
dval_dmx = amp[np.newaxis, :] * iy_m * d_ix_dmx_m
sqrt2 = rt2
- d_iy_ds_m = (
- iy / sy[np.newaxis, :] + sqrt2 * (uy_b * exp_uyb2 - uy_t * exp_uyt2)
- )[y_idx, :]
- d_ix_ds_m = (
- ix / sx[np.newaxis, :] + sqrt2 * (ux_l * exp_uxl2 - ux_r * exp_uxr2)
- )[x_idx, :]
+ d_iy_ds_m = (iy / sy[np.newaxis, :] + sqrt2 * (uy_b * exp_uyb2 - uy_t * exp_uyt2))[y_idx, :]
+ d_ix_ds_m = (ix / sx[np.newaxis, :] + sqrt2 * (ux_l * exp_uxl2 - ux_r * exp_uxr2))[x_idx, :]
dval_dsy = amp[np.newaxis, :] * d_iy_ds_m * ix_m
dval_dsx = amp[np.newaxis, :] * iy_m * d_ix_ds_m
@@ -231,18 +231,18 @@ def _lsq_curvefit(
) -> np.ndarray:
"""Bounded Levenberg-Marquardt fit of integrated Gaussians.
- Reimplements the subset of MATLAB ``lsqcurvefit`` (trust-region-reflective
- defaults) used by ``getActImPeaks.m``, but with the analytical Jacobian so
+ Reimplements the subset of MATLAB lsqcurvefit (trust-region-reflective
+ defaults) used by getActImPeaks.m, but with the analytical Jacobian so
each iteration is a single value+Jacobian evaluation.
Parameters
----------
theta0 : ndarray of shape (N, 5)
- Initial ``[amp, mu_y, mu_x, sigma_y, sigma_x]`` per Gaussian.
+ Initial [amp, mu_y, mu_x, sigma_y, sigma_x] per Gaussian.
xdata : ndarray of shape (M, 2)
- Pixel-center ``[y, x]`` coordinates.
+ Pixel-center [y, x] coordinates.
ydata : ndarray of shape (M,)
- Observed values (``act_im(sel) - mu_bg``).
+ Observed values (act_im(sel) - mu_bg).
lb_flat, ub_flat : ndarray of shape (5*N,)
Row-major-flattened lower/upper bounds.
max_nfev : int
@@ -255,6 +255,12 @@ def _lsq_curvefit(
-------
ndarray of shape (N, 5)
Optimized parameters.
+
+ Raises
+ ------
+ ValueError
+ If theta0 does not have shape (N, 5), if the bounds do not have shape (5*N,), or if
+ shared_widths is set and the y/x widths or their bounds differ.
"""
_validate_theta(theta0)
if lb_flat.shape != (theta0.size,) or ub_flat.shape != (theta0.size,):
@@ -264,9 +270,7 @@ def _lsq_curvefit(
or not np.array_equal(lb_flat[3::5], lb_flat[4::5])
or not np.array_equal(ub_flat[3::5], ub_flat[4::5])
):
- raise ValueError(
- "Shared-width fitting requires equal y/x widths and bounds"
- )
+ raise ValueError("Shared-width fitting requires equal y/x widths and bounds")
x = np.clip(theta0.ravel().copy(), lb_flat, ub_flat)
val, jac = _gaussian_peaks_integrated_val_jac(x.reshape(-1, 5), xdata)
@@ -299,9 +303,7 @@ def _lsq_curvefit(
delta = np.column_stack([updates, updates[:, 3]]).ravel()
x_new = np.clip(x + delta, lb_flat, ub_flat)
- val_new, jac_new = _gaussian_peaks_integrated_val_jac(
- x_new.reshape(-1, 5), xdata
- )
+ val_new, jac_new = _gaussian_peaks_integrated_val_jac(x_new.reshape(-1, 5), xdata)
r_new = val_new - ydata
cost_new = np.dot(r_new, r_new)
nfev += 1
@@ -340,12 +342,24 @@ def _fit_isotropic_then_anisotropic(
bounds (normally [0.35, 1] pixels).
The second stage starts from that solution with sigma_y == sigma_x and
restores the original five-parameter bounds. Each stage has its own
- ``max_nfev`` budget.
+ max_nfev budget.
This is an initialization preference, not an anisotropy penalty: widths
can separate whenever that lowers the residual sum of squares. The LM
solver accepts only improving steps, retaining the isotropic solution
when relaxation cannot improve it.
+
+ Returns
+ -------
+ ndarray of shape (N, 5)
+ Fitted [amp, mu_y, mu_x, sigma_y, sigma_x] per Gaussian after the anisotropic
+ stage; a copy of theta0 if it holds no peaks.
+
+ Raises
+ ------
+ ValueError
+ If theta0 does not have shape (N, 5), if the bounds do not have shape (5*N,), or if
+ the y/x width bounds do not overlap.
"""
_validate_theta(theta0)
if lb_flat.shape != (theta0.size,) or ub_flat.shape != (theta0.size,):
@@ -362,9 +376,7 @@ def _fit_isotropic_then_anisotropic(
iso_lb[:, 4] = iso_lb[:, 3]
iso_ub[:, 4] = iso_ub[:, 3]
if np.any(iso_lb[:, 3] > iso_ub[:, 3]):
- raise ValueError(
- "Isotropic fitting requires overlapping y/x width bounds"
- )
+ raise ValueError("Isotropic fitting requires overlapping y/x width bounds")
clipped = np.clip(theta0, lb, ub)
iso0 = clipped.copy()
@@ -379,24 +391,20 @@ def _fit_isotropic_then_anisotropic(
max_nfev=max_nfev,
shared_widths=True,
)
- return _lsq_curvefit(
- isotropic, xdata, ydata, lb_flat, ub_flat, max_nfev=max_nfev
- )
+ return _lsq_curvefit(isotropic, xdata, ydata, lb_flat, ub_flat, max_nfev=max_nfev)
-def _make_bounds(
- plocs: np.ndarray, height: int, width: int
-) -> Tuple[np.ndarray, np.ndarray]:
- """Return flattened LM bounds for peaks located at ``plocs``.
+def _make_bounds(plocs: np.ndarray, height: int, width: int) -> tuple[np.ndarray, np.ndarray]:
+ """Return flattened LM bounds for peaks located at plocs.
Amplitude is unbounded above; means are constrained to +/- 1.5 px of the
- seed (clipped to the image); sigma_y to ``[0.35, 8.0]`` and sigma_x to
- ``[0.35, 1.0]``, in pixels.
+ seed (clipped to the image); sigma_y to [0.35, 8.0] and sigma_x to
+ [0.35, 1.0], in pixels.
Parameters
----------
plocs : ndarray of shape (N, 2)
- Seed ``[y, x]`` locations.
+ Seed [y, x] locations.
height, width : int
Image extents (for clipping the mean bounds).
@@ -406,29 +414,31 @@ def _make_bounds(
Row-major-flattened lower/upper bounds.
"""
n = plocs.shape[0]
- lb = np.column_stack(
- [
- np.zeros(n),
- np.maximum(0, plocs[:, 0] - 1.5),
- np.maximum(0, plocs[:, 1] - 1.5),
- np.ones(n) * 0.35,
- np.ones(n) * 0.35,
- ]
- )
- ub = np.column_stack(
- [
- np.full(n, np.inf),
- np.minimum(height - 1, plocs[:, 0] + 1.5),
- np.minimum(width - 1, plocs[:, 1] + 1.5),
- np.full(n, 8.0),
- np.full(n, 1.0),
- ]
- )
+ lb = np.column_stack([
+ np.zeros(n),
+ np.maximum(0, plocs[:, 0] - 1.5),
+ np.maximum(0, plocs[:, 1] - 1.5),
+ np.ones(n) * 0.35,
+ np.ones(n) * 0.35,
+ ])
+ ub = np.column_stack([
+ np.full(n, np.inf),
+ np.minimum(height - 1, plocs[:, 0] + 1.5),
+ np.minimum(width - 1, plocs[:, 1] + 1.5),
+ np.full(n, 8.0),
+ np.full(n, 1.0),
+ ])
return lb.ravel(), ub.ravel()
def _peak_mask(tf: np.ndarray, height: int, width: int) -> np.ndarray:
- """Return a boolean image marking each Gaussian's rounded center."""
+ """Return a boolean image marking each Gaussian's rounded center.
+
+ Returns
+ -------
+ ndarray of shape (height, width)
+ Boolean mask, True at each Gaussian's rounded (mu_y, mu_x) pixel.
+ """
pim = np.zeros((height, width), dtype=bool)
if tf.shape[0] > 0:
iy = np.clip(np.round(tf[:, 1]).astype(int), 0, height - 1)
@@ -438,11 +448,15 @@ def _peak_mask(tf: np.ndarray, height: int, width: int) -> np.ndarray:
def _buffer_mask(pim: np.ndarray, buffer_size: int) -> np.ndarray:
- """Dilate the peak mask by a ``buffer_size`` square (identity if <= 0)."""
+ """Dilate the peak mask by a buffer_size square (identity if <= 0).
+
+ Returns
+ -------
+ ndarray of bool
+ The dilated mask, or pim itself if buffer_size is not positive.
+ """
if buffer_size > 0:
- return ndimage.binary_dilation(
- pim, structure=np.ones((buffer_size, buffer_size))
- )
+ return ndimage.binary_dilation(pim, structure=np.ones((buffer_size, buffer_size)))
return pim
@@ -456,7 +470,7 @@ def _process_cc_new_peak(
reject_mask: np.ndarray,
height: int,
width: int,
-) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Add and fit one new residual peak within its connected component.
Appends the candidate to the parameter set, refits every Gaussian whose
@@ -467,7 +481,7 @@ def _process_cc_new_peak(
Parameters
----------
new_peak : tuple
- ``((pY, pX), cc_label)`` for the candidate.
+ ((pY, pX), cc_label) for the candidate.
thetaf : ndarray of shape (N, 5)
Current Gaussian parameters.
p_locs : ndarray of shape (N, 2)
@@ -493,9 +507,7 @@ def _process_cc_new_peak(
amp_new = act_im_2d[py_new, px_new] * _AMP_SCALE
n_before = thetaf.shape[0]
- thetaf = np.vstack(
- [thetaf, [amp_new, float(py_new), float(px_new), 0.5, 0.5]]
- )
+ thetaf = np.vstack([thetaf, [amp_new, float(py_new), float(px_new), 0.5, 0.5]])
p_locs = np.vstack([p_locs, [float(py_new), float(px_new)]])
new_idx = n_before
@@ -514,10 +526,7 @@ def _process_cc_new_peak(
mu_y_new = thetaf[new_idx, 1]
mu_x_new = thetaf[new_idx, 2]
- if (
- abs(mu_y_new - round(mu_y_new)) < 1e-3
- and abs(mu_x_new - round(mu_x_new)) < 1e-3
- ):
+ if abs(mu_y_new - round(mu_y_new)) < 1e-3 and abs(mu_x_new - round(mu_x_new)) < 1e-3:
refit_mask = in_cc.copy()
refit_mask[new_idx] = False
if np.any(refit_mask):
@@ -549,10 +558,10 @@ def _refine_residual_peaks(
act_sel_pix: np.ndarray,
fit_im: np.ndarray,
) -> np.ndarray:
- """Iteratively add residual peaks, one per connected component per round.
+ """Add residual peaks iteratively, one per connected component per round.
Each round finds the strongest normalized-residual pixel in every component
- and, for those above ``peak_th``, adds and fits a new Gaussian (see
+ and, for those above peak_th, adds and fits a new Gaussian (see
:func:`_process_cc_new_peak`). The fit image, residual, support, and buffer
are rebuilt once per round. Terminates when no component yields a new peak.
@@ -595,11 +604,7 @@ def _refine_residual_peaks(
max_vals = ndimage.maximum(e, labeled_full, label_ids)
max_pos = ndimage.maximum_position(e, labeled_full, label_ids)
- new_peaks = [
- (max_pos[i], label_ids[i])
- for i in range(n_labels)
- if max_vals[i] > peak_th
- ]
+ new_peaks = [(max_pos[i], label_ids[i]) for i in range(n_labels) if max_vals[i] > peak_th]
if not new_peaks:
break
@@ -627,9 +632,7 @@ def _refine_residual_peaks(
act_sel_pix = ndimage.binary_dilation(p_im, structure=np.ones((9, 9)))
act_sel_pix &= ~np.isnan(act_im_2d)
- labeled_full, _ = cast(
- tuple[np.ndarray, int], ndimage.label(act_sel_pix)
- )
+ labeled_full, _ = cast(tuple[np.ndarray, int], ndimage.label(act_sel_pix))
return thetaf
@@ -645,7 +648,7 @@ def detect_peaks_2d(
) -> np.ndarray:
"""Detect Gaussian peaks in one activity-image plane.
- Finds initial local maxima (above ``peak_thresh``), fits them jointly, then
+ Finds initial local maxima (above peak_thresh), fits them jointly, then
iteratively adds residual peaks (:func:`_refine_residual_peaks`), and
finally drops peaks whose amplitude falls below a sigma-adjusted threshold.
Every fit/refit optimizes shared widths first, then allows anisotropy.
@@ -659,18 +662,18 @@ def detect_peaks_2d(
mu_bg, sigma_bg : float
Background median and MAD-scaled sigma for the supplied region.
peak_thresh : float
- Absolute detection threshold ``mu_bg + peak_th * sigma_bg``.
+ Absolute detection threshold mu_bg + peak_th * sigma_bg.
peak_th : float
Threshold in sigma for residual peaks.
buffer_size : int
- If > 0, detected peaks are buffered by a ``buffer_size`` square when
+ If > 0, detected peaks are buffered by a buffer_size square when
suppressing nearby residual peaks.
Returns
-------
ndarray of shape (N, 5)
- ``[amp, mu_y, mu_x, sigma_y, sigma_x]`` per peak, or ``(0, 5)`` if
- none. Widths are bounded to ``[0.35, 8]`` in y and ``[0.35, 1]`` in x.
+ [amp, mu_y, mu_x, sigma_y, sigma_x] per peak, or (0, 5) if
+ none. Widths are bounded to [0.35, 8] in y and [0.35, 1] in x.
"""
height, width = act_im_2d.shape
empty = np.zeros((0, 5))
@@ -692,24 +695,20 @@ def detect_peaks_2d(
act_sel_pix = ndimage.binary_dilation(p_tmp, structure=np.ones((9, 9)))
act_sel_pix &= ~np.isnan(act_im_2d)
- thetaf = np.column_stack(
- [
- amp,
- py.astype(float),
- px.astype(float),
- 0.5 * np.ones(n_peaks),
- 0.5 * np.ones(n_peaks),
- ]
- )
+ thetaf = np.column_stack([
+ amp,
+ py.astype(float),
+ px.astype(float),
+ 0.5 * np.ones(n_peaks),
+ 0.5 * np.ones(n_peaks),
+ ])
p_locs = np.column_stack([py.astype(float), px.astype(float)])
sel_yx = np.column_stack(np.where(act_sel_pix)).astype(float)
sel_vals = act_im_2d[act_sel_pix] - mu_bg
lb_f, ub_f = _make_bounds(p_locs, height, width)
- thetaf = _fit_isotropic_then_anisotropic(
- thetaf, sel_yx, sel_vals, lb_f, ub_f, max_nfev=5000
- )
+ thetaf = _fit_isotropic_then_anisotropic(thetaf, sel_yx, sel_vals, lb_f, ub_f, max_nfev=5000)
p_im = _peak_mask(thetaf, height, width)
buffer_mask = _buffer_mask(p_im, buffer_size)
@@ -741,12 +740,7 @@ def detect_peaks_2d(
sy = thetaf[:, 3]
sx = thetaf[:, 4]
adj_thresh = peak_thresh / (
- np.pi
- / 2
- * sy
- * sx
- * erf(1 / (np.sqrt(2) * sy))
- * erf(1 / (np.sqrt(2) * sx))
+ np.pi / 2 * sy * sx * erf(1 / (np.sqrt(2) * sy)) * erf(1 / (np.sqrt(2) * sx))
)
thetaf = thetaf[thetaf[:, 0] >= adj_thresh]
@@ -769,7 +763,7 @@ def get_act_im_peaks(
suppress peak detection but do not affect connectivity or background stats.
Gaussians have independent, axis-aligned standard deviations, bounded to
- ``0.35 <= sigma_y <= 8`` and ``0.35 <= sigma_x <= 1`` pixels.
+ 0.35 <= sigma_y <= 8 and 0.35 <= sigma_x <= 1 pixels.
Each fit starts with an optimized isotropic Gaussian (shared sigma in
[0.35, 1]) before relaxing to independent widths. This favors isotropic
local minima through initialization without an explicit shape penalty.
@@ -781,16 +775,16 @@ def get_act_im_peaks(
peak_th : float
Threshold in component-local MAD-normalized standard deviations.
exclusion_mask : None or ndarray
- ``None``, a 2-D ``(H, W)`` mask applied to every plane, or a 3-D
- ``(Z, H, W)`` per-plane mask (e.g. user soma ROIs).
+ None, a 2-D (H, W) mask applied to every plane, or a 3-D
+ (Z, H, W) per-plane mask (e.g. user soma ROIs).
buffer_size : int
- If > 0, detected peaks are buffered by a ``buffer_size`` square when
+ If > 0, detected peaks are buffered by a buffer_size square when
suppressing nearby residual peaks.
Returns
-------
ndarray of shape (N, 3)
- Source seeds ``[z, mu_y, mu_x]``, or ``(0, 3)`` if none detected.
+ Source seeds [z, mu_y, mu_x], or (0, 3) if none detected.
"""
n_z, height, width = act_im.shape
empty = np.zeros((0, 3))
@@ -804,9 +798,7 @@ def get_act_im_peaks(
source_seeds_list = []
for z in range(n_z):
- labels, _ = cast(
- tuple[np.ndarray, int], ndimage.label(np.isfinite(act_im[z]))
- )
+ labels, _ = cast(tuple[np.ndarray, int], ndimage.label(np.isfinite(act_im[z])))
counts = np.bincount(labels.ravel())
for label, bounds in enumerate(ndimage.find_objects(labels), start=1):
if bounds is None or counts[label] < _MIN_COMPONENT_PIXELS:
@@ -816,9 +808,7 @@ def get_act_im_peaks(
plane_crop = act_im[z][bounds]
valid_vals = plane_crop[component]
mu_bg = float(np.median(valid_vals))
- sigma_bg = (
- float(np.median(np.abs(valid_vals - mu_bg))) / _MAD_TO_SIGMA
- )
+ sigma_bg = float(np.median(np.abs(valid_vals - mu_bg))) / _MAD_TO_SIGMA
if sigma_bg <= 0:
continue
@@ -836,13 +826,11 @@ def get_act_im_peaks(
if thetaf.shape[0] > 0:
z_col = np.full(thetaf.shape[0], z, dtype=float)
source_seeds_list.append(
- np.column_stack(
- [
- z_col,
- thetaf[:, 1] + bounds[0].start,
- thetaf[:, 2] + bounds[1].start,
- ]
- )
+ np.column_stack([
+ z_col,
+ thetaf[:, 1] + bounds[0].start,
+ thetaf[:, 2] + bounds[1].start,
+ ])
)
return np.vstack(source_seeds_list) if source_seeds_list else empty
diff --git a/src/giant_python/parallel.py b/src/giant_python/parallel.py
index f7cb2aed..841336c2 100644
--- a/src/giant_python/parallel.py
+++ b/src/giant_python/parallel.py
@@ -1,7 +1,7 @@
"""Per-trial parallelism helper (replacement for MATLAB parfor/parfeval).
Centralizes the choice of parallel backend (e.g. joblib /
-``concurrent.futures``) so stages can map a pure per-trial function over
+concurrent.futures) so stages can map a pure per-trial function over
trials without each stage reimplementing the plumbing. Also starts process
pools whose workers load their numerical libraries under given environment
variables (:func:`spawn_pool`), and reads the thread counts of the BLAS
@@ -11,14 +11,30 @@
import os
import sys
import threading
-from typing import Callable, Iterable, List, Optional, TypeVar, cast
+from collections.abc import Callable, Iterable
+from concurrent.futures import ProcessPoolExecutor
+from multiprocessing.synchronize import Barrier
+from typing import TypeVar, cast
T = TypeVar("T")
R = TypeVar("R")
-def _maybe_bar(trials: list, desc: Optional[str]):
- """Wrap ``trials`` in a tqdm bar when ``desc`` is set, else as-is."""
+def _maybe_bar(trials: list, desc: str | None) -> Iterable:
+ """Wrap trials in a tqdm bar when desc is set, else as-is.
+
+ Parameters
+ ----------
+ trials : list
+ The trials to iterate over.
+ desc : str or None
+ The bar's label; None for no bar.
+
+ Returns
+ -------
+ iterable
+ trials itself, or a tqdm bar over them.
+ """
if desc is None:
return trials
from tqdm import tqdm
@@ -30,11 +46,11 @@ def map_trials(
func: Callable[[T], R],
trials: Iterable[T],
n_workers: int = 1,
- desc: Optional[str] = None,
-) -> List[R]:
+ desc: str | None = None,
+) -> list[R]:
"""Apply *func* to each trial, optionally in parallel.
- Runs serially when ``n_workers <= 1`` (or a single trial), otherwise fans
+ Runs serially when n_workers <= 1 (or a single trial), otherwise fans
the trials out over a joblib process pool. Results are returned in input
order regardless of backend.
@@ -45,10 +61,10 @@ def map_trials(
trials : iterable
The trials to process.
n_workers : int
- Number of parallel workers. ``1`` runs serially.
+ Number of parallel workers. 1 runs serially.
desc : str, optional
When set, display a tqdm progress bar with this label as the trials are
- dispatched (used by the verbose band pipeline). ``None`` shows nothing.
+ dispatched (used by the verbose band pipeline). None shows nothing.
Returns
-------
@@ -67,9 +83,7 @@ def map_trials(
# soon as tasks are submitted, long before the workers finish.
results = cast(
Iterable[R],
- Parallel(n_jobs=n_workers, return_as="generator")(
- delayed(func)(t) for t in trials
- ),
+ Parallel(n_jobs=n_workers, return_as="generator")(delayed(func)(t) for t in trials),
)
if desc is not None:
from tqdm import tqdm
@@ -109,8 +123,11 @@ def map_trials(
def _new_start_lock() -> None:
- """A new start lock, for a forked child: the one it inherits may be
- held by a thread that does not exist in the child."""
+ """Replace the start lock, for a forked child.
+
+ The one it inherits may be held by a thread that does not exist in the
+ child.
+ """
global _START_LOCK
_START_LOCK = threading.Lock()
@@ -133,35 +150,45 @@ def _new_start_lock() -> None:
# file names of BLAS libraries whose thread count is not read here
-def check_workers(workers) -> int:
- """``workers`` if it is a positive integer, else ValueError."""
+def check_workers(workers: object) -> int:
+ """Return workers if it is a positive integer, else raise ValueError.
+
+ Parameters
+ ----------
+ workers : object
+ The requested number of workers.
+
+ Returns
+ -------
+ int
+ workers as an int.
+
+ Raises
+ ------
+ ValueError
+ If workers is not a positive integer (a bool is not one).
+ """
import numbers
- if (
- isinstance(workers, bool)
- or not isinstance(workers, numbers.Integral)
- or workers < 1
- ):
- raise ValueError(
- f"workers must be a positive integer, not {workers!r}"
- )
+ if isinstance(workers, bool) or not isinstance(workers, numbers.Integral) or workers < 1:
+ raise ValueError(f"workers must be a positive integer, not {workers!r}")
return int(workers)
-def blas_threads() -> Optional[dict]:
- """The thread count of each BLAS library loaded into this process.
+def blas_threads() -> dict | None:
+ """Return the thread count of each BLAS library loaded into this process.
The counts the libraries use now (set by the thread variables when they
- loaded, or changed since), read with ``threadpoolctl`` when it is
+ loaded, or changed since), read with threadpoolctl when it is
installed, else from the OpenBLAS libraries listed in
- ``/proc/self/maps`` (Linux) through their own getter.
+ /proc/self/maps (Linux) through their own getter.
Returns
-------
dict or None
- ``{library path: threads}``; None when they cannot be told (no
+ {library path: threads}; None when they cannot be told (no
BLAS found, a BLAS whose count cannot be read, or neither
- ``threadpoolctl`` nor ``/proc/self/maps``).
+ threadpoolctl nor /proc/self/maps).
"""
try:
from threadpoolctl import threadpool_info
@@ -182,7 +209,13 @@ def blas_threads() -> Optional[dict]:
def _mapped_paths() -> list[str]:
- """Absolute file paths mapped into this process, on Linux."""
+ """Return the absolute file paths mapped into this process, on Linux.
+
+ Returns
+ -------
+ list of str
+ The sorted paths; empty when /proc/self/maps cannot be read.
+ """
paths = set()
try:
with open("/proc/self/maps", encoding="utf-8") as f:
@@ -195,22 +228,40 @@ def _mapped_paths() -> list[str]:
return sorted(paths)
-def _threadpoolctl_blas(info) -> Optional[dict]:
- """The BLAS thread counts in ``threadpoolctl``'s report ``info``
- (None: no BLAS in it, or a count it could not read)."""
+def _threadpoolctl_blas(info: Iterable[dict]) -> dict | None:
+ """Return the BLAS thread counts in threadpoolctl's report info.
+
+ Parameters
+ ----------
+ info : iterable of dict
+ The report of threadpoolctl.threadpool_info.
+
+ Returns
+ -------
+ dict or None
+ {library path: threads}; None: no BLAS in it, or a count it
+ could not read.
+ """
try:
- found = {
- i["filepath"]: int(i["num_threads"])
- for i in info
- if i.get("user_api") == "blas"
- }
+ found = {i["filepath"]: int(i["num_threads"]) for i in info if i.get("user_api") == "blas"}
except (KeyError, TypeError, ValueError):
return None
return found or None
-def _openblas_threads(path: str) -> Optional[int]:
- """The thread count of the loaded OpenBLAS ``path`` (None: unread)."""
+def _openblas_threads(path: str) -> int | None:
+ """Return the thread count of the loaded OpenBLAS path.
+
+ Parameters
+ ----------
+ path : str
+ The path of the loaded library.
+
+ Returns
+ -------
+ int or None
+ The thread count; None: unread.
+ """
import ctypes
try:
@@ -225,26 +276,61 @@ def _openblas_threads(path: str) -> Optional[int]:
return None
-def _pool_init(barrier, timeout, initializer, initargs) -> None:
- """A pool worker's start: keep the barrier and how long to wait at it,
- run the initializer."""
+def _pool_init(
+ barrier: Barrier,
+ timeout: float,
+ initializer: Callable | None,
+ initargs: tuple,
+) -> None:
+ """Start a pool worker: keep the barrier and how long to wait at it.
+
+ Then run the initializer.
+
+ Parameters
+ ----------
+ barrier : multiprocessing.synchronize.Barrier
+ The barrier at which the workers wait for each other.
+ timeout : float
+ Seconds to wait at the barrier.
+ initializer : callable or None
+ Run in the worker once it has started.
+ initargs : tuple
+ The initializer's arguments.
+ """
global _START_BARRIER
_START_BARRIER = (barrier, timeout)
if initializer is not None:
initializer(*initargs)
-def _pool_started(names) -> dict:
- """A pool worker's first task: wait until every worker has started,
- then report its process id, the variables ``names`` and its BLAS
- thread counts (:func:`blas_threads`)."""
+def _pool_started(names: Iterable[str]) -> dict:
+ """Run a pool worker's first task: wait until every worker has started.
+
+ Then report its process id, the variables names and its BLAS
+ thread counts (:func:`blas_threads`).
+
+ Parameters
+ ----------
+ names : iterable of str
+ The names of the environment variables to report.
+
+ Returns
+ -------
+ dict
+ pid, env (the values of the variables names) and
+ blas (:func:`blas_threads`).
+
+ Raises
+ ------
+ RuntimeError
+ If the workers did not all reach the barrier in time.
+ """
barrier, timeout = _START_BARRIER
try:
barrier.wait(timeout)
except threading.BrokenBarrierError:
raise RuntimeError(
- "the pool's worker processes did not all start within "
- f"{timeout:g} s"
+ f"the pool's worker processes did not all start within {timeout:g} s"
) from None
try:
blas = blas_threads()
@@ -258,13 +344,24 @@ def _pool_started(names) -> dict:
def pool_workers(workers: int) -> int:
- """``workers``, at most the platform's limit for a process pool."""
+ """Return workers, at most the platform's limit for a process pool.
+
+ Parameters
+ ----------
+ workers : int
+ The requested number of workers.
+
+ Returns
+ -------
+ int
+ workers, capped at :data:`WINDOWS_MAX_WORKERS` on Windows.
+ """
if sys.platform == "win32":
return min(workers, WINDOWS_MAX_WORKERS)
return workers
-def stop_pool(pool, end_workers: bool = False) -> None:
+def stop_pool(pool: ProcessPoolExecutor, end_workers: bool = False) -> None:
"""Stop a process pool without waiting for it.
Its workers end by themselves once the tasks they hold have ended
@@ -274,9 +371,9 @@ def stop_pool(pool, end_workers: bool = False) -> None:
rest of it. The pool is asked to cancel its waiting tasks, which it
does only while the caller keeps the pool object; a caller that drops
it should cancel the futures it holds (closing the iterator of
- ``pool.map`` does).
+ pool.map does).
- With ``end_workers`` the worker processes are killed as well. That is
+ With end_workers the worker processes are killed as well. That is
for a pool whose start failed (:func:`spawn_pool`), whose workers hand
over nothing but their short start reports: a worker still in its
initializer or at the start barrier, or one of a pool that could not
@@ -286,6 +383,13 @@ def stop_pool(pool, end_workers: bool = False) -> None:
killed before the pool is shut down: a pool that has found a worker
dead waits for its other workers to end, and the shutdown waits for
that.
+
+ Parameters
+ ----------
+ pool : concurrent.futures.ProcessPoolExecutor
+ The pool to stop.
+ end_workers : bool
+ Kill the worker processes as well.
"""
procs = getattr(pool, "_processes", None) if end_workers else None
for proc in list(procs.values()) if procs else []:
@@ -299,17 +403,17 @@ def stop_pool(pool, end_workers: bool = False) -> None:
def spawn_pool(
workers: int,
env: dict,
- initializer: Optional[Callable] = None,
+ initializer: Callable | None = None,
initargs: tuple = (),
-):
- """A process pool whose every worker starts under ``env``.
+) -> tuple[ProcessPoolExecutor, list[dict]]:
+ """Start a process pool whose every worker starts under env.
The workers are spawned (a forked worker inherits this process's
- numerical libraries, already loaded), with the variables ``env`` set in
+ numerical libraries, already loaded), with the variables env set in
this process's environment while they start, so that their libraries
see them when they load; the environment is then restored. A pool
starts its workers one per task while none is idle, so each worker's
- first task waits until all ``workers`` have started (a barrier): all
+ first task waits until all workers have started (a barrier): all
of them exist before the environment is restored. The environment is
changed under a lock shared by every pool started here. If the start
fails or is interrupted, or if a worker has not reported twice
@@ -318,7 +422,7 @@ def spawn_pool(
start whose workers have all reported by then is complete), the pool
is stopped and its workers are killed (:func:`stop_pool`) and the
error is raised. The launch of a worker itself (the standard
- library's, which sends it ``initargs``) is not interrupted. On
+ library's, which sends it initargs) is not interrupted. On
Windows the pool has at most
:data:`WINDOWS_MAX_WORKERS` workers.
@@ -335,8 +439,13 @@ def spawn_pool(
-------
pool : concurrent.futures.ProcessPoolExecutor
started : list of dict
- Per worker, its ``pid``, the values of the variables of ``env``
+ Per worker, its pid, the values of the variables of env
and its BLAS thread counts (:func:`blas_threads`).
+
+ Raises
+ ------
+ RuntimeError
+ If a worker has not started in time.
"""
import concurrent.futures as cf
import multiprocessing
@@ -359,9 +468,7 @@ def spawn_pool(
)
# a worker waiting at the barrier is not idle, so each of
# these tasks starts a worker
- first = [
- pool.submit(_pool_started, tuple(env)) for _ in range(workers)
- ]
+ first = [pool.submit(_pool_started, tuple(env)) for _ in range(workers)]
# the workers' own wait starts when they reach the barrier;
# this one also covers their launch (which sends them the
# initializer's arguments) and their initializer
diff --git a/src/giant_python/pipeline/__init__.py b/src/giant_python/pipeline/__init__.py
index 02eda946..8aa94d9c 100644
--- a/src/giant_python/pipeline/__init__.py
+++ b/src/giant_python/pipeline/__init__.py
@@ -1,6 +1,6 @@
"""Trial tables, registration, band annotation/extraction and a facade.
-``register_multiroi`` imports PyTorch only when called.
+register_multiroi imports PyTorch only when called.
"""
from .annotate import annotate_rois
@@ -10,11 +10,11 @@
from .trial_table import build_trial_table_slap2, trim_trial_table
__all__ = [
+ "Pipeline",
"annotate_rois",
"build_trial_table_slap2",
"extract_band_sources",
"extract_sources",
- "Pipeline",
"register_multiroi",
"trim_trial_table",
]
diff --git a/src/giant_python/pipeline/annotate.py b/src/giant_python/pipeline/annotate.py
index 0e2f2a26..ef79b851 100644
--- a/src/giant_python/pipeline/annotate.py
+++ b/src/giant_python/pipeline/annotate.py
@@ -2,8 +2,6 @@
from __future__ import annotations
-from typing import Optional
-
from ..models.params import (
AnnotationInput,
BandParamsInput,
@@ -17,7 +15,7 @@ def annotate_rois(
params: BandParamsInput = None,
*,
microscope: str = "slap2",
- scan_mode: Optional[str] = "band",
+ scan_mode: str | None = "band",
execution: ExecutionInput = None,
annotations: AnnotationInput = None,
) -> str:
@@ -31,25 +29,28 @@ def annotate_rois(
params : BandSiloParams, dict or None
Scientific configuration only.
microscope : str
- Currently only ``'slap2'`` is supported.
+ Currently only 'slap2' is supported.
scan_mode : str or None
- Same routing policy as ``extract_sources``.
+ Same routing policy as extract_sources.
execution : ExecutionOptions, dict or None
Run policy, including logging.
annotations : AnnotationOptions, dict or None
ROI inclusion and GUI policy. Calling this explicit annotation
- step enables ROI handling for this call even if ``enabled=False``.
+ step enables ROI handling for this call even if enabled=False.
Returns
-------
str
Path to the written or existing annotation file.
+
+ Raises
+ ------
+ ValueError
+ If input is None.
"""
_require_band_mode(microscope, scan_mode)
if input is None:
raise ValueError("A trial-table path or TrialTable is required")
from ..extraction.band.annotation import annotate_band_rois
- return annotate_band_rois(
- input, params, execution=execution, annotations=annotations
- )
+ return annotate_band_rois(input, params, execution=execution, annotations=annotations)
diff --git a/src/giant_python/pipeline/extract.py b/src/giant_python/pipeline/extract.py
index ef2f5fee..2c5a5f10 100644
--- a/src/giant_python/pipeline/extract.py
+++ b/src/giant_python/pipeline/extract.py
@@ -7,7 +7,7 @@
from __future__ import annotations
from pathlib import Path
-from typing import Optional, Union
+from typing import Union
from ..models.experiment_summary import ExperimentSummary
from ..models.params import (
@@ -22,18 +22,21 @@
def _require_band_mode(
microscope: str,
- scan_mode: Optional[str],
+ scan_mode: str | None,
) -> None:
- """Reject unsupported routing before loading data or a backend."""
+ """Reject unsupported routing before loading data or a backend.
+
+ Raises
+ ------
+ ValueError
+ If microscope is not 'slap2' or the scan mode is not 'band'.
+ """
if microscope != "slap2":
- raise ValueError(
- "Only microscope='slap2', scan_mode='band' is supported"
- )
+ raise ValueError("Only microscope='slap2', scan_mode='band' is supported")
mode = "band" if scan_mode is None else scan_mode
if mode != "band":
raise ValueError(
- f"Source extraction for scan_mode={mode!r} is unsupported; "
- "only 'band' is supported"
+ f"Source extraction for scan_mode={mode!r} is unsupported; only 'band' is supported"
)
@@ -42,7 +45,7 @@ def extract_sources(
params: BandParamsInput = None,
*,
microscope: str = "slap2",
- scan_mode: Optional[str] = "band",
+ scan_mode: str | None = "band",
execution: ExecutionInput = None,
annotations: AnnotationInput = None,
) -> ExperimentSummary:
@@ -55,9 +58,9 @@ def extract_sources(
params : BandSiloParams, dict or None
Scientific settings only.
microscope : str
- Currently only ``'slap2'`` is supported.
+ Currently only 'slap2' is supported.
scan_mode : str or None
- Explicit routing, defaulting to band. ``None`` also selects band.
+ Explicit routing, defaulting to band. None also selects band.
execution : ExecutionOptions, dict or None
Run policy, independent of science.
annotations : AnnotationOptions, dict or None
@@ -67,16 +70,9 @@ def extract_sources(
-------
ExperimentSummary
Eager extraction results, also persisted by the backend.
-
- Raises
- ------
- ValueError
- If an unsupported microscope or scan mode is requested.
"""
_require_band_mode(microscope, scan_mode)
- return extract_band_sources(
- input, params, execution=execution, annotations=annotations
- )
+ return extract_band_sources(input, params, execution=execution, annotations=annotations)
def extract_band_sources(
@@ -90,10 +86,10 @@ def extract_band_sources(
The band-scan variant of SILo: operates on superpixel / DMD-geometry
data and the externally produced band registration lookup table
- (``fnAdataInt``), rather than on a reconstructed pixel movie. Corresponds
- to ``extractSLAP2IntegrationSources.py`` in ophys-slap2-analysis.
+ (fnAdataInt), rather than on a reconstructed pixel movie. Corresponds
+ to extractSLAP2IntegrationSources.py in ophys-slap2-analysis.
- Delegates lazily to ``giant_python.extraction.band.workflow``. All option
+ Delegates lazily to giant_python.extraction.band.workflow. All option
resolution belongs to that service.
Parameters
@@ -111,6 +107,11 @@ def extract_band_sources(
-------
ExperimentSummary
The extracted sources and summary (also written to disk).
+
+ Raises
+ ------
+ ValueError
+ If not trial-table path or TrialTable is provided.
"""
if input is None:
raise ValueError("A trial-table path or TrialTable is required")
diff --git a/src/giant_python/pipeline/pipeline.py b/src/giant_python/pipeline/pipeline.py
index ac5751b8..4d19d0cc 100644
--- a/src/giant_python/pipeline/pipeline.py
+++ b/src/giant_python/pipeline/pipeline.py
@@ -8,7 +8,7 @@
from dataclasses import replace
from pathlib import Path
-from typing import Optional
+from typing import Any
from ..models.experiment_summary import ExperimentSummary
from ..models.params import (
@@ -29,7 +29,7 @@ class Pipeline:
Parameters
----------
microscope : str
- Acquisition type; only ``"slap2"`` band extraction is implemented.
+ Acquisition type; only "slap2" band extraction is implemented.
params : BandSiloParams, dict or None
Scientific settings only; defaults to band.
execution : ExecutionOptions, dict or None
@@ -47,7 +47,7 @@ class Pipeline:
summary : ExperimentSummary or None
The extraction result (eager arrays, not a disk-backed proxy).
trial_table_path : Path or None
- Exact source filename, when known. Never inferred from ``savedr``.
+ Exact source filename, when known. Never inferred from savedr.
"""
def __init__(
@@ -57,26 +57,26 @@ def __init__(
*,
execution: ExecutionInput = None,
annotations: AnnotationInput = None,
- scan_mode: Optional[str] = "band",
+ scan_mode: str | None = "band",
) -> None:
- """Store session config; ``tt``/``summary`` start empty."""
+ """Store session config; tt/summary start empty."""
self.microscope = microscope
self.params = BandSiloParams() if params is None else params
self.execution = execution
self.annotations = annotations
self.scan_mode = scan_mode
- self.tt: Optional[TrialTable] = None
- self.summary: Optional[ExperimentSummary] = None
- self.trial_table_path: Optional[Path] = None
- self.annotation_path: Optional[str] = None
+ self.tt: TrialTable | None = None
+ self.summary: ExperimentSummary | None = None
+ self.trial_table_path: Path | None = None
+ self.annotation_path: str | None = None
@classmethod
def from_trial_table(
cls,
path: TrialTableInput,
microscope: str = "slap2",
- **kwargs,
- ) -> "Pipeline":
+ **kwargs: Any, # noqa: ANN401
+ ) -> Pipeline:
"""Start a session from a trial-table path or loaded metadata.
Parameters
@@ -85,14 +85,19 @@ def from_trial_table(
Exact filename or an already loaded table. A path is read once;
in-memory inputs are not copied, serialized or reloaded.
microscope : str
- ``"slap2"``; other acquisition types are unsupported.
+ "slap2"; other acquisition types are unsupported.
**kwargs
- Forwarded to :class:`Pipeline` (e.g. ``params`` or ``execution``).
+ Forwarded to :class:`Pipeline` (e.g. params or execution).
Returns
-------
Pipeline
- A pipeline retaining ``tt`` and its known source filename.
+ A pipeline retaining tt and its known source filename.
+
+ Raises
+ ------
+ TypeError
+ If path is neither a path nor a :class:`TrialTable`.
"""
if isinstance(path, TrialTable):
table = path
@@ -106,13 +111,22 @@ def from_trial_table(
raise TypeError("Expected a trial-table path or TrialTable")
pipeline = cls(microscope=microscope, **kwargs)
pipeline.tt = table
- pipeline.trial_table_path = (
- Path(source_path) if source_path is not None else None
- )
+ pipeline.trial_table_path = Path(source_path) if source_path is not None else None
return pipeline
def _require_trial_table(self) -> TrialTable:
- """Return loaded metadata or explain how to initialize a session."""
+ """Return loaded metadata or explain how to initialize a session.
+
+ Returns
+ -------
+ TrialTable
+ The loaded trial table.
+
+ Raises
+ ------
+ ValueError
+ If no trial table is loaded.
+ """
if self.tt is None:
raise ValueError(
"No trial table is loaded; use Pipeline.from_trial_table() "
@@ -120,17 +134,17 @@ def _require_trial_table(self) -> TrialTable:
)
return self.tt
- def annotate(self) -> "Pipeline":
+ def annotate(self) -> Pipeline:
"""Load or draw band ROIs, retaining the same trial-table object.
Uses the public annotation service and enables ROI inclusion for a
- subsequent ``extract()`` after success. Drawing is still subject to
+ subsequent extract() after success. Drawing is still subject to
explicit/headless/automatic GUI policy. Caller options are not edited.
Returns
-------
Pipeline
- ``self`` (supports method chaining).
+ self (supports method chaining).
"""
table = self._require_trial_table()
self.annotation_path = annotate_rois(
@@ -141,19 +155,17 @@ def annotate(self) -> "Pipeline":
execution=self.execution,
annotations=self.annotations,
)
- _, _, policy = resolve_band_options(
- self.params, self.execution, self.annotations
- )
+ _, _, policy = resolve_band_options(self.params, self.execution, self.annotations)
self.annotations = replace(policy, enabled=True)
return self
- def extract(self) -> "Pipeline":
- """Run source extraction, storing ``self.summary``.
+ def extract(self) -> Pipeline:
+ """Run source extraction, storing self.summary.
Returns
-------
Pipeline
- ``self`` (supports method chaining).
+ self (supports method chaining).
"""
table = self._require_trial_table()
self.summary = extract_sources(
diff --git a/src/giant_python/pipeline/reg_stats.py b/src/giant_python/pipeline/reg_stats.py
index 84618172..4d4a986a 100644
--- a/src/giant_python/pipeline/reg_stats.py
+++ b/src/giant_python/pipeline/reg_stats.py
@@ -1,11 +1,11 @@
-"""``giant reg-stats``: summary statistics of trials registered earlier.
+"""giant reg-stats: summary statistics of trials registered earlier.
The same statistics that registration computes while it writes a movie
(:mod:`giant_python.registration.stats`), for movies that already exist:
GIAnT-Python's (TIFF or HDF5) and GIAnT-MATLAB's. Each trial's raw recording
is read again for the photon-noise model (gain curves and the kernel
geometry of its frames); the frames themselves come from the registered
-movie and ``varFacDS``, and pass through the same accumulator in the same
+movie and varFacDS, and pass through the same accumulator in the same
order, so the maps equal registration's (bit for bit on the same device).
The frame times, motion, registration window and online compensation are
@@ -19,65 +19,88 @@
import json
import logging
import os
+from collections.abc import Iterator, Sequence
from pathlib import Path
-from typing import Optional, Sequence, Union
+from typing import TYPE_CHECKING
import h5py
import numpy as np
+import numpy.typing as npt
+from ..io.slap2_raster import RasterLayout
from ..io.trial_table import read_trial_table
+from ..models.params import MultiRoiRegistrationParams
+from ..models.trial_table import TrialTable
from ..parallel import map_trials
from .register import recorded_cells
+if TYPE_CHECKING:
+ import torch
+
+ from ..registration.sources import CompensatedFrames, PlainFrames
+
log = logging.getLogger(__name__)
FRAMES_PER_READ = 64
"""Frames read from the movie at a time."""
-def _scalar(f: h5py.File, name: str, default=None):
- """A scalar of a MATLAB-layout file (``default`` if absent)."""
+def _scalar(f: h5py.File, name: str, default: float | None = None) -> np.generic | float | None:
+ """Read a scalar of a MATLAB-layout file (default if absent).
+
+ Returns
+ -------
+ np.generic or float or None
+ The first element of dataset `name`, or `default` if the file has no such dataset.
+ """
if name not in f:
return default
return np.asarray(f[name][()]).ravel()[0]
def _vector(f: h5py.File, name: str) -> np.ndarray:
- """A vector of a MATLAB-layout file, flattened."""
+ """Read a vector of a MATLAB-layout file, flattened.
+
+ Returns
+ -------
+ np.ndarray
+ Dataset `name` as a flat float64 array.
+ """
return np.asarray(f[name][()], dtype=np.float64).ravel()
-def read_alignment(path: Union[str, Path]) -> dict:
- """What the statistics need from an alignment file.
+def read_alignment(path: str | Path) -> dict:
+ """Read what the statistics need from an alignment file.
Returns
-------
dict
- ``ds`` (int64 frame times), ``motion`` ``(frames, 2)``,
- ``n_channels``, ``align_hz``, ``trim_rows``, ``trim_cols`` (one-based),
- ``out_shape`` (rows, cols), ``compensated``, ``compensation`` (the
- saved ``slap2/onlineCompensation`` record when enabled, else None),
- ``unlit_masked`` (whether the frames left out the samples behind
- the DMD curtain, ``slap2/unlitMasked``; False in files registered
- before it was recorded) and ``settings`` (the recorded registration
+ ds (int64 frame times), motion (frames, 2),
+ n_channels, align_hz, trim_rows, trim_cols (one-based),
+ out_shape (rows, cols), compensated, compensation (the
+ saved slap2/onlineCompensation record when enabled, else None),
+ unlit_masked (whether the frames left out the samples behind
+ the DMD curtain, slap2/unlitMasked; False in files registered
+ before it was recorded) and settings (the recorded registration
settings, MATLAB names, or None).
+
+ Raises
+ ------
+ ValueError
+ If the file's DSframes are not whole lines.
"""
with h5py.File(path, "r") as f:
row_major = "row_major" in f and bool(np.asarray(f["row_major"]).any())
ds = _vector(f, "DSframes")
out = {
"ds": ds.astype(np.int64),
- "motion": np.stack(
- [_vector(f, "motionDSr"), _vector(f, "motionDSc")], 1
- ),
+ "motion": np.stack([_vector(f, "motionDSr"), _vector(f, "motionDSc")], 1),
"n_channels": int(_scalar(f, "numChannels")),
"align_hz": float(_scalar(f, "alignHz")),
"trim_rows": _vector(f, "slap2/trimRows").astype(np.int64),
"trim_cols": _vector(f, "slap2/trimCols").astype(np.int64),
"out_shape": _out_shape(f["slap2"], row_major),
- "compensated": bool(
- _scalar(f, "slap2/onlineCompensation/enabled", 0)
- ),
+ "compensated": bool(_scalar(f, "slap2/onlineCompensation/enabled", 0)),
"unlit_masked": bool(_scalar(f, "slap2/unlitMasked", 0)),
"settings": None,
}
@@ -95,22 +118,42 @@ def read_alignment(path: Union[str, Path]) -> dict:
def _matlab_2d(ds: h5py.Dataset, row_major: bool) -> np.ndarray:
- """A 2-D dataset in MATLAB's orientation."""
+ """Read a 2-D dataset in MATLAB's orientation.
+
+ Returns
+ -------
+ np.ndarray
+ The dataset as float64, transposed unless `row_major`.
+ """
a = np.asarray(ds[()], dtype=np.float64)
return a if row_major else a.T
def _out_shape(grp: h5py.Group, row_major: bool) -> tuple:
- """``(rows, cols)`` of the registered frame, from ``viewR`` and
- ``viewC`` (as the SILo loader reads them)."""
+ """(rows, cols) of the registered frame, from viewR and viewC.
+
+ As the SILo loader reads them.
+
+ Returns
+ -------
+ tuple
+ The number of rows and the number of columns.
+ """
rows = _matlab_2d(grp["viewR"], row_major)[:, 0]
cols = _matlab_2d(grp["viewC"], row_major)[0, :]
return rows.size, cols.size
def _compensation_record(grp: h5py.Group, row_major: bool) -> dict:
- """The fields of a saved ``onlineCompensation`` record that decide
- where samples are placed."""
+ """Read the fields of a saved onlineCompensation record.
+
+ These are the fields that decide where samples are placed.
+
+ Returns
+ -------
+ dict
+ refOffset, frameRefX, frameRefY, mapping and yLead as arrays.
+ """
return {
"refOffset": _vector(grp, "refOffset"),
"frameRefX": _vector(grp, "frameRefX"),
@@ -120,10 +163,22 @@ def _compensation_record(grp: h5py.Group, row_major: bool) -> dict:
}
-def _check_compensation(dat, source, ds, saved: Optional[dict]) -> None:
- """Refuse a trial whose online compensation, rebuilt from the raw
- recording, is not the one its registration saved (other offsets,
- references, mapping or y lead would place the samples elsewhere)."""
+def _check_compensation(
+ dat: str | Path,
+ source: PlainFrames | CompensatedFrames,
+ ds: np.ndarray,
+ saved: dict | None,
+) -> None:
+ """Refuse a trial whose online compensation differs from the one its registration saved.
+
+ The compensation is rebuilt from the raw recording; other offsets,
+ references, mapping or y lead would place the samples elsewhere.
+
+ Raises
+ ------
+ ValueError
+ If a field of the rebuilt compensation differs from the alignment file's record.
+ """
from ..registration.compensation import compensation_record
if source.compensation is None:
@@ -133,17 +188,22 @@ def _check_compensation(dat, source, ds, saved: Optional[dict]) -> None:
mine = np.asarray(rec[key], dtype=np.float64).ravel()
if not np.array_equal(mine, np.asarray(value).ravel()):
raise ValueError(
- f"{dat}: online compensation ({key}) differs from the "
- "alignment file's record"
+ f"{dat}: online compensation ({key}) differs from the alignment file's record"
)
-def registration_params(alignment: dict, table_settings: Optional[dict]):
- """The settings that formed the trial's frames.
+def registration_params(alignment: dict, table_settings: dict | None) -> MultiRoiRegistrationParams:
+ """Build the settings that formed the trial's frames.
The alignment file's own record (GIAnT-Python), else the trial table's
- ``align_params``, else the defaults; online compensation always as the
+ align_params, else the defaults; online compensation always as the
alignment file says.
+
+ Returns
+ -------
+ MultiRoiRegistrationParams
+ The registration settings, with align_hz and compensate_online taken from
+ `alignment`.
"""
from ..models.params import MultiRoiRegistrationParams
@@ -160,8 +220,30 @@ def registration_params(alignment: dict, table_settings: Optional[dict]):
return MultiRoiRegistrationParams(**kw)
-def _source(dat, first, last, alignment, params, device):
- """The trial's frame source, checked against the alignment file."""
+def _source(
+ dat: str | Path,
+ first: float,
+ last: float,
+ alignment: dict,
+ params: MultiRoiRegistrationParams,
+ device: str | torch.device,
+) -> tuple[RasterLayout, PlainFrames | CompensatedFrames, np.ndarray]:
+ """Open the trial's frame source, checked against the alignment file.
+
+ Returns
+ -------
+ layout : RasterLayout
+ The raster layout of the trial.
+ source : PlainFrames or CompensatedFrames
+ The frame source built from the raw recording.
+ ds : np.ndarray
+ The frame times of the source.
+
+ Raises
+ ------
+ ValueError
+ If the frame times or the registration window differ from the alignment file's.
+ """
from ..registration.multiroi import open_trial
from ..registration.sources import make_source
@@ -175,9 +257,7 @@ def _source(dat, first, last, alignment, params, device):
f"{dat}: frame times differ from the alignment file's "
f"({ds.size} vs {alignment['ds'].size} frames)"
)
- source = make_source(
- layout, former, first, last, init, ds, dtk, params.compensate_online
- )
+ source = make_source(layout, former, first, last, init, ds, dtk, params.compensate_online)
win = source.window
if not (
np.array_equal(win.trim_rows, alignment["trim_rows"])
@@ -188,9 +268,18 @@ def _source(dat, first, last, alignment, params, device):
return layout, source, ds
-def _movie_reader(path: Path, n_channels: int):
- """Iterator over ``(frame, (channels, rows, cols))`` float32 frames of
- a registered movie (HDF5 ``/data`` or TIFF pages)."""
+def _movie_reader(path: Path, n_channels: int) -> Iterator[tuple[int, np.ndarray]]:
+ """Iterate over the (frame, (channels, rows, cols)) float32 frames of a registered movie.
+
+ The movie is HDF5 /data or TIFF pages.
+
+ Yields
+ ------
+ frame : int
+ Index of the frame.
+ pixels : np.ndarray
+ Float32 array (channels, rows, cols) of the frame.
+ """
if path.suffix == ".h5":
with h5py.File(path, "r") as f:
data = f[next(iter(f.keys()))]
@@ -208,15 +297,18 @@ def _movie_reader(path: Path, n_channels: int):
pages = tf.pages
n = len(pages) // n_channels
for k in range(n):
- frame = [
- pages[k * n_channels + ch].asarray().T
- for ch in range(n_channels)
- ]
+ frame = [pages[k * n_channels + ch].asarray().T for ch in range(n_channels)]
yield k, np.stack(frame).astype(np.float32, copy=False)
-def _var_factor_reader(path: Path):
- """Iterator over each frame's ``(rows, cols)`` ``varFacDS``."""
+def _var_factor_reader(path: Path) -> Iterator[np.ndarray]:
+ """Iterate over each frame's (rows, cols) varFacDS.
+
+ Yields
+ ------
+ np.ndarray
+ Float32 array (rows, cols): the variance factor of one frame.
+ """
with h5py.File(path, "r") as f:
vf = f["slap2/varFacDS"]
n = vf.shape[0]
@@ -227,14 +319,14 @@ def _var_factor_reader(path: Path):
def trial_stats(
- dat,
+ dat: str | Path,
first: float,
last: float,
- movie: Union[str, Path],
- adata: Union[str, Path],
- out: Union[str, Path],
- device="cpu",
- table_settings: Optional[dict] = None,
+ movie: str | Path,
+ adata: str | Path,
+ out: str | Path,
+ device: str | torch.device = "cpu",
+ table_settings: dict | None = None,
) -> dict:
"""Compute and write one registered trial's statistics.
@@ -243,7 +335,7 @@ def trial_stats(
dat : str or Path
The raw recording.
first, last : float
- The trial's line range (trial table ``slap2_info``).
+ The trial's line range (trial table slap2_info).
movie, adata : str or Path
Registered movie and alignment file.
out : str or Path
@@ -251,13 +343,18 @@ def trial_stats(
device : str or torch.device
Where the statistics are formed.
table_settings : dict, optional
- The trial table's ``align_params`` (MATLAB names).
+ The trial table's align_params (MATLAB names).
Returns
-------
dict
The statistics (:func:`~giant_python.registration.stats.maps.
finish_maps`).
+
+ Raises
+ ------
+ ValueError
+ If the alignment file's output shape does not fit the registration window.
"""
import torch
@@ -270,7 +367,7 @@ def trial_stats(
movie, adata, out = Path(movie), Path(adata), Path(out)
align = read_alignment(adata)
params = registration_params(align, table_settings)
- layout, source, ds = _source(dat, first, last, align, params, device)
+ _layout, source, ds = _source(dat, first, last, align, params, device)
h, w = source.window.shape
margin = (align["out_shape"][0] - h) // 2
if align["out_shape"] != (h + 2 * margin, w + 2 * margin):
@@ -283,9 +380,7 @@ def trial_stats(
mr, mc = align["motion"][k]
# as registration: a frame without data is missing, whatever motion
# an alignment file (GIAnT-MATLAB's) gives it
- if not (
- np.isfinite(mr) and np.isfinite(mc) and np.isfinite(frame).any()
- ):
+ if not (np.isfinite(mr) and np.isfinite(mc) and np.isfinite(frame).any()):
acc.add_missing(k)
continue
x = torch.from_numpy(np.ascontiguousarray(frame)).to(dev)
@@ -310,8 +405,15 @@ def trial_stats(
def _up_to_date(out: Path, adata: Path, movie: Path) -> bool:
- """Whether ``out`` holds this version's statistics of ``adata`` and
- ``movie`` (same frame times and motion, same movie size)."""
+ """Whether out holds this version's statistics of adata and movie.
+
+ That is, the same frame times and motion, and the same movie size.
+
+ Returns
+ -------
+ bool
+ True if `out` exists with this statistics version and matches `adata` and `movie`.
+ """
from ..registration.stats import STATS_VERSION, alignment_digest
if not (out.exists() and adata.exists() and movie.exists()):
@@ -324,18 +426,19 @@ def _up_to_date(out: Path, adata: Path, movie: Path) -> bool:
align = read_alignment(adata)
except (OSError, KeyError, ValueError):
return False
- want = alignment_digest(
- align["ds"], align["motion"][:, 0], align["motion"][:, 1]
- )
- return (
- version == STATS_VERSION
- and digest == want
- and size == movie.stat().st_size
- )
+ want = alignment_digest(align["ds"], align["motion"][:, 0], align["motion"][:, 1])
+ return version == STATS_VERSION and digest == want and size == movie.stat().st_size
def _stats_job(job: dict) -> dict:
- """One trial; failures are logged and reported, not raised."""
+ """One trial; failures are logged and reported, not raised.
+
+ Returns
+ -------
+ dict
+ out (the statistics file path as a string) and error (None on success,
+ else the repr of the exception).
+ """
import torch
if job["threads"]:
@@ -357,8 +460,14 @@ def _stats_job(job: dict) -> dict:
return {"out": str(job["out"]), "error": repr(exc)}
-def _table_settings(path: Path) -> Optional[dict]:
- """The trial table's ``motion_correction/align_params`` (or None)."""
+def _table_settings(path: Path) -> dict | None:
+ """Read the trial table's motion_correction/align_params (or None).
+
+ Returns
+ -------
+ dict or None
+ The align_params record, or None if the table cannot be read or has none.
+ """
from ..io.hdf5 import load_struct_h5
try:
@@ -369,13 +478,27 @@ def _table_settings(path: Path) -> Optional[dict]:
return ap if isinstance(ap, dict) else None
-def _grid(value, shape) -> np.ndarray:
- """A trial-table field as an object grid of ``shape``."""
+def _grid(value: npt.ArrayLike, shape: tuple[int, ...]) -> np.ndarray:
+ """Reshape a trial-table field as an object grid of shape.
+
+ Returns
+ -------
+ np.ndarray
+ `value` as an object array of shape `shape`.
+ """
return np.asarray(value, dtype=object).reshape(shape)
-def _selected(shape, paths, trials) -> np.ndarray:
- """Cells of the requested one-based paths and trials (all if None)."""
+def _selected(
+ shape: tuple[int, ...], paths: Sequence[int] | None, trials: Sequence[int] | None
+) -> np.ndarray:
+ """Cells of the requested one-based paths and trials (all if None).
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask of shape `shape`, True for the cells to do.
+ """
keep = np.ones(shape, dtype=bool)
if paths is not None:
keep &= np.isin(np.arange(shape[0]) + 1, list(paths))[:, None]
@@ -384,9 +507,20 @@ def _selected(shape, paths, trials) -> np.ndarray:
return keep
-def _jobs(tt, files, opts: dict):
- """One job per registered trial-path that needs statistics, and the
- results of those whose movie or alignment file is missing (failed)."""
+def _jobs(tt: TrialTable, files: np.ndarray, opts: dict) -> tuple[list[dict], list[dict]]:
+ """One job per registered trial-path that needs statistics.
+
+ Also the results of those whose movie or alignment file is missing
+ (failed).
+
+ Returns
+ -------
+ jobs : list[dict]
+ The job of each registered trial-path that needs statistics.
+ missing : list[dict]
+ out and error of each requested trial-path whose movie or alignment file is
+ missing.
+ """
from ..registration.stats import stats_path
shape = files.shape
@@ -412,49 +546,47 @@ def _jobs(tt, files, opts: dict):
if not opts["overwrite"] and _up_to_date(out, adata, movie):
log.info("%s is up to date; skipping", out.name)
continue
- jobs.append(
- dict(
- dat=opts["datadr"] / str(files[d, t]),
- first=float(first[d, t]),
- last=float(last[d, t]),
- movie=movie,
- adata=adata,
- out=out,
- device=str(opts["device"]),
- settings=opts["settings"],
- threads=None,
- )
- )
+ jobs.append({
+ "dat": opts["datadr"] / str(files[d, t]),
+ "first": float(first[d, t]),
+ "last": float(last[d, t]),
+ "movie": movie,
+ "adata": adata,
+ "out": out,
+ "device": str(opts["device"]),
+ "settings": opts["settings"],
+ "threads": None,
+ })
return jobs, missing
def reg_stats(
- trial_table: Union[str, Path],
- out_dir: Optional[Union[str, Path]] = None,
+ trial_table: str | Path,
+ out_dir: str | Path | None = None,
*,
- datadr: Optional[Union[str, Path]] = None,
- moco: Optional[Union[str, Path]] = None,
+ datadr: str | Path | None = None,
+ moco: str | Path | None = None,
device: str = "auto",
max_workers: int = 1,
overwrite: bool = False,
- paths: Optional[Sequence[int]] = None,
- trials: Optional[Sequence[int]] = None,
+ paths: Sequence[int] | None = None,
+ trials: Sequence[int] | None = None,
) -> list:
"""Statistics of every registered trial of a trial table.
Parameters
----------
trial_table : str or Path
- A trial table with ``motion_correction`` (it is not changed).
+ A trial table with motion_correction (it is not changed).
out_dir : str or Path, optional
Folder for the statistics files (default: next to each movie).
datadr, moco : str or Path, optional
The raw-data folder and the motion-correction folder, if they moved
- since the table was written (default: ``datadr`` and
- ``/motion_correction``).
+ since the table was written (default: datadr and
+ /motion_correction).
device : str
- ``'auto'``, ``'cpu'``, ``'cuda'`` or ``'cuda:N'``. On the CPU up to
- ``max_workers`` trials run in parallel; on CUDA one at a time.
+ 'auto', 'cpu', 'cuda' or 'cuda:N'. On the CPU up to
+ max_workers trials run in parallel; on CUDA one at a time.
max_workers : int
Parallel trials on the CPU.
overwrite : bool
@@ -466,8 +598,13 @@ def reg_stats(
Returns
-------
list of dict
- Per trial: ``out`` and ``error`` (None if it succeeded; a requested
+ Per trial: out and error (None if it succeeded; a requested
trial whose movie or alignment file is missing has failed).
+
+ Raises
+ ------
+ ValueError
+ If the trial table has no slap2_info.
"""
from ..registration.multiroi import resolve_device
@@ -477,16 +614,16 @@ def reg_stats(
raise ValueError("the trial table has no slap2_info")
files = np.atleast_2d(np.asarray(tt.filename, dtype=object))
dev = resolve_device(device)
- opts = dict(
- moco=Path(moco) if moco else Path(tt.savedr) / "motion_correction",
- datadr=Path(datadr) if datadr else Path(tt.datadr),
- out_dir=out_dir,
- device=dev,
- settings=_table_settings(path),
- overwrite=overwrite,
- paths=paths,
- trials=trials,
- )
+ opts = {
+ "moco": Path(moco) if moco else Path(tt.savedr) / "motion_correction",
+ "datadr": Path(datadr) if datadr else Path(tt.datadr),
+ "out_dir": out_dir,
+ "device": dev,
+ "settings": _table_settings(path),
+ "overwrite": overwrite,
+ "paths": paths,
+ "trials": trials,
+ }
jobs, missing = _jobs(tt, files, opts)
workers = 1
if dev.type == "cpu":
diff --git a/src/giant_python/pipeline/register.py b/src/giant_python/pipeline/register.py
index fda789fe..47000fff 100644
--- a/src/giant_python/pipeline/register.py
+++ b/src/giant_python/pipeline/register.py
@@ -1,9 +1,9 @@
"""Register every trial of a SLAP2 raster trial table (MultiRoiRegistration).
-Outputs go to ``/motion_correction`` with GIAnT-MATLAB's names, and
-the registration fields of the trial table's ``motion_correction`` group are
-replaced in place (other groups and other ``motion_correction`` entries are
-kept), as ``MultiRoiRegistration.m`` does. The table must be MATLAB-written
+Outputs go to /motion_correction with GIAnT-MATLAB's names, and
+the registration fields of the trial table's motion_correction group are
+replaced in place (other groups and other motion_correction entries are
+kept), as MultiRoiRegistration.m does. The table must be MATLAB-written
(column-major).
A request is validated before anything is written: the table's layout, the
@@ -11,8 +11,8 @@
leaves the outputs and the table as they were.
Cells of a ragged table without a recording (empty filename) are skipped:
-their output names stay empty and they are marked ``registration_failed``,
-as SILo's ``verifyFiles`` treats missing trials. (MATLAB's
+their output names stay empty and they are marked registration_failed,
+as SILo's verifyFiles treats missing trials. (MATLAB's
MultiRoiRegistration does not skip them; their missing data file aborts the
whole run.)
"""
@@ -24,10 +24,10 @@
import os
from datetime import datetime
from pathlib import Path
-from typing import Optional, Union
import h5py
import numpy as np
+import numpy.typing as npt
from ..io.hdf5 import write_matlab_value
from ..io.trial_table import read_trial_table
@@ -44,12 +44,18 @@
def _now() -> str:
- """Local time as MATLAB's ``yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ``."""
+ """Local time as MATLAB's yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ.
+
+ Returns
+ -------
+ str
+ The current local time, ISO 8601 with millisecond precision.
+ """
return datetime.now().astimezone().isoformat(timespec="milliseconds")
-def recorded_cells(filenames) -> np.ndarray:
- """Which cells of a trial table's ``filename`` grid name a recording.
+def recorded_cells(filenames: npt.ArrayLike) -> np.ndarray:
+ """Which cells of a trial table's filename grid name a recording.
Parameters
----------
@@ -62,8 +68,14 @@ def recorded_cells(filenames) -> np.ndarray:
Same shape (rank two).
"""
- def named(x) -> bool:
- """Whether a cell holds a filename."""
+ def named(x: object) -> bool:
+ """Whether a cell holds a filename.
+
+ Returns
+ -------
+ bool
+ True if the cell is neither None nor NaN nor blank.
+ """
if x is None or (isinstance(x, float) and np.isnan(x)):
return False
return bool(str(x).strip())
@@ -84,13 +96,13 @@ def output_names(
trial, dmd : int
One-based trial and DMD indices.
params : MultiRoiRegistrationParams
- Selects ``.tif`` or ``.h5`` and the rate in the name.
+ Selects .tif or .h5 and the rate in the name.
Returns
-------
tuple of str
- ``ETDMD_REGISTERED_DOWNSAMPLED-Hz.tif`` (or
- ``.h5``) and ``ETDMD_ALIGNMENTDATA.h5``.
+ ETDMD_REGISTERED_DOWNSAMPLED-Hz.tif (or
+ .h5) and ETDMD_ALIGNMENTDATA.h5.
"""
stem = f"E{int(round(epoch))}T{trial}DMD{dmd}"
ext = ".tif" if params.save_tif else ".h5"
@@ -110,17 +122,15 @@ def output_names(
GPU_MEMORY_SHARE = 0.85
-def job_workers(
- device_type: str, execution: ExecutionOptions, n_jobs: int, n_cpu: int
-) -> tuple:
- """Processes to register trials in, and the CPU threads of each.
+def job_workers(device_type: str, execution: ExecutionOptions, n_jobs: int, n_cpu: int) -> tuple:
+ """Return the processes to register trials in, and the CPU threads of each.
Parameters
----------
device_type : str
- ``'cpu'`` or ``'cuda'``.
+ 'cpu' or 'cuda'.
execution : ExecutionOptions
- ``max_workers`` (CPU) and ``gpu_workers`` (CUDA).
+ max_workers (CPU) and gpu_workers (CUDA).
n_jobs : int
Trials to register.
n_cpu : int
@@ -129,7 +139,7 @@ def job_workers(
Returns
-------
workers : int
- At least 1, at most ``n_jobs``.
+ At least 1, at most n_jobs.
threads : int or None
None for one process (torch's default).
"""
@@ -145,10 +155,16 @@ def job_workers(
def _register_job(job: dict) -> dict:
"""Register one trial; failures are logged and reported, not raised.
- With ``gpu_fraction`` (several processes on one CUDA device) the
+ With gpu_fraction (several processes on one CUDA device) the
process keeps to that share of the device's memory, so that the memory
torch holds back for reuse in one process is not missing in another,
and gives back what it holds when the trial is done.
+
+ Returns
+ -------
+ dict
+ failed: the trial's registration_failed; error: the
+ repr of the exception that was raised, or None.
"""
import torch
@@ -182,12 +198,18 @@ def _register_job(job: dict) -> dict:
def _retry_alone(jobs: list, results: list) -> list:
- """Register again, one at a time, the trials that lacked device memory
- while several shared the device.
+ """Register again, one at a time, the trials that lacked device memory.
- Those are the trials whose registration raised an out-of-memory error
- and the registered trials without the statistics file they were to get
+ These lacked memory while several trials shared the device. Those are
+ the trials whose registration raised an out-of-memory error and the
+ registered trials without the statistics file they were to get
(registration skips the statistics when computing them fails).
+
+ Returns
+ -------
+ list
+ The outcome of each job: the earlier outcome, or that of the
+ registration done again.
"""
from ..registration.stats.io import stats_path
@@ -196,23 +218,18 @@ def _retry_alone(jobs: list, results: list) -> list:
if res["error"] is not None:
again = "out of memory" in res["error"].lower()
else:
- again = (
- bool(job.get("stats"))
- and not stats_path(job["movie"]).is_file()
- )
+ again = bool(job.get("stats")) and not stats_path(job["movie"]).is_file()
if again:
log.info("registering %s again, alone", Path(job["dat"]).name)
- out[i] = _register_job(
- {**job, "threads": None, "gpu_fraction": None}
- )
+ out[i] = _register_job({**job, "threads": None, "gpu_fraction": None})
return out
-def _reusable(movie: Path, adata: Path, settings: dict) -> Optional[bool]:
+def _reusable(movie: Path, adata: Path, settings: dict) -> bool | None:
"""Whether a trial's existing outputs can be kept, and their status.
Outputs are kept only if their alignment file records the requested
- settings, so that ``align_params`` describes every output in the
+ settings, so that align_params describes every output in the
table. Outputs made with other settings, or that do not record theirs
(e.g. MATLAB's), are registered again.
@@ -227,7 +244,7 @@ def _reusable(movie: Path, adata: Path, settings: dict) -> Optional[bool]:
Returns
-------
bool or None
- The alignment file's ``registrationFailed`` if the outputs can be
+ The alignment file's registrationFailed if the outputs can be
kept; otherwise None (register the trial again).
"""
from ..registration.outputs import SETTINGS_ATTR
@@ -251,7 +268,13 @@ def _reusable(movie: Path, adata: Path, settings: dict) -> Optional[bool]:
return failed
-def _record(results, where, failed, fn_reg, fn_adata) -> None:
+def _record(
+ results: list,
+ where: list,
+ failed: np.ndarray,
+ fn_reg: np.ndarray,
+ fn_adata: np.ndarray,
+) -> None:
"""Enter each job's outcome in the trial table's grids.
A trial whose registration raised published nothing; files left from
@@ -265,18 +288,27 @@ def _record(results, where, failed, fn_reg, fn_adata) -> None:
def _check_column_major(f: h5py.File) -> None:
- """Reject trial tables that are not MATLAB-written (column-major)."""
+ """Reject trial tables that are not MATLAB-written (column-major).
+
+ Raises
+ ------
+ ValueError
+ If the table is row-major.
+ """
flag = f.get("row_major")
if flag is not None and int(np.asarray(flag[()]).ravel()[0]) != 0:
- raise ValueError(
- "only MATLAB-written (column-major) trial tables can be updated"
- )
+ raise ValueError("only MATLAB-written (column-major) trial tables can be updated")
def _check_recordings(jobs: list) -> None:
"""Reject the request if a recording to register is not supported.
Each data file is checked once, before anything is written.
+
+ Raises
+ ------
+ ValueError
+ If a recording is not supported or cannot be read.
"""
from ..registration.multiroi import check_recording
@@ -289,8 +321,7 @@ def _check_recordings(jobs: list) -> None:
if problems:
listed = "; ".join(f"{p.name}: {e}" for p, e in problems.items())
raise ValueError(
- f"{len(problems)} recording(s) cannot be registered, so nothing "
- f"was written: {listed}"
+ f"{len(problems)} recording(s) cannot be registered, so nothing was written: {listed}"
)
@@ -317,10 +348,8 @@ def _stage(grp: h5py.Group, fields: dict) -> dict:
return staged
-def _update_trial_table(
- path: Path, fields: dict, group: str = "motion_correction"
-) -> None:
- """Replace ``fields`` in one of the table's groups.
+def _update_trial_table(path: Path, fields: dict, group: str = "motion_correction") -> None:
+ """Replace fields in one of the table's groups.
Other entries of the group (and their attributes) are left as they
are. Every new value is first written under a staged name; old values
@@ -339,35 +368,35 @@ def _update_trial_table(
def register_multiroi(
- trial_table: Union[str, Path],
+ trial_table: str | Path,
params: RegistrationParamsInput = None,
*,
execution: ExecutionInput = None,
stats: bool = True,
) -> dict:
- """Register all trials of a trial table (``MultiRoiRegistration``).
+ """Register all trials of a trial table (MultiRoiRegistration).
Parameters
----------
trial_table : str or Path
- A MATLAB-written ``trial_table.h5``; it is updated in place.
+ A MATLAB-written trial_table.h5; it is updated in place.
params : MultiRoiRegistrationParams, dict or None
Scientific settings.
execution : ExecutionOptions, dict or None
- ``device`` selects CPU or CUDA. On the CPU, up to ``max_workers``
- trials run in parallel processes; on CUDA, ``gpu_workers`` (one at
- a time by default). ``max_trials`` is ignored.
+ device selects CPU or CUDA. On the CPU, up to max_workers
+ trials run in parallel processes; on CUDA, gpu_workers (one at
+ a time by default). max_trials is ignored.
stats : bool
Also write each registered trial's summary statistics
- (``_REGSTATS-Hz.h5`` next to its movie, see
+ (_REGSTATS-Hz.h5 next to its movie, see
:mod:`giant_python.registration.stats`). Trials whose outputs are
- kept are not changed; ``giant reg-stats`` adds their statistics.
+ kept are not changed; giant reg-stats adds their statistics.
Returns
-------
dict
- The ``motion_correction`` fields written: ``fn_reg_ds``,
- ``fn_adata``, ``registration_failed`` and ``align_params``. Trials
+ The motion_correction fields written: fn_reg_ds,
+ fn_adata, registration_failed and align_params. Trials
whose registration raised, and cells without a recording, are
failed and have empty filenames.
@@ -375,7 +404,7 @@ def register_multiroi(
------
ValueError
Before anything is written, for a row-major trial table, one
- without ``slap2_info``, an unavailable device, or a recording to
+ without slap2_info, an unavailable device, or a recording to
register that is not supported (or cannot be read).
"""
from ..registration.multiroi import resolve_device
@@ -392,12 +421,8 @@ def register_multiroi(
files = np.atleast_2d(np.asarray(tt.filename, dtype=object))
n_dmd, n_trials = files.shape
epoch = np.asarray(tt.epoch, dtype=float).reshape(n_dmd, n_trials)
- first = np.asarray(tt.slap2_info.first_line, dtype=float).reshape(
- n_dmd, n_trials
- )
- last = np.asarray(tt.slap2_info.last_line, dtype=float).reshape(
- n_dmd, n_trials
- )
+ first = np.asarray(tt.slap2_info.first_line, dtype=float).reshape(n_dmd, n_trials)
+ last = np.asarray(tt.slap2_info.last_line, dtype=float).reshape(n_dmd, n_trials)
moco = Path(tt.savedr) / "motion_correction"
device = resolve_device(execution.device)
settings = settings_record(params)
@@ -418,27 +443,23 @@ def register_multiroi(
log.info("%s is already registered; skipping", adata)
failed[d, t] = saved # as recorded when registered
continue
- jobs.append(
- {
- "dat": Path(tt.datadr) / str(files[d, t]),
- # fractional for continuous recordings; MATLAB keeps
- # them unrounded (ceil(first:dt:last))
- "first": float(first[d, t]),
- "last": float(last[d, t]),
- "movie": moco / movie,
- "adata": moco / adata,
- "params": params,
- "device": str(device),
- "threads": None,
- "stats": bool(stats),
- }
- )
+ jobs.append({
+ "dat": Path(tt.datadr) / str(files[d, t]),
+ # fractional for continuous recordings; MATLAB keeps
+ # them unrounded (ceil(first:dt:last))
+ "first": float(first[d, t]),
+ "last": float(last[d, t]),
+ "movie": moco / movie,
+ "adata": moco / adata,
+ "params": params,
+ "device": str(device),
+ "threads": None,
+ "stats": bool(stats),
+ })
where.append((d, t))
_check_recordings(jobs)
moco.mkdir(parents=True, exist_ok=True)
- workers, threads = job_workers(
- device.type, execution, len(jobs), os.cpu_count() or 1
- )
+ workers, threads = job_workers(device.type, execution, len(jobs), os.cpu_count() or 1)
shared = device.type == "cuda" and workers > 1
for job in jobs:
job["threads"] = threads
diff --git a/src/giant_python/pipeline/silo.py b/src/giant_python/pipeline/silo.py
index 1226bfbe..4e3c1588 100644
--- a/src/giant_python/pipeline/silo.py
+++ b/src/giant_python/pipeline/silo.py
@@ -1,6 +1,6 @@
"""SILo for SLAP2 multi-ROI raster recordings: stages and the streaming driver.
-GIAnT-MATLAB's ``SILo.m`` (main 5a0673b) as stages, each a function from
+GIAnT-MATLAB's SILo.m (main 5a0673b) as stages, each a function from
files to files that runs for any subset of its units and skips units whose
outputs exist and were made with the same settings:
@@ -10,28 +10,28 @@
baseline trial-path registered movie ``*_BASELINE-80Hz.h5``
(slap2-f0, optional)
localize trial-path registered movie, alignment ``localize/*.h5``
-plan path localization files, ``plan/path.h5``
+plan path localization files, plan/path.h5
annotations, seeds
-prepare trial-path raw ``.dat``, plan, ``containers/*.h5``
+prepare trial-path raw .dat, plan, ``containers/*.h5``
network baseline
-dispatch session containers ``jobs/job_*.json``
+dispatch session containers jobs/job_*.json
solve job container(s), job file ``results/*.h5``
-collect session plans, results, localization ``experiment_summary.h5``,
- and alignment files ``per_trial_summary.h5``,
+collect session plans, results, localization experiment_summary.h5,
+ and alignment files per_trial_summary.h5,
trial table fields
========= ========== =========================== ========================
:func:`run_silo` runs them on one machine the way MATLAB does: per path,
trials are loaded one ahead of the solver and their subproblems solved in a
local process pool; no containers are written unless asked for. With
-``SiloExecution.prepare_workers`` or ``trial_workers`` it instead prepares
+SiloExecution.prepare_workers or trial_workers it instead prepares
the trials in several processes and solves each whole in one of several
solver processes (:func:`stream_local`), which uses a many-core workstation
far better. Every way of running gives the same results files, and
:func:`collect` makes the summaries from them.
-With ``SiloParams.baseline_source='network'`` the F0 network's baselines
-(``--baseline-dir``, or predicted with ``--f0-ckpt``) are used to localize
+With SiloParams.baseline_source='network' the F0 network's baselines
+(--baseline-dir, or predicted with --f0-ckpt) are used to localize
and, mapped onto each trial's selected pixels
(:mod:`~giant_python.extraction.raster.baseline_map`), to extract. Each
stage checks that the stage before it used the same baseline.
@@ -48,13 +48,15 @@
import threading
import time
import warnings
+from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
from concurrent.futures.process import BrokenProcessPool
from dataclasses import asdict, dataclass, replace
from pathlib import Path, PurePath
-from typing import Iterable, Optional, Sequence
+from typing import TYPE_CHECKING
import h5py
import numpy as np
+import numpy.typing as npt
from ..models.params import (
SiloExecution,
@@ -64,67 +66,117 @@
from .silo_session import (
NO_DATA,
SiloSession,
-)
-from .silo_session import attr as _attr
-from .silo_session import file_id as _file_id
-from .silo_session import (
make_pool,
pool_failure,
recording_ids,
run_jobs,
skip_hash,
+ write_skip,
)
+from .silo_session import attr as _attr
+from .silo_session import file_id as _file_id
from .silo_session import stage_hash as _hash
-from .silo_session import write_skip
+
+if TYPE_CHECKING:
+ from ..extraction.raster.baseline_map import TrialBaseline
+ from ..extraction.raster.plan import ExtractionPlan
+ from ..extraction.raster.results import TrialRecord
+ from ..extraction.raster.solver import SolverOptions
+ from ..extraction.raster.solver_setup import SolverParams, Subproblem
+ from ..extraction.raster.trial_data import TrialData
log = logging.getLogger(__name__)
# ---------------------------------------------------------------- localize
-def _localize_hash(session: SiloSession, params: SiloParams, d, t, baseline):
- """Settings hash of one localization."""
- return _hash(
- {
- "stage": "localize",
- "settings": params.stage_settings("localize"),
- "movie": _file_id(session.movie(d, t)),
- "alignment": _file_id(session.alignment(d, t)),
- "baseline": baseline,
- }
- )
+def _localize_hash(
+ session: SiloSession, params: SiloParams, d: int, t: int, baseline: dict | None
+) -> str:
+ """Return the settings hash of one localization.
+
+ Returns
+ -------
+ str
+ The hash of the stage, its settings, the movie, the alignment and the baseline.
+ """
+ return _hash({
+ "stage": "localize",
+ "settings": params.stage_settings("localize"),
+ "movie": _file_id(session.movie(d, t)),
+ "alignment": _file_id(session.alignment(d, t)),
+ "baseline": baseline,
+ })
-def _baseline_file(baseline_dir, movie: Path) -> Optional[Path]:
- """The network baseline of a registered movie."""
+def _baseline_file(baseline_dir: str | Path | None, movie: Path) -> Path | None:
+ """Return the network baseline of a registered movie.
+
+ Returns
+ -------
+ Path or None
+ The baseline file's path; None without baseline_dir.
+ """
if baseline_dir is None:
return None
stem = movie.name[: movie.name.index("_REGISTERED")]
return Path(baseline_dir) / f"{stem}_BASELINE-80Hz.h5"
-def baseline_folder(session: SiloSession, baseline_dir=None) -> Path:
- """The folder of the network's baselines: ``baseline_dir``, or the
- session's default (``/baselines``, where ``--f0-ckpt`` puts
- them)."""
+def baseline_folder(session: SiloSession, baseline_dir: str | Path | None = None) -> Path:
+ """Return the folder of the network's baselines.
+
+ It is baseline_dir, or the session's default (/baselines, where
+ --f0-ckpt puts them).
+
+ Returns
+ -------
+ Path
+ The folder.
+ """
return Path(baseline_dir) if baseline_dir else session.baselines_dir
def registered_name(session: SiloSession, d: int, t: int) -> Path:
- """The registered movie's file name that the trial table records
- (``fn_reg_ds``), whether or not the movie is here."""
+ """Return the registered movie's file name that the trial table records.
+
+ The name is that of fn_reg_ds, whether or not the movie is here.
+
+ Returns
+ -------
+ Path
+ The movie's file name, without its folder.
+ """
return Path(PurePath(str(session.fn_reg_ds[d, t]).replace("\\", "/")).name)
-def _network_baseline(session, params, d, t, baseline_dir) -> Path:
- """The baseline file of trial-path ``(d, t)``; it must exist and have
- been predicted from the movie that SILo reads (and, if it has a record,
- with this run's settings: ``check_baseline_record``)."""
+def _network_baseline(
+ session: SiloSession,
+ params: SiloParams,
+ d: int,
+ t: int,
+ baseline_dir: str | Path | None,
+) -> Path:
+ """Return the baseline file of trial-path (d, t).
+
+ It must exist and have been predicted from the movie that SILo reads (and, if it has a
+ record, with this run's settings: check_baseline_record).
+
+ Returns
+ -------
+ Path
+ The baseline file.
+
+ Raises
+ ------
+ FileNotFoundError
+ If the baseline file does not exist.
+ ValueError
+ If the baseline was predicted from another movie than the one SILo reads.
+ """
from .silo_baseline import check_baseline_record
- base = _baseline_file(
- baseline_folder(session, baseline_dir), registered_name(session, d, t)
- )
+ base = _baseline_file(baseline_folder(session, baseline_dir), registered_name(session, d, t))
if not base.exists():
raise FileNotFoundError(
f"no network baseline: {base} (predict it with --f0-ckpt, or "
@@ -144,9 +196,16 @@ def _network_baseline(session, params, d, t, baseline_dir) -> Path:
return base
-def _recorded(path, name: str, default: str = "median") -> str:
- """A stage file's record of the baseline it used (files made before
- the network baseline was wired in used the moving median)."""
+def _recorded(path: Path, name: str, default: str = "median") -> str:
+ """Return a stage file's record of the baseline it used.
+
+ Files made before the network baseline was wired in used the moving median.
+
+ Returns
+ -------
+ str
+ The recorded value, or default when the file has none.
+ """
value = _attr(path, name)
if isinstance(value, bytes):
value = value.decode()
@@ -154,9 +213,15 @@ def _recorded(path, name: str, default: str = "median") -> str:
def _check_same(
- what: str, used, given, option: str, flag: str = "--baseline"
+ what: str, used: object, given: object, option: str, flag: str = "--baseline"
) -> None:
- """Refuse a stage whose settings differ from the stage before it."""
+ """Refuse a stage whose settings differ from the stage before it.
+
+ Raises
+ ------
+ ValueError
+ If used and given differ.
+ """
if used != given:
raise ValueError(
f"{what} was made with {option}={used!r}, these settings have "
@@ -166,20 +231,35 @@ def _check_same(
def _needs_halves(params: SiloParams) -> bool:
- """Whether the plan needs each trial's half images (the patchwise
- alignment weights its patches with them)."""
+ """Return whether the plan needs each trial's half images.
+
+ The patchwise alignment weights its patches with them.
+
+ Returns
+ -------
+ bool
+ True when the inter-trial alignment is patchwise.
+ """
return params.inter_trial_alignment == "patchwise"
-def _has_halves(path) -> bool:
- """Whether a localization file holds the trial's half images."""
+def _has_halves(path: Path) -> bool:
+ """Return whether a localization file holds the trial's half images.
+
+ Returns
+ -------
+ bool
+ True when the file holds them.
+ """
return bool(_attr(path, "half_ims"))
-def check_plan_alignment(what: str, plan, params: SiloParams) -> None:
- """Refuse to extract or collect with another across-trial alignment
- than the plan's: the trials are read through the plan's maps, and the
- summaries record these settings."""
+def check_plan_alignment(what: str, plan: ExtractionPlan, params: SiloParams) -> None:
+ """Refuse to extract or collect with another across-trial alignment than the plan's.
+
+ The trials are read through the plan's maps, and the
+ summaries record these settings.
+ """
_check_same(
what,
plan.params.inter_trial_alignment,
@@ -197,8 +277,14 @@ def check_plan_alignment(what: str, plan, params: SiloParams) -> None:
)
-def check_plan_seeding(what: str, plan, params: SiloParams) -> None:
- """Check the seeding settings used by the summary and evidence test."""
+def check_plan_seeding(what: str, plan: ExtractionPlan, params: SiloParams) -> None:
+ """Check the seeding settings used by the summary and evidence test.
+
+ Raises
+ ------
+ ValueError
+ If the plan was seeded with other settings than params.
+ """
used, given = float(plan.params.peak_th), float(params.peak_th)
if used != given:
raise ValueError(
@@ -221,9 +307,11 @@ def check_plan_seeding(what: str, plan, params: SiloParams) -> None:
)
-def check_plan_support(what: str, plan, params: SiloParams) -> None:
- """Refuse to extract with a footprint support other than the one the
- plan's zones were made for (``valid_kernel``: one per run)."""
+def check_plan_support(what: str, plan: ExtractionPlan, params: SiloParams) -> None:
+ """Refuse to extract with a footprint support other than the plan's.
+
+ The support is the one the plan's zones were made for (valid_kernel: one per run).
+ """
_check_same(
what,
int(plan.params.valid_kernel),
@@ -234,19 +322,32 @@ def check_plan_support(what: str, plan, params: SiloParams) -> None:
def trial_null_seed(base: int, d: int, t: int, draws: int = 1) -> int:
- """The first null seed of trial-path ``(d, t)`` (zero-based) when the
- run keeps its null images: ``base`` plus a trial-path offset, so that
+ """Return the first null seed of trial-path (d, t) (zero-based).
+
+ This is for a run that keeps its null images: base plus a trial-path offset, so that
the trials' null movies are independent draws (with one seed for all
trials the same random stream recurs in every trial, and the combined
- null keeps much of one trial's spread). A trial-path's ``draws`` seeds
- (``seed .. seed + draws - 1``) never overlap another's: offsets are
- ``max(1000, draws)`` apart."""
+ null keeps much of one trial's spread). A trial-path's draws seeds
+ (seed .. seed + draws - 1) never overlap another's: offsets are
+ max(1000, draws) apart.
+
+ Returns
+ -------
+ int
+ The first seed of the trial-path.
+ """
width = max(1000, int(draws))
return int(base) + width * (1 + int(t) + 100000 * int(d))
def _localize_job(job: dict) -> dict:
- """Localize one trial-path and write its file (a pool task)."""
+ """Localize one trial-path and write its file (a pool task).
+
+ Returns
+ -------
+ dict
+ unit, seconds and peak_seconds of the task.
+ """
from ..extraction.raster.peaks import get_act_im_peaks
from ..extraction.raster.stage_files import write_localization
from ..extraction.raster.trial import localize_trial
@@ -257,9 +358,7 @@ def _localize_job(job: dict) -> dict:
if p.localization_keep_null:
lp = replace(
lp,
- null_seed=trial_null_seed(
- lp.null_seed, *job["unit"], draws=lp.null_draws
- ),
+ null_seed=trial_null_seed(lp.null_seed, *job["unit"], draws=lp.null_draws),
)
loc, trial = localize_trial(
job["moco_dir"],
@@ -307,7 +406,13 @@ def _localize_job(job: dict) -> dict:
def _peaks_job(job: dict) -> dict:
- """Fit one localized trial's peaks and add them to its file."""
+ """Fit one localized trial's peaks and add them to its file.
+
+ Returns
+ -------
+ dict
+ unit and seconds of the task.
+ """
from ..extraction.raster.peaks import get_act_im_peaks
from ..extraction.raster.stage_files import add_peaks, read_localization
@@ -325,14 +430,20 @@ def _peaks_job(job: dict) -> dict:
return {"unit": job["unit"], "seconds": time.perf_counter() - t0}
-def _units(session: SiloSession, units, paths=None) -> list:
- """Kept trial-paths ``(d, t)``, zero-based, of ``units`` or all."""
+def _units(
+ session: SiloSession,
+ units: Iterable[tuple[int, int]] | None,
+ paths: Collection[int] | None = None,
+) -> list:
+ """Return the kept trial-paths (d, t), zero-based, of units or all.
+
+ Returns
+ -------
+ list of tuple of int
+ The kept (path, trial) pairs.
+ """
if units is None:
- units = [
- (d, t)
- for d in range(session.n_paths)
- for t in range(session.n_trials)
- ]
+ units = [(d, t) for d in range(session.n_paths) for t in range(session.n_trials)]
out = []
for d, t in units:
if paths is not None and d not in paths:
@@ -345,22 +456,22 @@ def _units(session: SiloSession, units, paths=None) -> list:
def localize_jobs(
session: SiloSession,
params: SiloParams,
- units=None,
- baseline_dir=None,
+ units: Iterable[tuple[int, int]] | None = None,
+ baseline_dir: str | Path | None = None,
fit_peaks: bool = True,
overwrite: bool = False,
) -> list:
- """The localization tasks still to do (stage ``localize``).
+ """Return the localization tasks still to do (stage localize).
Parameters
----------
session : SiloSession
params : SiloParams
units : iterable of (int, int), optional
- Zero-based ``(path, trial)`` pairs (default: every kept one).
+ Zero-based (path, trial) pairs (default: every kept one).
baseline_dir : str or Path, optional
- Folder of the network baseline files (``localization_baseline =
- 'network'``; default: the session's ``baselines`` folder).
+ Folder of the network baseline files (localization_baseline =
+ 'network'; default: the session's baselines folder).
fit_peaks : bool
Fit the per-trial peaks in the same task (otherwise
:func:`peaks_jobs` does it later).
@@ -376,67 +487,65 @@ def localize_jobs(
jobs = []
for d, t in _units(session, units):
movie = session.movie(d, t)
- base = (
- _network_baseline(session, params, d, t, baseline_dir)
- if network
- else None
- )
- h = _localize_hash(
- session, params, d, t, None if base is None else _file_id(base)
- )
+ base = _network_baseline(session, params, d, t, baseline_dir) if network else None
+ h = _localize_hash(session, params, d, t, None if base is None else _file_id(base))
out = session.localize_file(d, t)
if (
not overwrite
and _attr(out, "settings_hash") == h
# files made before the baseline was recorded: those made with
# the network are redone (the plan stage would refuse them)
- and _recorded(out, "localization_baseline")
- == params.localization_baseline
+ and _recorded(out, "localization_baseline") == params.localization_baseline
# the patchwise alignment needs the half images, which files
# localized for another alignment lack
and (not _needs_halves(params) or _has_halves(out))
):
continue
out.parent.mkdir(parents=True, exist_ok=True)
- jobs.append(
- {
- "unit": (d, t),
- "params": asdict(params),
- "moco_dir": str(session.moco_dir),
+ jobs.append({
+ "unit": (d, t),
+ "params": asdict(params),
+ "moco_dir": str(session.moco_dir),
+ "movie": movie.name,
+ "num_channels": session.num_channels,
+ "align_hz": session.align_hz,
+ "baseline_dir": (str(base.parent) if base is not None else None),
+ "fit_peaks": fit_peaks,
+ "out": str(out),
+ "attrs": {
+ "settings_hash": h,
"movie": movie.name,
- "num_channels": session.num_channels,
+ "path": d + 1,
+ "trial": t + 1,
"align_hz": session.align_hz,
- "baseline_dir": (
- str(base.parent) if base is not None else None
+ "num_channels": session.num_channels,
+ "localization_baseline": params.localization_baseline,
+ # the file localized with (extraction must use it too)
+ # and its network, for the summary
+ "network_baseline": (
+ json.dumps(baseline_provenance(base), sort_keys=True)
+ if base is not None
+ else ""
),
- "fit_peaks": fit_peaks,
- "out": str(out),
- "attrs": {
- "settings_hash": h,
- "movie": movie.name,
- "path": d + 1,
- "trial": t + 1,
- "align_hz": session.align_hz,
- "num_channels": session.num_channels,
- "localization_baseline": params.localization_baseline,
- # the file localized with (extraction must use it too)
- # and its network, for the summary
- "network_baseline": (
- json.dumps(baseline_provenance(base), sort_keys=True)
- if base is not None
- else ""
- ),
- },
- }
- )
+ },
+ })
return jobs
-def peaks_jobs(session: SiloSession, params: SiloParams, units=None) -> list:
- """Peak fits still to do: localization files without peaks (in the
- file or its ``.peaks.h5`` sidecar, where :func:`_peaks_job` writes
+def peaks_jobs(
+ session: SiloSession, params: SiloParams, units: Iterable[tuple[int, int]] | None = None
+) -> list:
+ """Return the peak fits still to do: localization files without peaks.
+
+ The peaks are in the file or its .peaks.h5 sidecar, where :func:`_peaks_job` writes
them so that the localization file is not written while the plan stage
- reads it)."""
+ reads it.
+
+ Returns
+ -------
+ list of dict
+ Tasks for :func:`_peaks_job`.
+ """
from ..extraction.raster.stage_files import localization_attrs
if not params.trial_peaks:
@@ -447,27 +556,25 @@ def peaks_jobs(session: SiloSession, params: SiloParams, units=None) -> list:
f = session.localize_file(d, t)
attrs = localization_attrs(f)
if attrs is not None and not int(attrs.get("peaks_fitted", 0)):
- jobs.append(
- {
- "unit": (d, t),
- "file": str(f),
- "peak_th": loc.peak_th,
- "min_peak_distance": loc.min_peak_distance,
- "seed_fit": params.seed_fit,
- "seed_merge_px": params.seed_merge_px,
- }
- )
+ jobs.append({
+ "unit": (d, t),
+ "file": str(f),
+ "peak_th": loc.peak_th,
+ "min_peak_distance": loc.min_peak_distance,
+ "seed_fit": params.seed_fit,
+ "seed_merge_px": params.seed_merge_px,
+ })
return jobs
def localize(
session: SiloSession,
params: SiloParams,
- execution: Optional[SiloExecution] = None,
- units=None,
- baseline_dir=None,
+ execution: SiloExecution | None = None,
+ units: Iterable[tuple[int, int]] | None = None,
+ baseline_dir: str | Path | None = None,
) -> list:
- """Stage ``localize``: one localization file per trial-path.
+ """Stage localize: one localization file per trial-path.
Units whose files exist with the same settings are kept, but their
per-trial peaks are fitted if they are missing.
@@ -475,43 +582,55 @@ def localize(
Returns
-------
list of dict
- Per localized unit (and per peak fit): ``unit`` and ``seconds``.
+ Per localized unit (and per peak fit): unit and seconds.
"""
ex = execution or SiloExecution()
- jobs = localize_jobs(
- session, params, units, baseline_dir, True, ex.overwrite
- )
+ jobs = localize_jobs(session, params, units, baseline_dir, True, ex.overwrite)
threads = max(1, (os.cpu_count() or 1) // max(1, ex.workers))
done = run_jobs(_localize_job, jobs, ex.workers, threads)
# peaks still missing (e.g. a streaming run stopped before its
# background fits ended): fit them now
- done += run_jobs(
- _peaks_job, peaks_jobs(session, params, units), ex.workers, threads
- )
+ done += run_jobs(_peaks_job, peaks_jobs(session, params, units), ex.workers, threads)
return done
# ---------------------------------------------------------------- plan
-def _plan_inputs(session: SiloSession, d: int, half_ims: bool = False):
- """The localization records of path ``d`` (None for trials without);
- the half images only with ``half_ims``."""
+def _plan_inputs(session: SiloSession, d: int, half_ims: bool = False) -> list:
+ """Return the localization records of path d (None for trials without).
+
+ The half images only with half_ims.
+
+ Returns
+ -------
+ list
+ One localization record per trial, None for trials not kept.
+ """
from ..extraction.raster.stage_files import read_localization
recs = []
for t in range(session.n_trials):
f = session.localize_file(d, t)
recs.append(
- read_localization(f, peaks=False, half_ims=half_ims)
- if session.keep[d, t]
- else None
+ read_localization(f, peaks=False, half_ims=half_ims) if session.keep[d, t] else None
)
return recs
-def _localization_hashes(session, d) -> dict:
- """The settings hashes of path ``d``'s localization files, by trial."""
+def _localization_hashes(session: SiloSession, d: int) -> dict:
+ """Return the settings hashes of path d's localization files, by trial.
+
+ Returns
+ -------
+ dict
+ The settings hash of each kept trial's localization file, by trial index.
+
+ Raises
+ ------
+ FileNotFoundError
+ If a kept trial is not localized.
+ """
locs = {}
for t in range(session.n_trials):
if session.keep[d, t]:
@@ -522,11 +641,18 @@ def _localization_hashes(session, d) -> dict:
return locs
-def check_plan_localizations(session, d) -> None:
- """Refuse a plan whose trials were localized again since it was made
- (their peaks and baselines would not be the plan's): the plan records
+def check_plan_localizations(session: SiloSession, d: int) -> None:
+ """Refuse a plan whose trials were localized again since it was made.
+
+ Their peaks and baselines would not be the plan's: the plan records
its localizations' settings hashes (plans made before that are not
- checked)."""
+ checked).
+
+ Raises
+ ------
+ ValueError
+ If a trial was localized again since the plan was made.
+ """
made = _attr(session.plan_file(d), "localization_hashes")
if not made:
return
@@ -543,11 +669,24 @@ def check_plan_localizations(session, d) -> None:
def _plan_hash(
- session, params, d, seeds, annotations, frame_origins=None
+ session: SiloSession,
+ params: SiloParams,
+ d: int,
+ seeds: npt.ArrayLike | None,
+ annotations: dict | None,
+ frame_origins: npt.ArrayLike | None = None,
) -> str:
- """Settings hash of a path's plan. The trials' frame origins enter it
+ """Return the settings hash of a path's plan.
+
+ The trials' frame origins enter it
only when they differ among the kept trials (so that plans of sessions
- whose ROIs never changed keep their hash)."""
+ whose ROIs never changed keep their hash).
+
+ Returns
+ -------
+ str
+ The hash of the stage, its settings, the localizations, the seeds and the annotations.
+ """
locs = _localization_hashes(session, d)
record = {
"stage": "plan",
@@ -564,11 +703,18 @@ def _plan_hash(
return _hash(record)
-def trial_frame_origins(session, d: int) -> np.ndarray:
- """Raster start ``[row, col]`` of the registered image of every trial
- of path ``d`` (NaN for trials without an alignment file or without
- the fields), see
- :func:`~giant_python.extraction.raster.plan.read_frame_origins`."""
+def trial_frame_origins(session: SiloSession, d: int) -> np.ndarray:
+ """Return the raster start [row, col] of the registered image of every trial of path d.
+
+ NaN for trials without an alignment file or without
+ the fields, see
+ :func:`~giant_python.extraction.raster.plan.read_frame_origins`.
+
+ Returns
+ -------
+ np.ndarray
+ The raster start [row, col] of each trial's registered image.
+ """
from ..extraction.raster.plan import read_frame_origins
files = []
@@ -578,10 +724,12 @@ def trial_frame_origins(session, d: int) -> np.ndarray:
return read_frame_origins(files)
-def write_user_rois(path: Path, labels: Sequence[str], masks) -> None:
- """Add the user ROIs in the consensus frame to a plan file
- (``/user_rois``: ``labels`` JSON attribute, ``masks`` (rois, rows,
- cols) uint8)."""
+def write_user_rois(path: Path, labels: Sequence[str], masks: npt.ArrayLike) -> None:
+ """Add the user ROIs in the consensus frame to a plan file.
+
+ They are stored as /user_rois: labels JSON attribute, masks (rois, rows,
+ cols) uint8.
+ """
with h5py.File(path, "a") as f:
if "user_rois" in f:
del f["user_rois"]
@@ -591,12 +739,20 @@ def write_user_rois(path: Path, labels: Sequence[str], masks) -> None:
g.create_dataset(
"masks",
data=m,
- **(dict(compression="gzip", compression_opts=4) if m.size else {}),
+ **({"compression": "gzip", "compression_opts": 4} if m.size else {}),
)
def read_user_rois(path: Path) -> tuple[list, list]:
- """The user ROIs of a plan file: labels and masks."""
+ """Return the user ROIs of a plan file: labels and masks.
+
+ Returns
+ -------
+ labels : list
+ The ROIs' labels.
+ masks : list of np.ndarray
+ The ROIs' boolean masks.
+ """
with h5py.File(path, "r") as f:
if "user_rois" not in f:
return [], []
@@ -606,7 +762,7 @@ def read_user_rois(path: Path) -> tuple[list, list]:
return labels, masks
-def _warn_frame_offsets(plan, d: int) -> None:
+def _warn_frame_offsets(plan: ExtractionPlan, d: int) -> None:
"""Say so when a path's trials start at different raster positions."""
if plan.frame_offset is None or not plan.frame_offset.any():
return
@@ -624,11 +780,11 @@ def plan_one(
session: SiloSession,
params: SiloParams,
d: int,
- seeds: Optional[np.ndarray] = None,
+ seeds: np.ndarray | None = None,
overwrite: bool = False,
refine_workers: int = 1,
-) -> Optional[Path]:
- """Stage ``plan`` for path ``d``: ``plan/path.h5``.
+) -> Path | None:
+ """Stage plan for path d: plan/path.h5.
Parameters
----------
@@ -637,8 +793,8 @@ def plan_one(
d : int
Zero-based path.
seeds : ndarray of shape (n, 4), optional
- Zero-based ``[amplitude, row, col, sigma]`` used instead of the
- plan's own seeding (MATLAB's ``thetaf``, for parity runs).
+ Zero-based [amplitude, row, col, sigma] used instead of the
+ plan's own seeding (MATLAB's thetaf, for parity runs).
overwrite : bool
Redo a plan made with the same settings.
refine_workers : int
@@ -706,9 +862,7 @@ def plan_one(
write_user_rois(
tmp,
[r.label for r in rois],
- np.array([r.mask for r in rois]).reshape(
- (len(rois),) + plan.shape
- ),
+ np.array([r.mask for r in rois]).reshape((len(rois),) + plan.shape),
)
with h5py.File(tmp, "a") as f:
f.attrs["settings_hash"] = h
@@ -726,10 +880,18 @@ def plan_one(
return out
-def _check_localizations(session: SiloSession, params: SiloParams, d: int):
- """Refuse to plan path ``d`` from localizations made with another
+def _check_localizations(session: SiloSession, params: SiloParams, d: int) -> None:
+ """Refuse to plan path d from localizations that do not fit these settings.
+
+ These are localizations made with another
baseline than these settings', or without the half images that a
- patchwise alignment needs."""
+ patchwise alignment needs.
+
+ Raises
+ ------
+ ValueError
+ If a localization lacks the half images that the patchwise alignment needs.
+ """
for t in np.flatnonzero(session.keep[d]):
f = session.localize_file(d, int(t))
if f.exists():
@@ -748,7 +910,13 @@ def _check_localizations(session: SiloSession, params: SiloParams, d: int):
def _z_depth(session: SiloSession, d: int) -> float:
- """``Z_depths`` of path ``d`` (first kept trial's alignment file)."""
+ """Return Z_depths of path d (first kept trial's alignment file).
+
+ Returns
+ -------
+ float
+ The depth; NaN when no trial is kept.
+ """
from ..extraction.raster.summary import read_alignment_record
kept = np.flatnonzero(session.keep[d])
@@ -763,17 +931,31 @@ def _z_depth(session: SiloSession, d: int) -> float:
def refine_workers(threads: int, workers: int) -> int:
- """Worker processes for a path's per-trial refits, given the threads
- its plan has and the run's ``workers`` (``SiloExecution.workers``):
+ """Return the worker processes for a path's per-trial refits.
+
+ These are given the threads
+ its plan has and the run's workers (SiloExecution.workers):
up to :data:`REFINE_WORKERS`; none (1) when the run has one worker,
- which keeps the whole plan in one process."""
+ which keeps the whole plan in one process.
+
+ Returns
+ -------
+ int
+ The number of worker processes.
+ """
if workers <= 1:
return 1
return max(1, min(REFINE_WORKERS, int(threads)))
-def _plan_job(job: dict):
- """:func:`plan_one` as a pool task."""
+def _plan_job(job: dict) -> dict:
+ """Run :func:`plan_one` as a pool task.
+
+ Returns
+ -------
+ dict
+ path, file and seconds of the task.
+ """
session = job["session"]
t0 = time.perf_counter()
out = plan_one(
@@ -790,40 +972,40 @@ def _plan_job(job: dict):
def plan(
session: SiloSession,
params: SiloParams,
- execution: Optional[SiloExecution] = None,
- paths: Optional[Iterable[int]] = None,
- seeds: Optional[list] = None,
+ execution: SiloExecution | None = None,
+ paths: Iterable[int] | None = None,
+ seeds: list | None = None,
workers_from_here: bool = False,
) -> list:
- """Stage ``plan`` for several paths (in parallel processes).
+ """Stage plan for several paths (in parallel processes).
- With ``execution.workers`` 1 the paths are planned here, one after
+ With execution.workers 1 the paths are planned here, one after
another, without child processes. With more, the paths are planned in
- a pool of up to ``execution.workers`` processes (a process plans more
+ a pool of up to execution.workers processes (a process plans more
than one path when there are fewer), and each path's patchwise
alignment refits its trials in up to :data:`REFINE_WORKERS` more
(:func:`refine_workers`). A single path is planned here, and then
- starts no process either unless ``workers_from_here`` is set.
+ starts no process either unless workers_from_here is set.
Parameters
----------
paths : iterable of int, optional
Zero-based paths (default: all).
seeds : list of (ndarray or None), optional
- Per path, seeds to use instead of seeding (``read_seeds``).
+ Per path, seeds to use instead of seeding (read_seeds).
workers_from_here : bool
Whether a single path, which is planned in this process, may
start the refit workers from it. False by default, so that a call
that plans one path starts no process, as before there were refit
- workers; ``giant silo-plan`` sets it. A script that sets it must
- call this under ``if __name__ == "__main__":`` (the workers are
+ workers; giant silo-plan sets it. A script that sets it must
+ call this under if __name__ == "__main__": (the workers are
spawned and import the script), as one that plans several paths
with several workers must.
Returns
-------
list of dict
- ``path``, ``file`` and ``seconds`` of each path.
+ path, file and seconds of each path.
"""
ex = execution or SiloExecution()
paths = list(range(session.n_paths)) if paths is None else list(paths)
@@ -846,18 +1028,22 @@ def plan(
# idle BLAS threads sleep: the plan's many small calls left 64 threads
# per path spinning (the thread count is kept: it can change the seeds'
# last bits)
- return run_jobs(
- _plan_job, jobs, min(ex.workers, len(jobs)), threads, blas_idle=True
- )
+ return run_jobs(_plan_job, jobs, min(ex.workers, len(jobs)), threads, blas_idle=True)
# ---------------------------------------------------------------- prepare
def load_trial_for(
- session: SiloSession, params: SiloParams, plan, d, t, rois, device="cpu"
-):
- """Trial ``t`` of path ``d`` at the plan's selected pixels.
+ session: SiloSession,
+ params: SiloParams,
+ plan: ExtractionPlan,
+ d: int,
+ t: int,
+ rois: Sequence[np.ndarray],
+ device: str = "cpu",
+) -> TrialData:
+ """Load trial t of path d at the plan's selected pixels.
Returns
-------
@@ -885,13 +1071,21 @@ def _prepare_hash(
session: SiloSession,
params: SiloParams,
plan_hash: str,
- d,
- t,
- baseline: Optional[Path] = None,
+ d: int,
+ t: int,
+ baseline: Path | None = None,
) -> str:
- """Settings hash of a container: the prepare settings, the plan, the
+ """Return the settings hash of a container.
+
+ It covers the prepare settings, the plan, the
raw recording's files, the trial's lines and its alignment file, and
- the network baseline file mapped into it (when the solver uses one)."""
+ the network baseline file mapped into it (when the solver uses one).
+
+ Returns
+ -------
+ str
+ The hash.
+ """
from ..extraction.raster.baseline_map import MIN_WEIGHT
record = {
@@ -914,12 +1108,28 @@ def _prepare_hash(
return _hash(record)
-def _extraction_baseline(session, params, d, t, baseline_dir):
- """The baseline file the solver's mode needs for ``(d, t)``, or None.
+def _extraction_baseline(
+ session: SiloSession,
+ params: SiloParams,
+ d: int,
+ t: int,
+ baseline_dir: str | Path | None,
+) -> Path | None:
+ """Return the baseline file the solver's mode needs for (d, t), or None.
It must be the file the trial was localized with, when it was localized
with the network's baseline (one baseline per run, whichever folders
the stages were given).
+
+ Returns
+ -------
+ Path or None
+ The baseline file; None when the solver fits the baseline.
+
+ Raises
+ ------
+ ValueError
+ If the trial was localized with another baseline file.
"""
if params.baseline_mode == "fit":
return None
@@ -935,9 +1145,17 @@ def _extraction_baseline(session, params, d, t, baseline_dir):
def baseline_provenance(base: Path) -> dict:
- """A baseline file's identity and its network: the checkpoint's path
+ """Return a baseline file's identity and its network.
+
+ The network is the checkpoint's path
and step that slap2-f0 records, and its identity at prediction time
- from the file's record (when it was predicted here)."""
+ from the file's record (when it was predicted here).
+
+ Returns
+ -------
+ dict
+ file, network and, when the file has a record, checkpoint.
+ """
from .silo_baseline import record_path
network = {}
@@ -954,9 +1172,16 @@ def baseline_provenance(base: Path) -> dict:
return out
-def localization_baseline(session: SiloSession, d: int, t: int):
- """The network baseline trial-path ``(d, t)`` was localized with
- (:func:`baseline_provenance`), or None."""
+def localization_baseline(session: SiloSession, d: int, t: int) -> dict | None:
+ """Return the network baseline trial-path (d, t) was localized with, or None.
+
+ See :func:`baseline_provenance`.
+
+ Returns
+ -------
+ dict or None
+ The baseline's provenance; None when the localization recorded none.
+ """
v = _attr(session.localize_file(d, t), "network_baseline")
if isinstance(v, bytes):
v = v.decode()
@@ -964,13 +1189,18 @@ def localization_baseline(session: SiloSession, d: int, t: int):
def load_trial_baseline(
- session: SiloSession, params: SiloParams, trial, base: Path, d, t
-):
- """The network's baseline at a loaded trial's selected pixels.
+ session: SiloSession, params: SiloParams, trial: TrialData, base: Path, d: int, t: int
+) -> TrialBaseline:
+ """Load the network's baseline at a loaded trial's selected pixels.
:func:`~giant_python.extraction.raster.baseline_map.read_trial_baseline`,
with the checkpoint's identity and the prediction's settings added from
the file's record (when it was predicted here).
+
+ Returns
+ -------
+ TrialBaseline
+ The trial's baseline.
"""
from ..extraction.raster.baseline_map import (
apply_trial_sd_finv,
@@ -1008,14 +1238,29 @@ def load_trial_baseline(
return tb
-def trial_subproblems(plan, trial, solver_params, baseline=None) -> list:
- """The plan's subproblems on a loaded trial.
+def trial_subproblems(
+ plan: ExtractionPlan,
+ trial: TrialData,
+ solver_params: SolverParams,
+ baseline: TrialBaseline | None = None,
+) -> list:
+ """Return the plan's subproblems on a loaded trial.
With a solver mode that uses an external baseline, each gets the
- network's (``baseline``, a
+ network's (baseline, a
:class:`~giant_python.extraction.raster.baseline_map.TrialBaseline`):
the same arrays as a container of the trial gives
(:meth:`~giant_python.extraction.raster.container.Container.subproblem`).
+
+ Returns
+ -------
+ list of Subproblem
+ One subproblem per source group of the plan.
+
+ Raises
+ ------
+ ValueError
+ If the solver's baseline mode needs the network's baseline and baseline is None.
"""
from ..extraction.raster.baseline_map import subproblem_baseline
@@ -1043,12 +1288,20 @@ def trial_subproblems(plan, trial, solver_params, baseline=None) -> list:
]
-def _path_plan(session: SiloSession, params: SiloParams, plans: dict, d):
- """Path ``d``'s plan, user-ROI masks and settings hash, read and
- checked against the settings once (kept in ``plans``). The plan's
- per-trial image stacks stay in the file (``read_plan(...,
- trial_images=False)``): a trial's aligned mean image is read when the
- trial is loaded."""
+def _path_plan(session: SiloSession, params: SiloParams, plans: dict, d: int) -> tuple:
+ """Return path d's plan, user-ROI masks and settings hash.
+
+ They are read and
+ checked against the settings once (kept in plans). The plan's
+ per-trial image stacks stay in the file (read_plan(...,
+ trial_images=False)): a trial's aligned mean image is read when the
+ trial is loaded.
+
+ Returns
+ -------
+ tuple
+ The plan, the user-ROI masks and the plan file's settings hash.
+ """
from ..extraction.raster.plan import read_plan
if d not in plans:
@@ -1077,15 +1330,20 @@ def _prepare_unit(
plans: dict,
d: int,
t: int,
- baseline_dir=None,
-) -> Optional[dict]:
- """Prepare trial-path ``(d, t)``: its container, or its skip marker.
+ baseline_dir: str | Path | None = None,
+) -> dict | None:
+ """Prepare trial-path (d, t): its container, or its skip marker.
Returns
-------
dict or None
- ``unit``, ``file`` and ``seconds`` of a container written; None
+ unit, file and seconds of a container written; None
for a unit that is up to date or without data (marked skipped).
+
+ Raises
+ ------
+ ValueError
+ If loading the trial fails for a reason other than a lack of data.
"""
from ..extraction.raster.container import write_container
@@ -1094,16 +1352,12 @@ def _prepare_unit(
h = _prepare_hash(session, params, ph, d, t, base)
out = session.container_file(d, t)
skip = session.skip_file(d, t)
- if not ex.overwrite and (
- _attr(out, "settings_hash") == h or skip_hash(skip) == h
- ):
+ if not ex.overwrite and (_attr(out, "settings_hash") == h or skip_hash(skip) == h):
return None
out.parent.mkdir(parents=True, exist_ok=True)
t0 = time.perf_counter()
try:
- trial = load_trial_for(
- session, params, p, d, t, rois, ex.loader_device
- )
+ trial = load_trial_for(session, params, p, d, t, rois, ex.loader_device)
except ValueError as exc:
if NO_DATA not in str(exc):
raise
@@ -1111,11 +1365,7 @@ def _prepare_unit(
return None
if skip.exists():
skip.unlink()
- tb = (
- None
- if base is None
- else load_trial_baseline(session, params, trial, base, d, t)
- )
+ tb = None if base is None else load_trial_baseline(session, params, trial, base, d, t)
write_container(
out,
trial,
@@ -1142,9 +1392,17 @@ def _prepare_unit(
file and its identity: a worker reads each path's plan once."""
-def _prepare_job(job: dict) -> Optional[dict]:
- """Prepare one trial-path in a pool worker (:func:`prepare` with
- ``prepare_workers``): :func:`_prepare_unit` with the worker's plans."""
+def _prepare_job(job: dict) -> dict | None:
+ """Prepare one trial-path in a pool worker.
+
+ This is :func:`prepare` with
+ prepare_workers: :func:`_prepare_unit` with the worker's plans.
+
+ Returns
+ -------
+ dict or None
+ The result of :func:`_prepare_unit`.
+ """
session, d, t = job["session"], *job["unit"]
f = session.plan_file(d)
key = json.dumps([str(f), _file_id(f)], sort_keys=True)
@@ -1161,15 +1419,36 @@ def _prepare_job(job: dict) -> Optional[dict]:
def prepare_threads(workers: int) -> int:
- """Threads of each of ``workers`` prepare processes: the cores shared
+ """Return the threads of each of workers prepare processes.
+
+ The cores are shared
out, at most 4 (a loading trial uses few threads well) and at least
- 1."""
+ 1.
+
+ Returns
+ -------
+ int
+ The number of threads.
+ """
return max(1, min(4, (os.cpu_count() or 1) // max(1, workers)))
-def _prepare_pending(session, params, ex, units, baseline_dir) -> list:
- """The selected valid ``units`` whose container or skip marker is not
- up to date, after checking each path's plan against its localizations."""
+def _prepare_pending(
+ session: SiloSession,
+ params: SiloParams,
+ ex: SiloExecution,
+ units: Iterable[tuple[int, int]],
+ baseline_dir: str | Path | None,
+) -> list:
+ """Return the selected valid units whose container or skip marker is not up to date.
+
+ This is after checking each path's plan against its localizations.
+
+ Returns
+ -------
+ list of tuple of int
+ The (path, trial) pairs still to prepare.
+ """
todo, hashes = [], {}
for d, t in units:
if d not in hashes:
@@ -1188,19 +1467,19 @@ def _prepare_pending(session, params, ex, units, baseline_dir) -> list:
def prepare(
session: SiloSession,
params: SiloParams,
- execution: Optional[SiloExecution] = None,
- units=None,
- baseline_dir=None,
+ execution: SiloExecution | None = None,
+ units: Iterable[tuple[int, int]] | None = None,
+ baseline_dir: str | Path | None = None,
) -> list:
- """Stage ``prepare``: a container per extracted trial-path.
+ """Stage prepare: a container per extracted trial-path.
The valid trials of each planned path are loaded at the plan's
selected pixels (200 Hz, from the raw files) and written with the
- plan's subproblems, and, when the solver's ``baseline_mode`` uses it,
+ plan's subproblems, and, when the solver's baseline_mode uses it,
the network's baseline at those pixels. A trial in which no selected
pixel has data gets a ``*.skip.json`` marker instead.
- With ``execution.prepare_workers`` above 1 the trials are prepared in
+ With execution.prepare_workers above 1 the trials are prepared in
that many processes at once (each reads the path's plan and the
recording's layout once, then loads one trial at a time with
:func:`prepare_threads` threads); the containers are the same.
@@ -1208,15 +1487,15 @@ def prepare(
Parameters
----------
units : iterable of (int, int), optional
- Zero-based ``(path, trial)`` pairs (default: all valid trials).
+ Zero-based (path, trial) pairs (default: all valid trials).
baseline_dir : str or Path, optional
Folder of the network baseline files (default: the session's
- ``baselines`` folder).
+ baselines folder).
Returns
-------
list of dict
- Per unit: ``unit``, ``file`` and ``seconds``.
+ Per unit: unit, file and seconds.
"""
ex = execution or SiloExecution()
units = _valid_units(session, units)
@@ -1238,10 +1517,27 @@ def prepare(
return done
-def _prepare_parallel(session, params, ex, todo: list, baseline_dir) -> list:
- """:func:`prepare` of the trial-paths ``todo`` in
- ``ex.prepare_workers`` processes; the first failure is raised once the
- pool has stopped."""
+def _prepare_parallel(
+ session: SiloSession,
+ params: SiloParams,
+ ex: SiloExecution,
+ todo: list,
+ baseline_dir: str | Path | None,
+) -> list:
+ """Run :func:`prepare` of the trial-paths todo in ex.prepare_workers processes.
+
+ The first failure is raised once the pool has stopped.
+
+ Returns
+ -------
+ list of dict
+ The containers written, as :func:`prepare` returns them.
+
+ Raises
+ ------
+ pool_failure
+ The :class:`RuntimeError` it returns, when a worker process died.
+ """
workers = min(ex.prepare_workers, len(todo))
pool = None
try:
@@ -1269,9 +1565,14 @@ def _prepare_parallel(session, params, ex, todo: list, baseline_dir) -> list:
return [m for m in made if m is not None]
-def _mark_skipped(session, d, t, reason, prepare_hash, plan_hash) -> None:
- """Mark a trial-path as without data; remove its earlier container and
- results files, so that no stage uses them."""
+def _mark_skipped(
+ session: SiloSession, d: int, t: int, reason: str, prepare_hash: str, plan_hash: str
+) -> None:
+ """Mark a trial-path as without data.
+
+ Remove its earlier container and
+ results files, so that no stage uses them.
+ """
write_skip(session.skip_file(d, t), reason, prepare_hash, plan_hash)
stale = [session.container_file(d, t)]
stem = f"path{d + 1}_trial{t + 1:04d}"
@@ -1287,10 +1588,22 @@ def _mark_skipped(session, d, t, reason, prepare_hash, plan_hash) -> None:
def _container_params(
- params: SiloParams, plan_hash: str, d: int, t: int, baseline=None
+ params: SiloParams,
+ plan_hash: str,
+ d: int,
+ t: int,
+ baseline: TrialBaseline | None = None,
) -> dict:
- """What a container records of its settings (with the network: the
- baseline source, and the identity of the baseline mapped into it)."""
+ """Return what a container records of its settings.
+
+ With the network: the
+ baseline source, and the identity of the baseline mapped into it.
+
+ Returns
+ -------
+ dict
+ The settings record.
+ """
out = {
"prepare": params.stage_settings("prepare"),
"plan": plan_hash,
@@ -1307,8 +1620,14 @@ def _container_params(
return out
-def _valid_units(session: SiloSession, units=None) -> list:
- """Planned paths' valid trials ``(d, t)`` (of ``units`` or all)."""
+def _valid_units(session: SiloSession, units: Iterable[tuple[int, int]] | None = None) -> list:
+ """Return the planned paths' valid trials (d, t) (of units or all).
+
+ Returns
+ -------
+ list of tuple of int
+ The (path, trial) pairs.
+ """
wanted = None if units is None else {(int(d), int(t)) for d, t in units}
out = []
for d in range(session.n_paths):
@@ -1339,95 +1658,118 @@ class _Pending:
attrs: dict
out: Path
submitted: float = 0.0
- done: Optional[_Done] = None
+ done: _Done | None = None
class _Done:
"""Completion times of a trial's subproblems, from done callbacks."""
def __init__(self, n: int = 1) -> None:
- """Expect ``n`` completions (set by :func:`_submit`)."""
+ """Expect n completions (set by :func:`_submit`)."""
self.n, self.times = n, []
self.cond = threading.Condition()
- def add(self, _future=None) -> None:
+ def add(self, _future: cf.Future | None = None) -> None:
"""Record one completion now (a done callback)."""
with self.cond:
self.times.append(time.perf_counter())
self.cond.notify_all()
- def last(self, timeout: float = 60.0):
- """The last completion time once all ``n`` are in (a future's
- result can be read before its callbacks have run), or None."""
+ def last(self, timeout: float = 60.0) -> float | None:
+ """Return the last completion time once all n are in, or None.
+
+ A future's result can be read before its callbacks have run.
+
+ Returns
+ -------
+ float or None
+ The last completion time; None when none was recorded in time.
+ """
with self.cond:
self.cond.wait_for(lambda: len(self.times) >= self.n, timeout)
return max(self.times) if self.times else None
def _finish(p: _Pending) -> float:
- """Wait for a trial's subproblems and write its results file."""
+ """Wait for a trial's subproblems and write its results file.
+
+ Returns
+ -------
+ float
+ Seconds the wait and the write took.
+ """
from ..extraction.raster.results import write_results
t0 = time.perf_counter()
results = p.results or [f.result() for f in p.futures]
- solved = {
- k: (pix, src, r)
- for k, ((pix, src), r) in enumerate(zip(p.placements, results))
- }
+ solved = {k: (pix, src, r) for k, ((pix, src), r) in enumerate(zip(p.placements, results))}
write_results(p.out, p.record, solved, p.attrs)
return time.perf_counter() - t0
@dataclass
class _ContainerView:
- """What :func:`~.silo_solve.results_attrs` reads of a container, from a
- loaded trial."""
+ """Describe what :func:`~.silo_solve.results_attrs` reads of a container.
+
+ This is from a loaded trial.
+ """
trial: object
plan: object
d: int
t: int
plan_hash: str = ""
- baseline: Optional[dict] = None
+ baseline: dict | None = None
@property
- def pixel_rc(self):
+ def pixel_rc(self) -> np.ndarray:
"""The selected pixels."""
return self.trial.pixel_rc
@property
- def sources_rc(self):
+ def sources_rc(self) -> np.ndarray:
"""The path's sources."""
return np.column_stack([self.plan.source_rows, self.plan.source_cols])
@property
- def photon_scale(self):
+ def photon_scale(self) -> float:
"""Counts per unit of the data."""
return self.trial.photon_scale
@property
- def source(self):
+ def source(self) -> dict:
"""Path and trial, one-based."""
return {"path": self.d + 1, "trial": self.t + 1}
@property
- def params(self):
- """What the container would record: its plan's hash and the
- baseline's identity."""
+ def params(self) -> dict:
+ """What the container would record: its plan's hash and the baseline's identity."""
out = {"plan": self.plan_hash}
if self.baseline is not None:
out["baseline"] = self.baseline
return out
-def _submit(subs, sp, options, pool, done: Optional[_Done] = None):
- """Solve a trial's subproblems: futures from the pool (largest first),
- or results solved here.
+def _submit(
+ subs: Sequence[Subproblem],
+ sp: SolverParams,
+ options: SolverOptions,
+ pool: cf.ProcessPoolExecutor | None,
+ done: _Done | None = None,
+) -> tuple[list, list]:
+ """Solve a trial's subproblems: futures from the pool (largest first), or results solved here.
- ``done`` gets each future's completion time (its done callback is
+ done gets each future's completion time (its done callback is
attached as soon as the future exists, so a subproblem solved while the
rest are still submitted keeps its own time), or the time the solve
here returned.
+
+ Returns
+ -------
+ futures : list
+ The futures of the subproblems, in their order; empty when they were solved here.
+ results : list
+ The results solved here; empty when the subproblems went to the pool.
"""
from ..extraction.raster.solver import solve_subproblems
from .silo_solve import _solve_one, effective_batch
@@ -1454,9 +1796,18 @@ def _submit(subs, sp, options, pool, done: Optional[_Done] = None):
def _save_container(
- folder, session, params, plan, ph, chash, trial, d, t, baseline=None
-):
- """Write a loaded trial's container (``--save-subproblems``)."""
+ folder: str | Path,
+ session: SiloSession,
+ params: SiloParams,
+ plan: ExtractionPlan,
+ ph: str,
+ chash: str,
+ trial: TrialData,
+ d: int,
+ t: int,
+ baseline: TrialBaseline | None = None,
+) -> None:
+ """Write a loaded trial's container (--save-subproblems)."""
from ..extraction.raster.container import write_container
folder = Path(folder)
@@ -1477,10 +1828,17 @@ def _save_container(
f.attrs["settings_hash"] = chash
-def _held_bytes(subs, record) -> int:
- """Bytes of the arrays a loaded trial keeps until its results are
- written: its subproblems' data, variance multipliers and baselines,
- and its traces."""
+def _held_bytes(subs: Iterable[Subproblem], record: TrialRecord) -> int:
+ """Return the bytes of the arrays a loaded trial keeps until its results are written.
+
+ These are its subproblems' data, variance multipliers and baselines,
+ and its traces.
+
+ Returns
+ -------
+ int
+ The number of bytes.
+ """
total = 0
for s in subs:
for a in (s.y, s.finv, s.baseline):
@@ -1493,12 +1851,14 @@ def _held_bytes(subs, record) -> int:
@dataclass
class _Unit:
- """A trial-path the streaming driver extracts: where its results go
- and the hashes they get."""
+ """Describe a trial-path the streaming driver extracts.
+
+ It holds where its results go and the hashes they get.
+ """
d: int
t: int
- base: Optional[Path]
+ base: Path | None
chash: str
rhash: str
out: Path
@@ -1506,21 +1866,28 @@ class _Unit:
lines: float = 1.0
-def _loaded(units, load, execution: SiloExecution):
- """``(unit, load(unit))`` in the units' order.
+def _loaded(
+ units: Iterable[_Unit], load: Callable[[_Unit], dict], execution: SiloExecution
+) -> Iterator[tuple[_Unit, dict]]:
+ """Yield (unit, load(unit)) in the units' order.
- ``units`` is an iterable, taken from only when a unit is about to be
+ units is an iterable, taken from only when a unit is about to be
loaded (a generator can check each unit then). With
- ``execution.load_workers`` 1 each unit is taken and loaded when the
+ execution.load_workers 1 each unit is taken and loaded when the
caller asks for it (after it has handed on the previous one). With
more, later units are loaded ahead in threads of this process, at most
- ``load_workers`` at a time and, with ``load_memory_gb``, only while the
+ load_workers at a time and, with load_memory_gb, only while the
data of the trials loaded and not yet handed on is estimated below it
(from the bytes per line of the loads that reported their bytes,
- ``nbytes``, so far; until one has, one load at a time). The loads are
+ nbytes, so far; until one has, one load at a time). The loads are
the same either way: one process, the same threads per operation. An
error raised while taking a unit (its check) reaches the caller after
the units before it, as with one worker.
+
+ Yields
+ ------
+ tuple of (_Unit, dict)
+ A unit and what its load returned.
"""
if execution.load_workers <= 1:
for u in units:
@@ -1535,10 +1902,18 @@ def _loaded(units, load, execution: SiloExecution):
)
-def _fits(queued: list, unit: _Unit, per_line: list, limit) -> bool:
- """Whether ``unit`` may load while the ``queued`` units wait: always
+def _fits(queued: list[_Unit], unit: _Unit, per_line: list[float], limit: float | None) -> bool:
+ """Return whether unit may load while the queued units wait.
+
+ Always
when none waits or without a limit (bytes); otherwise only once a load
- has given a bytes-per-line estimate and the estimate fits."""
+ has given a bytes-per-line estimate and the estimate fits.
+
+ Returns
+ -------
+ bool
+ True when the unit may load now.
+ """
if not queued or limit is None:
return True
if not per_line:
@@ -1547,18 +1922,43 @@ def _fits(queued: list, unit: _Unit, per_line: list, limit) -> bool:
return max(per_line) * lines <= limit
-def _take(source) -> tuple:
- """``(unit, None)`` for the source's next unit, ``(None, None)`` at its
- end, or ``(None, error)`` if taking it raised (its check failed)."""
+def _take(source: Iterator[_Unit]) -> tuple[_Unit | None, Exception | None]:
+ """Return (unit, None) for the source's next unit.
+
+ (None, None) at its
+ end, or (None, error) if taking it raised (its check failed).
+
+ Returns
+ -------
+ tuple of (_Unit or None, Exception or None)
+ The next unit and the error raised in taking it, as described above.
+ """
try:
return next(source, None), None
except Exception as exc: # handed on after the earlier units
return None, exc
-def _loaded_ahead(source, load, workers: int, limit):
- """:func:`_loaded` with ``workers`` loader threads and a memory
- ``limit`` in bytes (or None)."""
+def _loaded_ahead(
+ source: Iterator[_Unit],
+ load: Callable[[_Unit], dict],
+ workers: int,
+ limit: float | None,
+) -> Iterator[tuple[_Unit, dict]]:
+ """Yield :func:`_loaded` with workers loader threads and a memory limit.
+
+ The limit is in bytes (or None).
+
+ Yields
+ ------
+ tuple of (_Unit, dict)
+ A unit and what its load returned.
+
+ Raises
+ ------
+ Exception
+ The error raised in taking a unit, once the loads before it are handed on.
+ """ # noqa: DOC502
from collections import deque
from concurrent.futures import ThreadPoolExecutor
@@ -1572,9 +1972,7 @@ def _loaded_ahead(source, load, workers: int, limit):
while len(queue) < workers:
if taken is None and error is None:
taken, error = _take(source)
- if taken is None or not _fits(
- [v for v, _ in queue], taken, per_line, limit
- ):
+ if taken is None or not _fits([v for v, _ in queue], taken, per_line, limit):
break
queue.append((taken, pool.submit(load, taken)))
taken = None
@@ -1593,26 +1991,26 @@ def _loaded_ahead(source, load, workers: int, limit):
pool.shutdown(wait=True)
-def stream( # noqa: C901
+def stream(
session: SiloSession,
params: SiloParams,
execution: SiloExecution,
- paths: Optional[Iterable[int]] = None,
- pool=None,
- save_subproblems: Optional[Path] = None,
- clock0: Optional[float] = None,
- baseline_dir=None,
+ paths: Iterable[int] | None = None,
+ pool: cf.ProcessPoolExecutor | None = None,
+ save_subproblems: Path | None = None,
+ clock0: float | None = None,
+ baseline_dir: str | Path | None = None,
) -> list:
"""Load the paths' valid trials one ahead of the solver.
- As MATLAB's ``processAllTrials_Async``: while one trial's subproblems
- are solved in ``pool``, the next trial is loaded here (also across
+ As MATLAB's processAllTrials_Async: while one trial's subproblems
+ are solved in pool, the next trial is loaded here (also across
paths: a path's first trial is loaded while the previous path's last
trial is solved). Each trial's results go to the results file that the
- staged run writes (``results/path_trial.h5``, with the same
+ staged run writes (results/path_trial.h5, with the same
settings hash), so that :func:`~.silo_collect.collect` makes the
summaries either way. Containers are written only to
- ``save_subproblems``, if given.
+ save_subproblems, if given.
Parameters
----------
@@ -1621,24 +2019,24 @@ def stream( # noqa: C901
that yields each path once it is planned (default: every planned
path).
clock0 : float, optional
- ``time.perf_counter()`` that ``submitted`` and ``solved`` count
+ time.perf_counter() that submitted and solved count
from (default: when this starts).
baseline_dir : str or Path, optional
Folder of the network baseline files, when the solver's mode uses
- them (default: the session's ``baselines`` folder).
+ them (default: the session's baselines folder).
Returns
-------
list of dict
- Per trial: ``unit``, ``load`` and ``wait`` seconds (the wait is
- for the previous trial's solve), ``load_phases`` (the loader's
- wall seconds per phase: ``setup``, ``frames``, ``roi_svd``,
- ``finish``, and ``layout``, the part of ``setup`` spent reading the
- recording's layout), ``submitted`` and ``solved``
- (seconds since ``clock0`` when its subproblems went to the solver
+ Per trial: unit, load and wait seconds (the wait is
+ for the previous trial's solve), load_phases (the loader's
+ wall seconds per phase: setup, frames, roi_svd,
+ finish, and layout, the part of setup spent reading the
+ recording's layout), submitted and solved
+ (seconds since clock0 when its subproblems went to the solver
and when the last was solved; a trial solved in this process, with
one solver process or batches, is solved when that returns), or
- ``skipped``.
+ skipped.
"""
clock0 = time.perf_counter() if clock0 is None else clock0
solve_times = {}
@@ -1649,7 +2047,7 @@ def stream( # noqa: C901
sp = params.solver_params()
options = execution.solver_options()
report = []
- pending: Optional[_Pending] = None
+ pending: _Pending | None = None
if paths is None:
paths = range(session.n_paths)
try:
@@ -1672,33 +2070,47 @@ def stream( # noqa: C901
placements = [(g.pixels, g.sources) for g in plan.groups]
n_sub = len(plan.groups)
- def units(d=d, ph=ph, n_sub=n_sub):
- """The path's trial-paths to extract, each checked (baseline,
+ def units(d: int = d, ph: str = ph, n_sub: int = n_sub) -> Iterator[_Unit]:
+ """Yield the path's trial-paths to extract.
+
+ Each is checked (baseline,
hashes) when the loader takes it, so that a later trial's
- missing file does not stop the earlier ones."""
+ missing file does not stop the earlier ones.
+
+ Yields
+ ------
+ _Unit
+ A trial-path to extract, with its hashes and file names.
+ """
for t in (int(x) for x in plan.valid_trials):
- base = _extraction_baseline(
- session, params, d, t, baseline_dir
- )
+ base = _extraction_baseline(session, params, d, t, baseline_dir)
chash = _prepare_hash(session, params, ph, d, t, base)
rhash = solve_hash(params, options, chash, (0, n_sub))
out = session.results_file(d, t)
skip = session.skip_file(d, t)
if not execution.overwrite and (
- _attr(out, "settings_hash") == rhash
- or skip_hash(skip) == chash
+ _attr(out, "settings_hash") == rhash or skip_hash(skip) == chash
):
- report.append(
- {"unit": (d, t), "skipped": "up to date"}
- )
+ report.append({"unit": (d, t), "skipped": "up to date"})
continue
lines = session.last_line[d, t] - session.first_line[d, t]
- yield _Unit(
- d, t, base, chash, rhash, out, skip, float(lines + 1)
- )
+ yield _Unit(d, t, base, chash, rhash, out, skip, float(lines + 1))
def load(u: _Unit) -> dict:
- """Load one trial and make its subproblems (a loader task)."""
+ """Load one trial and make its subproblems (a loader task).
+
+ Returns
+ -------
+ dict
+ skipped (the reason) for a trial without data; otherwise load
+ seconds, load_phases, record, placements, subs,
+ attrs and, when it has subproblems, nbytes.
+
+ Raises
+ ------
+ ValueError
+ If loading the trial fails for a reason other than a lack of data.
+ """
t0 = time.perf_counter()
try:
trial = load_trial_for(
@@ -1720,14 +2132,10 @@ def load(u: _Unit) -> dict:
tb = (
None
if u.base is None
- else load_trial_baseline(
- session, params, trial, u.base, u.d, u.t
- )
+ else load_trial_baseline(session, params, trial, u.base, u.d, u.t)
)
load_s = time.perf_counter() - t0
- phases = {
- k: round(float(v), 3) for k, v in trial.timings.items()
- }
+ phases = {k: round(float(v), 3) for k, v in trial.timings.items()}
record = TrialRecord.from_trial(trial)
if save_subproblems is not None:
_save_container(
@@ -1787,9 +2195,7 @@ def load(u: _Unit) -> dict:
for u, item in _loaded(units(), load, execution):
if "skipped" in item:
- report.append(
- {"unit": (u.d, u.t), "skipped": item["skipped"]}
- )
+ report.append({"unit": (u.d, u.t), "skipped": item["skipped"]})
continue
subs = item.pop("subs")
submitted = time.perf_counter() - clock0
@@ -1798,9 +2204,7 @@ def load(u: _Unit) -> dict:
del subs
if pending is not None:
wait_s = _finish(pending)
- solve_times[(pending.d, pending.t)] = _solve_span(
- pending, clock0
- )
+ solve_times[(pending.d, pending.t)] = _solve_span(pending, clock0)
else:
wait_s = 0.0
u.out.parent.mkdir(parents=True, exist_ok=True)
@@ -1817,14 +2221,12 @@ def load(u: _Unit) -> dict:
done,
)
load_s = item["load"]
- report.append(
- {
- "unit": (u.d, u.t),
- "load": load_s,
- "load_phases": item["load_phases"],
- "wait": wait_s,
- }
- )
+ report.append({
+ "unit": (u.d, u.t),
+ "load": load_s,
+ "load_phases": item["load_phases"],
+ "wait": wait_s,
+ })
if execution.verbose:
print(
f"SILo path {u.d + 1} trial {u.t + 1}: loaded in "
@@ -1840,9 +2242,7 @@ def load(u: _Unit) -> dict:
_finish(pending)
raise
if pending is not None:
- report.append(
- {"unit": (pending.d, pending.t), "wait": _finish(pending)}
- )
+ report.append({"unit": (pending.d, pending.t), "wait": _finish(pending)})
solve_times[(pending.d, pending.t)] = _solve_span(pending, clock0)
for entry in report:
if "load" in entry and entry["unit"] in solve_times:
@@ -1850,17 +2250,37 @@ def load(u: _Unit) -> dict:
return report
-def plan_subproblems(path) -> int:
- """The number of subproblems (source groups) of a plan file, read
- without the plan."""
+def plan_subproblems(path: str | Path) -> int:
+ """Return the number of subproblems (source groups) of a plan file.
+
+ The plan is not read.
+
+ Returns
+ -------
+ int
+ The number of subproblems.
+ """
with h5py.File(path, "r") as f:
return int(f["groups/origin"].shape[0])
-def _local_units(session, params, execution, paths, baseline_dir, report):
- """The trial-paths the local staged run still has to extract, as
- ``(d, t, container hash)`` in path and trial order; those up to date
+def _local_units(
+ session: SiloSession,
+ params: SiloParams,
+ execution: SiloExecution,
+ paths: Iterable[int],
+ baseline_dir: str | Path | None,
+ report: list,
+) -> list:
+ """Return the trial-paths the local staged run still has to extract.
+
+ They are (d, t, container hash) in path and trial order; those up to date
are reported as skipped.
+
+ Returns
+ -------
+ list of tuple
+ (d, t, container hash) of each trial-path to extract.
"""
from .silo_solve import solve_hash
@@ -1879,9 +2299,7 @@ def _local_units(session, params, execution, paths, baseline_dir, report):
)
ph = _attr(pf, "settings_hash")
n_sub = plan_subproblems(pf)
- for _, t in _valid_units(
- session, [(d, t) for t in range(session.n_trials)]
- ):
+ for _, t in _valid_units(session, [(d, t) for t in range(session.n_trials)]):
base = _extraction_baseline(session, params, d, t, baseline_dir)
chash = _prepare_hash(session, params, ph, d, t, base)
rhash = solve_hash(params, options, chash, (0, n_sub))
@@ -1895,23 +2313,24 @@ def _local_units(session, params, execution, paths, baseline_dir, report):
return units
-def stream_local( # noqa: C901
+def stream_local(
session: SiloSession,
params: SiloParams,
execution: SiloExecution,
- paths: Optional[Iterable[int]] = None,
- save_subproblems: Optional[Path] = None,
- clock0: Optional[float] = None,
- baseline_dir=None,
+ paths: Iterable[int] | None = None,
+ save_subproblems: Path | None = None,
+ clock0: float | None = None,
+ baseline_dir: str | Path | None = None,
) -> list:
- """Prepare and solve the paths' valid trials in processes of this
- machine: the staged run's prepare and solve, started and fed here.
+ """Prepare and solve the paths' valid trials in processes of this machine.
- ``execution.local_workers`` gives the two pools. The prepare
+ This is the staged run's prepare and solve, started and fed here.
+
+ execution.local_workers gives the two pools. The prepare
processes each load one trial at a time and write its container
(:func:`prepare`'s work, :func:`prepare_threads` threads each); as a
container arrives, a solver process reads it, solves its subproblems
- one after another with ``solver_threads`` threads and writes the
+ one after another with solver_threads threads and writes the
trial's results file
(:func:`~giant_python.pipeline.silo_solve.solve_trials`' work).
Loading and solving therefore overlap, and neither waits on one
@@ -1920,7 +2339,7 @@ def stream_local( # noqa: C901
so :func:`~.silo_collect.collect` makes the same summaries.
A container is removed once its results are written (or moved to
- ``save_subproblems``, if given). At most ``prepare + 2 x solver``
+ save_subproblems, if given). At most prepare + 2 x solver
processes' worth of trial-paths are between the start of their
preparation and their results, so the containers waiting on disk and
the prepare processes' lead over the solver stay bounded.
@@ -1934,7 +2353,7 @@ def stream_local( # noqa: C901
save_subproblems : str or Path, optional
Keep the containers in this folder.
clock0 : float, optional
- ``time.perf_counter()`` that ``submitted`` and ``solved`` count
+ time.perf_counter() that submitted and solved count
from (default: when this starts).
baseline_dir : str or Path, optional
Folder of the network baseline files.
@@ -1942,11 +2361,18 @@ def stream_local( # noqa: C901
Returns
-------
list of dict
- Per trial: ``unit``; ``prepare`` and ``solve`` (seconds of its
+ Per trial: unit; prepare and solve (seconds of its
prepare and solve tasks, None for a task that found its file up
- to date), ``submitted`` and ``solved`` (seconds since ``clock0``
+ to date), submitted and solved (seconds since clock0
when its container went to the solver and when its results were
- written); or ``skipped``.
+ written); or skipped.
+
+ Raises
+ ------
+ ValueError
+ If save_subproblems is one of the stages' folders.
+ pool_failure
+ The :class:`RuntimeError` it returns, when a worker process died.
"""
import queue
@@ -1954,9 +2380,7 @@ def stream_local( # noqa: C901
clock0 = time.perf_counter() if clock0 is None else clock0
options = execution.solver_options()
- archive = (
- None if save_subproblems is None else Path(save_subproblems).resolve()
- )
+ archive = None if save_subproblems is None else Path(save_subproblems).resolve()
if archive is not None:
# a container has the name of its trial's results and localization
# files: moved into one of the stages' folders it would replace
@@ -1969,16 +2393,11 @@ def stream_local( # noqa: C901
session.jobs_dir,
):
if archive == folder.resolve():
- raise ValueError(
- "--save-subproblems cannot use the "
- f"{folder.name} directory"
- )
+ raise ValueError(f"--save-subproblems cannot use the {folder.name} directory")
report: list = []
if paths is None:
paths = range(session.n_paths)
- todo = _local_units(
- session, params, execution, list(paths), baseline_dir, report
- )
+ todo = _local_units(session, params, execution, list(paths), baseline_dir, report)
if not todo:
return report
n_prep, n_solve = (min(n, len(todo)) for n in execution.local_workers)
@@ -1991,11 +2410,9 @@ def stream_local( # noqa: C901
prep_pool = solve_pool = None
try:
prep_pool = make_pool(n_prep, prepare_threads(n_prep))
- solve_pool = trial_pool(
- replace(execution, trial_workers=n_solve), n_solve
- )
+ solve_pool = trial_pool(replace(execution, trial_workers=n_solve), n_solve)
- def feed():
+ def feed() -> None:
"""Start preparing trials while the window has room."""
nonlocal in_flight
while waiting and in_flight < window:
@@ -2009,9 +2426,7 @@ def feed():
}
preparing.add((d, t))
fut = prep_pool.submit(_prepare_job, job)
- fut.add_done_callback(
- lambda f, u=(d, t, chash): events.put(("prepared", u, f))
- )
+ fut.add_done_callback(lambda f, u=(d, t, chash): events.put(("prepared", u, f)))
in_flight += 1
feed()
@@ -2042,9 +2457,7 @@ def feed():
"remove": archive is None,
}
sfut = solve_pool.submit(_solve_container_job, job)
- sfut.add_done_callback(
- lambda f, u=(d, t, chash): events.put(("solved", u, f))
- )
+ sfut.add_done_callback(lambda f, u=(d, t, chash): events.put(("solved", u, f)))
continue
in_flight -= 1
done = fut.result()
@@ -2062,14 +2475,9 @@ def feed():
feed()
except BrokenProcessPool as exc:
units = "; ".join(
- f"path {d + 1}, trial {t + 1}"
- for d, t in sorted(preparing | entries.keys())
- )
- affected = (
- f"trial-paths in flight: {units}"
- if units
- else "starting a trial pool"
+ f"path {d + 1}, trial {t + 1}" for d, t in sorted(preparing | entries.keys())
)
+ affected = f"trial-paths in flight: {units}" if units else "starting a trial pool"
raise pool_failure(affected) from exc
finally:
for pool in (prep_pool, solve_pool):
@@ -2079,37 +2487,47 @@ def feed():
def _solve_span(p: _Pending, clock0: float) -> tuple:
- """When a finished trial went to the solver and when its last
- subproblem was solved, in seconds since ``clock0``."""
+ """Return when a finished trial went to the solver and when its last subproblem was solved.
+
+ Both are in seconds since clock0.
+
+ Returns
+ -------
+ tuple of float
+ The seconds at which the trial was submitted and at which its last subproblem was solved.
+ """
end = p.done.last() if p.done is not None else None
if end is None:
end = time.perf_counter()
return p.submitted, end - clock0
-def _ready_paths( # noqa: C901
- session,
- params,
- ex,
- seeds,
- baseline_dir,
- timer,
- peak_pool,
- peak_futures,
- pools,
-):
+def _ready_paths(
+ session: SiloSession,
+ params: SiloParams,
+ ex: SiloExecution,
+ seeds: list | None,
+ baseline_dir: str | Path | None,
+ timer: dict,
+ peak_pool: cf.ProcessPoolExecutor | None,
+ peak_futures: list,
+ pools: list,
+) -> Iterator[int]:
"""Localize and plan the paths; yield each path once it is planned.
With several workers a path's plan starts as soon as its own trials
- are localized, and its per-trial peak fits go to ``peak_pool``
- (``peak_futures``) then; paths are yielded in the order their plans
+ are localized, and its per-trial peak fits go to peak_pool
+ (peak_futures) then; paths are yielded in the order their plans
finish, so the first planned path is extracted while the other is
still planned. With one worker everything runs here, in order.
+
+ Yields
+ ------
+ int
+ A zero-based path whose plan is written.
"""
t0 = time.perf_counter()
- jobs = localize_jobs(
- session, params, None, baseline_dir, False, ex.overwrite
- )
+ jobs = localize_jobs(session, params, None, baseline_dir, False, ex.overwrite)
timer["localize_units"] = len(jobs)
cpus = os.cpu_count() or 1
paths = [d for d in range(session.n_paths) if session.keep[d].any()]
@@ -2126,9 +2544,7 @@ def _ready_paths( # noqa: C901
return
loc_pool = None
if jobs:
- loc_pool = make_pool(
- min(ex.workers, len(jobs)), max(1, cpus // ex.workers)
- )
+ loc_pool = make_pool(min(ex.workers, len(jobs)), max(1, cpus // ex.workers))
pools.append(loc_pool)
plan_pool = make_pool(
max(1, len(paths)),
@@ -2144,8 +2560,8 @@ def _ready_paths( # noqa: C901
planned = {}
timer["plan_paths"] = {}
- def start(d):
- """Plan path ``d`` and fit its trials' peaks in the background."""
+ def start(d: int) -> None:
+ """Plan path d and fit its trials' peaks in the background."""
planned[
plan_pool.submit(
_plan_job,
@@ -2155,9 +2571,7 @@ def start(d):
"d": d,
"seeds": seeds_of(d),
"overwrite": ex.overwrite,
- "refine_workers": refine_workers(
- cpus // max(1, len(paths)), ex.workers
- ),
+ "refine_workers": refine_workers(cpus // max(1, len(paths)), ex.workers),
},
)
] = d
@@ -2188,56 +2602,56 @@ def start(d):
def run_silo(
- table,
- params=None,
- execution=None,
+ table: str | Path,
+ params: SiloParams | dict | None = None,
+ execution: SiloExecution | dict | None = None,
*,
- moco_dir=None,
- data_dir=None,
- out_dir=None,
- work_dir=None,
- annotations=None,
- seeds_file=None,
- baseline_dir=None,
- save_subproblems=None,
+ moco_dir: str | Path | None = None,
+ data_dir: str | Path | None = None,
+ out_dir: str | Path | None = None,
+ work_dir: str | Path | None = None,
+ annotations: str | Path | None = None,
+ seeds_file: str | Path | None = None,
+ baseline_dir: str | Path | None = None,
+ save_subproblems: str | Path | None = None,
update_table: bool = True,
- peak_workers: Optional[int] = None,
- f0_ckpt=None,
+ peak_workers: int | None = None,
+ f0_ckpt: str | Path | None = None,
f0_device: str = "cuda",
- f0_command: Optional[str] = None,
- f0_out_frames: Optional[int] = None,
+ f0_command: str | None = None,
+ f0_out_frames: int | None = None,
) -> dict:
- """SILo on one machine (``giant silo``), streaming as MATLAB's.
+ """SILo on one machine (giant silo), streaming as MATLAB's.
- 0. With ``f0_ckpt``: predict the network's baselines of the trial-paths
- that have none (``slap2-f0 predict-registered``, one process).
- 1. Localize every kept trial-path (``workers`` processes).
+ 0. With f0_ckpt: predict the network's baselines of the trial-paths
+ that have none (slap2-f0 predict-registered, one process).
+ 1. Localize every kept trial-path (workers processes).
2. Plan each path (one process per path) as soon as its trials are
localized; its per-trial peak fits, which only the per-trial
- summary uses, start then in the background (``peak_workers``
+ summary uses, start then in the background (peak_workers
processes, one thread each).
3. Per path, in the order the plans finish, load each valid trial at
the plan's selected pixels while the previous trial's subproblems
- are solved (``solver_workers`` processes of ``solver_threads``
+ are solved (solver_workers processes of solver_threads
threads); write each trial's results file. With
- ``execution.prepare_workers`` or ``trial_workers`` above 0, once
+ execution.prepare_workers or trial_workers above 0, once
every path is planned: prepare the trials in several processes and
solve each whole in one of several solver processes
(:func:`stream_local`); the results files are the same.
- 4. Collect: kinetics test, ``experiment_summary.h5``,
- ``per_trial_summary.h5``, the trial table's fields.
+ 4. Collect: kinetics test, experiment_summary.h5,
+ per_trial_summary.h5, the trial table's fields.
Units whose outputs exist and were made with the same settings are
- kept (unless ``execution.overwrite``).
+ kept (unless execution.overwrite).
Parameters
----------
table : str or Path
- ``trial_table.h5`` (or its folder).
+ trial_table.h5 (or its folder).
params : SiloParams or dict, optional
Scientific settings (default: MATLAB's SILo for SLAP2). Given as a
- dict or None, ``baseline_source`` defaults to 'network' when
- ``baseline_dir`` or ``f0_ckpt`` is given (moving median otherwise).
+ dict or None, baseline_source defaults to 'network' when
+ baseline_dir or f0_ckpt is given (moving median otherwise).
execution : SiloExecution or dict, optional
How to run.
moco_dir, data_dir, out_dir, work_dir, annotations : optional
@@ -2247,21 +2661,21 @@ def run_silo(
(:func:`~giant_python.extraction.raster.stage_files.read_seeds`).
baseline_dir : str or Path, optional
Folder of the network's baselines (default
- ``/baselines``).
+ /baselines).
save_subproblems : str or Path, optional
Also write each trial-path's container to this folder.
update_table : bool
- Write the trial table's ``source_extraction`` fields.
+ Write the trial table's source_extraction fields.
peak_workers : int, optional
Processes fitting per-trial peaks in the background (default: half
- of ``workers``, at least 1).
+ of workers, at least 1).
f0_ckpt : str or Path, optional
A slap2-f0 checkpoint: predict the missing baselines into the
- baselines' folder first (needs ``slap2-f0``).
+ baselines' folder first (needs slap2-f0).
f0_device : str
Device of the prediction ('cuda' by default, 'cpu', 'auto').
f0_command : str, optional
- The slap2-f0 executable (default: ``slap2-f0`` on the PATH).
+ The slap2-f0 executable (default: slap2-f0 on the PATH).
f0_out_frames : int, optional
Frames per tile of the prediction (see
:func:`~giant_python.pipeline.silo_baseline.predict_baselines`).
@@ -2275,16 +2689,12 @@ def run_silo(
from .silo_collect import collect
from .silo_session import now
- params = default_baseline_source(
- params, baseline_dir is not None or f0_ckpt is not None
- )
+ params = default_baseline_source(params, baseline_dir is not None or f0_ckpt is not None)
params, ex = resolve_silo_options(params, execution)
start = now()
timer: dict = {"start": start}
t_all = time.perf_counter()
- session = SiloSession.open(
- table, moco_dir, data_dir, out_dir, work_dir, annotations
- )
+ session = SiloSession.open(table, moco_dir, data_dir, out_dir, work_dir, annotations)
seeds = read_seeds(seeds_file, session.n_paths) if seeds_file else None
bdir = baseline_folder(session, baseline_dir)
if not params.needs_network_baseline and (baseline_dir or f0_ckpt):
@@ -2353,9 +2763,7 @@ def run_silo(
t0 = time.perf_counter()
timer["peaks"] = [f.result() for f in peak_futures]
if peak_pool is None and params.trial_peaks:
- timer["peaks"] = run_jobs(
- _peaks_job, peaks_jobs(session, params), 1, 1
- )
+ timer["peaks"] = run_jobs(_peaks_job, peaks_jobs(session, params), 1, 1)
timer["peaks_wait"] = time.perf_counter() - t0
finally:
for p in pools + ([peak_pool] if peak_pool is not None else []):
@@ -2376,11 +2784,18 @@ def run_silo(
return timer
-def default_baseline_source(params, network: bool):
- """``params`` with ``baseline_source`` 'network' when the network's
- baselines are given (``network``) and ``params`` (a dict or None)
+def default_baseline_source(params: SiloParams | dict | None, network: bool) -> SiloParams | dict:
+ """Return params with baseline_source 'network' when the network's baselines are given.
+
+ This is when network is true and params (a dict or None)
does not set it. A :class:`SiloParams` is returned as it is: its
- ``baseline_source`` was chosen when it was made."""
+ baseline_source was chosen when it was made.
+
+ Returns
+ -------
+ SiloParams or dict
+ params as a dict with baseline_source, or params itself.
+ """
if not network or isinstance(params, SiloParams):
return params
values = dict(params or {})
diff --git a/src/giant_python/pipeline/silo_baseline.py b/src/giant_python/pipeline/silo_baseline.py
index 02019671..bbb4e230 100644
--- a/src/giant_python/pipeline/silo_baseline.py
+++ b/src/giant_python/pipeline/silo_baseline.py
@@ -1,15 +1,15 @@
-"""The F0 network's baselines for SILo (stage ``baseline``).
+"""The F0 network's baselines for SILo (stage baseline).
-``slap2-f0 predict-registered`` (slap2-F0-network) writes one
-``_BASELINE-80Hz.h5`` per registered trial-path. GIAnT-Python does
+slap2-f0 predict-registered (slap2-F0-network) writes one
+_BASELINE-80Hz.h5 per registered trial-path. GIAnT-Python does
not import slap2-f0: :func:`predict_baselines` runs its command line, when
it is installed, for the trial-paths whose baseline file is missing
-(``giant silo --f0-ckpt PATH``). Elsewhere (Code Ocean) the prediction is
-its own step and the files are given with ``--baseline-dir``.
+(giant silo --f0-ckpt PATH). Elsewhere (Code Ocean) the prediction is
+its own step and the files are given with --baseline-dir.
slap2-f0's files do not record how the trial was prepared for the network
(channel, thresholds). :func:`predict_baselines` therefore writes a record
-beside each file it makes (``_BASELINE-80Hz.json``: those settings,
+beside each file it makes (_BASELINE-80Hz.json: those settings,
the movie, alignment and baseline files' identities, and the checkpoint's
SHA-256 at prediction time), and :func:`check_baseline_record` refuses a
baseline whose record does not fit the run. A file without a record (made
@@ -17,7 +17,7 @@
path and step the file names.
Files are identified by name, size and modification time. A record written
-with ``digests=True`` also holds each file's SHA-256, so that it still
+with digests=True also holds each file's SHA-256, so that it still
identifies the files after they are copied or moved (a Code Ocean data
asset's files carry their upload times): a file whose modification time
differs is then accepted if its content has the recorded SHA-256.
@@ -32,8 +32,8 @@
import subprocess
import time
import warnings
+from collections.abc import Iterable
from pathlib import Path
-from typing import Optional
from ..models.params import SiloParams
from .silo_session import SiloSession
@@ -54,8 +54,14 @@
_SHA_CACHE: dict = {}
-def file_sha256(path) -> str:
- """A file's SHA-256 (cached per path, size and modification time)."""
+def file_sha256(path: str | Path) -> str:
+ """Return a file's SHA-256 (cached per path, size and modification time).
+
+ Returns
+ -------
+ str
+ The hexadecimal SHA-256 digest of the file's content.
+ """
path = Path(path)
st = path.stat()
key = (str(path.resolve()), st.st_size, st.st_mtime_ns)
@@ -68,23 +74,42 @@ def file_sha256(path) -> str:
return _SHA_CACHE[key]
-def checkpoint_identity(path) -> dict:
- """A checkpoint's name, size and SHA-256 (cached per path, size and
- modification time)."""
+def checkpoint_identity(path: str | Path) -> dict:
+ """Return a checkpoint's name, size and SHA-256.
+
+ The SHA-256 is cached per path, size and
+ modification time.
+
+ Returns
+ -------
+ dict
+ name, size (bytes) and sha256 of the checkpoint file.
+ """
path = Path(path)
sha = file_sha256(path)
return {"name": path.name, "size": path.stat().st_size, "sha256": sha}
-def baseline_path(baseline_dir, movie: Path) -> Path:
- """The network baseline file of a registered movie."""
+def baseline_path(baseline_dir: str | Path, movie: Path) -> Path:
+ """Return the network baseline file of a registered movie.
+
+ Returns
+ -------
+ Path
+ The baseline file in baseline_dir for movie.
+ """
from ..extraction.raster.baseline_map import baseline_file
return baseline_file(baseline_dir, Path(movie).name)
-def f0_command(command: Optional[str] = None) -> str:
- """The slap2-f0 executable: ``command`` or ``slap2-f0`` on the PATH.
+def f0_command(command: str | None = None) -> str:
+ """Return the slap2-f0 executable: command or slap2-f0 on the PATH.
+
+ Returns
+ -------
+ str
+ The path of the executable.
Raises
------
@@ -102,38 +127,63 @@ def f0_command(command: Optional[str] = None) -> str:
def record_path(baseline: Path) -> Path:
- """The record of a baseline file (``_BASELINE-80Hz.json``)."""
+ """Return the record of a baseline file (_BASELINE-80Hz.json).
+
+ Returns
+ -------
+ Path
+ The record file beside baseline.
+ """
return Path(baseline).with_suffix(".json")
def _file_id(path: Path) -> dict:
- """A file's identity (name, size, modification time)."""
+ """Return a file's identity (name, size, modification time).
+
+ Returns
+ -------
+ dict
+ The file's identity (see :func:`~giant_python.pipeline.silo_session.file_id`).
+ """
from .silo_session import file_id
return file_id(Path(path))
def _identity(path: Path, digest: bool) -> dict:
- """A file's identity for a record: :func:`_file_id`, with its SHA-256
- when ``digest``."""
+ """Return a file's identity for a record.
+
+ This is :func:`_file_id`, with its SHA-256
+ when digest.
+
+ Returns
+ -------
+ dict
+ The file's identity, with sha256 when digest.
+ """
out = _file_id(path)
if digest:
out["sha256"] = file_sha256(path)
return out
-def same_file(recorded: Optional[dict], path: Path) -> bool:
- """Whether a recorded identity is ``path``'s: the same name and size,
+def same_file(recorded: dict | None, path: Path) -> bool:
+ """Return whether a recorded identity is path's.
+
+ It is when the file has the same name and size,
and the same modification time, or (a file moved or copied since, e.g.
into a data asset, whose files carry their upload times) the same
- SHA-256 when the record has one."""
+ SHA-256 when the record has one.
+
+ Returns
+ -------
+ bool
+ True if the recorded identity is path's.
+ """
if not recorded:
return False
now = _file_id(path)
- if (
- recorded.get("name") != now["name"]
- or recorded.get("size") != now["size"]
- ):
+ if recorded.get("name") != now["name"] or recorded.get("size") != now["size"]:
return False
if recorded.get("mtime_ns") == now["mtime_ns"]:
return True
@@ -142,7 +192,13 @@ def same_file(recorded: Optional[dict], path: Path) -> bool:
def prediction_settings(params: SiloParams) -> dict:
- """The run's settings that a baseline's prediction depends on."""
+ """Return the run's settings that a baseline's prediction depends on.
+
+ Returns
+ -------
+ dict
+ The value of each prediction setting of params, by name.
+ """
return {n: getattr(params, n) for n in _PREDICTION_SETTINGS}
@@ -150,22 +206,27 @@ def write_baseline_record(
baseline: Path,
movie: Path,
alignment: Path,
- params,
+ params: SiloParams,
checkpoint: dict,
done: bool = True,
digests: bool = False,
) -> Path:
"""Record how a baseline file was predicted (see the module).
- Written before the prediction runs with ``done=False`` (the baseline
+ Written before the prediction runs with done=False (the baseline
file's identity left empty), so that a file written by a prediction
that then fails or is stopped still has its settings; and again with
the file's identity once it is there.
- With ``digests`` the baseline, movie and alignment files' identities
+ With digests the baseline, movie and alignment files' identities
also hold their SHA-256, so that the record still identifies them after
they are copied or moved to another place (:func:`same_file`), for
example when the baselines and the registration become data assets.
+
+ Returns
+ -------
+ Path
+ The record file that was written.
"""
path = record_path(baseline)
rec = {
@@ -181,9 +242,9 @@ def write_baseline_record(
def check_baseline_record(
- baseline: Path, movie: Optional[Path], alignment: Path, params
-) -> Optional[dict]:
- """The record of a baseline file, checked against the run.
+ baseline: Path, movie: Path | None, alignment: Path, params: SiloParams
+) -> dict | None:
+ """Return the record of a baseline file, checked against the run.
Returns
-------
@@ -206,9 +267,7 @@ def check_baseline_record(
again = f"predict {Path(baseline).name} again (remove it and its record)"
# a record without the file's identity was written before a prediction
# that did not finish: the file (written whole by slap2-f0) is its
- if rec.get("baseline") is not None and not same_file(
- rec["baseline"], baseline
- ):
+ if rec.get("baseline") is not None and not same_file(rec["baseline"], baseline):
raise ValueError(
f"{path.name} does not describe {Path(baseline).name} (replaced "
f"since?): remove the record, or {again}"
@@ -228,15 +287,31 @@ def check_baseline_record(
return rec
-def _units(session: SiloSession, units=None) -> list:
- """Kept trial-paths ``(d, t)`` of ``units`` or all."""
+def _units(session: SiloSession, units: Iterable[tuple[int, int]] | None = None) -> list:
+ """Return the kept trial-paths (d, t) of units or all.
+
+ Returns
+ -------
+ list
+ The kept (d, t) trial-paths.
+ """
from .silo import _units as kept_units
return kept_units(session, units)
-def missing_baselines(session: SiloSession, baseline_dir, units=None) -> list:
- """Kept trial-paths without a baseline file: ``[(d, t, movie), ...]``."""
+def missing_baselines(
+ session: SiloSession,
+ baseline_dir: str | Path,
+ units: Iterable[tuple[int, int]] | None = None,
+) -> list:
+ """Return the kept trial-paths without a baseline file.
+
+ Returns
+ -------
+ list
+ [(d, t, movie), ...] of the trial-paths without a baseline file.
+ """
out = []
for d, t in _units(session, units):
movie = session.movie(d, t)
@@ -245,23 +320,37 @@ def missing_baselines(session: SiloSession, baseline_dir, units=None) -> list:
return out
-def f0_movie(moco_dir, stem: str) -> Optional[Path]:
- """The registered movie of a trial that ``predict-registered`` reads:
- ``.tif`` or ``.h5``, the newer where both exist (slap2-f0's
- ``registered_movies``)."""
+def f0_movie(moco_dir: str | Path, stem: str) -> Path | None:
+ """Return the registered movie of a trial that predict-registered reads.
+
+ It is the
+ .tif or .h5, the newer where both exist (slap2-f0's
+ registered_movies).
+
+ Returns
+ -------
+ Path or None
+ The movie, or None if the trial has neither.
+ """
chosen = None
for ext in (".tif", ".h5"):
p = Path(moco_dir) / f"{stem}_REGISTERED_DOWNSAMPLED-80Hz{ext}"
- if p.exists() and (
- chosen is None or p.stat().st_mtime > chosen.stat().st_mtime
- ):
+ if p.exists() and (chosen is None or p.stat().st_mtime > chosen.stat().st_mtime):
chosen = p
return chosen
def _check_movies(session: SiloSession, todo: list) -> None:
- """Refuse to predict from another movie than SILo reads (a trial with
- both a TIFF and an HDF5 movie whose newer one is not SILo's)."""
+ """Refuse to predict from another movie than SILo reads.
+
+ This is a trial with
+ both a TIFF and an HDF5 movie whose newer one is not SILo's.
+
+ Raises
+ ------
+ ValueError
+ If slap2-f0 would read another movie of a trial than SILo does.
+ """
for _, _, movie in todo:
stem = movie.name[: movie.name.index("_REGISTERED")]
other = f0_movie(session.moco_dir, stem)
@@ -272,18 +361,31 @@ def _check_movies(session: SiloSession, todo: list) -> None:
)
-def _check_kept(session, params, baseline_dir, units, todo, identity):
- """The baseline files that are kept must fit the run: their records
+def _check_kept(
+ session: SiloSession,
+ params: SiloParams,
+ baseline_dir: str | Path,
+ units: Iterable[tuple[int, int]] | None,
+ todo: set[tuple[int, int]],
+ identity: dict,
+) -> None:
+ """Check that the baseline files that are kept fit the run.
+
+ Their records
(:func:`check_baseline_record`), and the checkpoint they were predicted
with must be this one (by its SHA-256), so that one run does not mix
- the predictions of two models."""
+ the predictions of two models.
+
+ Raises
+ ------
+ ValueError
+ If a kept baseline file was predicted with another checkpoint.
+ """
for d, t in _units(session, units):
if (d, t) in todo:
continue
base = baseline_path(baseline_dir, session.movie(d, t))
- rec = check_baseline_record(
- base, session.movie(d, t), session.alignment(d, t), params
- )
+ rec = check_baseline_record(base, session.movie(d, t), session.alignment(d, t), params)
made = (rec or {}).get("checkpoint") or {}
if made.get("sha256") and made["sha256"] != identity["sha256"]:
raise ValueError(
@@ -295,7 +397,12 @@ def _check_kept(session, params, baseline_dir, units, todo, identity):
)
-def _check_checkpoint(session, baseline_dir, units, ckpt: Path) -> None:
+def _check_checkpoint(
+ session: SiloSession,
+ baseline_dir: str | Path,
+ units: Iterable[tuple[int, int]] | None,
+ ckpt: Path,
+) -> None:
"""Warn when existing baseline files name another checkpoint."""
import h5py
@@ -318,32 +425,43 @@ def _check_checkpoint(session, baseline_dir, units, ckpt: Path) -> None:
)
-def _run(args: list, log: Path, verbose: bool):
- """Run a command, its output shown or appended to ``log``."""
+def _run(args: list, log: Path, verbose: bool) -> subprocess.CompletedProcess:
+ """Run a command, its output shown or appended to log.
+
+ Returns
+ -------
+ subprocess.CompletedProcess
+ The finished process.
+ """
env = dict(os.environ)
if verbose:
return subprocess.run(args, env=env)
with open(log, "a", encoding="utf-8") as out:
out.write(" ".join(args) + "\n")
out.flush()
- return subprocess.run(
- args, stdout=out, stderr=subprocess.STDOUT, env=env
- )
+ return subprocess.run(args, stdout=out, stderr=subprocess.STDOUT, env=env)
def _predict_args(
- exe,
- session,
- params,
- ckpt,
- baseline_dir,
- todo,
- device,
- out_frames,
+ exe: str,
+ session: SiloSession,
+ params: SiloParams,
+ ckpt: str | Path,
+ baseline_dir: str | Path,
+ todo: list,
+ device: str,
+ out_frames: int | None,
fast: bool = True,
) -> list:
- """The ``predict-registered`` command line for the trial-paths
- ``todo`` (the run's trial preparation settings)."""
+ """Return the predict-registered command line for the trial-paths todo.
+
+ It uses the run's trial preparation settings.
+
+ Returns
+ -------
+ list
+ The command and its arguments.
+ """
keys = sorted({m.name[: m.name.index("_REGISTERED")] for _, _, m in todo})
args = [
exe,
@@ -377,22 +495,22 @@ def _predict_args(
def predict_baselines(
session: SiloSession,
params: SiloParams,
- baseline_dir,
- ckpt,
- units=None,
+ baseline_dir: str | Path,
+ ckpt: str | Path,
+ units: Iterable[tuple[int, int]] | None = None,
device: str = "cuda",
- command: Optional[str] = None,
+ command: str | None = None,
verbose: bool = False,
- out_frames: Optional[int] = None,
+ out_frames: int | None = None,
digests: bool = False,
fast: bool = True,
) -> dict:
- """Predict the missing baselines with ``slap2-f0 predict-registered``.
+ """Predict the missing baselines with slap2-f0 predict-registered.
One process predicts every missing trial-path (the model is loaded
once). The prediction prepares each trial as SILo does, with the run's
- ``activity_channel``, ``nan_thresh``, ``motion_thresh`` and
- ``discard_initial_s``.
+ activity_channel, nan_thresh, motion_thresh and
+ discard_initial_s.
Parameters
----------
@@ -403,17 +521,17 @@ def predict_baselines(
ckpt : str or Path
The slap2-f0 checkpoint.
units : iterable of (int, int), optional
- Zero-based ``(path, trial)`` pairs (default: every kept one).
+ Zero-based (path, trial) pairs (default: every kept one).
device : str
- ``predict-registered``'s device ('cuda' by default; 'cpu' works,
+ predict-registered's device ('cuda' by default; 'cpu' works,
at many times the time; 'auto' takes the GPU if there is one).
command : str, optional
- The slap2-f0 executable (default: ``slap2-f0`` on the PATH).
+ The slap2-f0 executable (default: slap2-f0 on the PATH).
verbose : bool
- Show its output (otherwise it goes to ``predict.log`` in
- ``baseline_dir``).
+ Show its output (otherwise it goes to predict.log in
+ baseline_dir).
out_frames : int, optional
- Frames per tile of the network (``--out_frames``; default: as many
+ Frames per tile of the network (--out_frames; default: as many
as fit in 85% of the free GPU memory). On a GPU that also drives a
display, memory beyond what is free spills into shared system
memory instead of failing, several times slower; a fixed size
@@ -425,19 +543,21 @@ def predict_baselines(
them after the files are copied or moved (data assets). Costs one
read of each file.
fast : bool
- Pass ``--fast`` to ``predict-registered`` (streaming inference,
+ Pass --fast to predict-registered (streaming inference,
prefetch and chunked HDF5 reads; about three times faster, with
- the same baselines to float16 rounding) when ``out_frames`` is not
+ the same baselines to float16 rounding) when out_frames is not
given.
Returns
-------
dict
- ``predicted`` (one-based ``[path, trial]`` pairs), ``seconds``,
- ``checkpoint`` (:func:`checkpoint_identity`).
+ predicted (one-based [path, trial] pairs), seconds,
+ checkpoint (:func:`checkpoint_identity`).
Raises
------
+ FileNotFoundError
+ If ckpt is not a file.
RuntimeError
If the command fails or leaves a file missing.
"""
diff --git a/src/giant_python/pipeline/silo_collect.py b/src/giant_python/pipeline/silo_collect.py
index 2c8b8c08..f9322ab8 100644
--- a/src/giant_python/pipeline/silo_collect.py
+++ b/src/giant_python/pipeline/silo_collect.py
@@ -2,19 +2,19 @@
Reads every planned path's plan, results files, localization files (the
trials' own peaks) and alignment files (the motion records), runs the
-kinetics test, and writes ``experiment_summary.h5`` and
-``per_trial_summary.h5`` in GIAnT-MATLAB's schema, then the trial table's
-``source_extraction`` fields (``analysis_params``, ``fn_raw``), as
-``SILo.m`` does at its end.
-
-With the network's baseline, ``experiment_summary.h5`` also gets the
-attributes ``baseline_source``, ``baseline_mode``, ``localization_baseline``,
-``network_baseline`` (JSON: per trial-path, the baseline file and the
+kinetics test, and writes experiment_summary.h5 and
+per_trial_summary.h5 in GIAnT-MATLAB's schema, then the trial table's
+source_extraction fields (analysis_params, fn_raw), as
+SILo.m does at its end.
+
+With the network's baseline, experiment_summary.h5 also gets the
+attributes baseline_source, baseline_mode, localization_baseline,
+network_baseline (JSON: per trial-path, the baseline file and the
network's checkpoint that extraction used) and
-``localization_network_baseline`` (the same for localization, which
-decided the seeds); the ``params`` struct records
-the settings that differ from MATLAB's (``baselineSource``,
-``baselineMode``, ``peakth``, ``localizationSurround``, ...).
+localization_network_baseline (the same for localization, which
+decided the seeds); the params struct records
+the settings that differ from MATLAB's (baselineSource,
+baselineMode, peakth, localizationSurround, ...).
"""
from __future__ import annotations
@@ -23,7 +23,8 @@
import os
import time
import warnings
-from typing import Optional
+from pathlib import Path
+from typing import TYPE_CHECKING
import h5py
import numpy as np
@@ -32,27 +33,48 @@
from .silo_session import SiloSession, attr, now, skip_hash
from .silo_solve import solve_science
+if TYPE_CHECKING:
+ from ..extraction.raster.results import TrialOutcome, TrialShape
+ from ..extraction.raster.solver_setup import SolverParams
+
def _results_files(session: SiloSession, d: int, t: int) -> list:
- """The results files of trial-path ``(d, t)``."""
+ """Return the results files of trial-path (d, t).
+
+ Returns
+ -------
+ list
+ The paths of its results files in the session's results folder, sorted; empty if
+ the folder does not exist.
+ """
stem = f"path{d + 1}_trial{t + 1:04d}"
folder = session.results_dir
if not folder.exists():
return []
return sorted(
- p
- for p in folder.glob(f"{stem}*.h5")
- if p.stem == stem or p.stem.startswith(stem + "_s")
+ p for p in folder.glob(f"{stem}*.h5") if p.stem == stem or p.stem.startswith(stem + "_s")
)
def _container_hash(
- session, params, plan_hash, d, t, baseline_dir=None
-) -> Optional[str]:
- """The prepare hash of trial-path ``(d, t)`` from its current inputs;
+ session: SiloSession,
+ params: SiloParams,
+ plan_hash: str,
+ d: int,
+ t: int,
+ baseline_dir: str | Path | None = None,
+) -> str | None:
+ """Return the prepare hash of trial-path (d, t) from its current inputs.
+
None if its raw recording or its network baseline is not here (a
collect machine without them: results are then checked against plan
- and settings only)."""
+ and settings only).
+
+ Returns
+ -------
+ str or None
+ The prepare hash; None if the raw recording or the network baseline is not here.
+ """
from .silo import (
_baseline_file,
_prepare_hash,
@@ -79,21 +101,26 @@ def _current(
files: list,
plan_hash: str,
science: str,
- container_hash: Optional[str] = None,
+ container_hash: str | None = None,
) -> list:
- """The results files made from the plan ``plan_hash`` (and, when
- given, the container ``container_hash``: the trial's current raw data,
- lines and alignment) with the scientific solve settings ``science``;
- others are left out, with a warning (they are from earlier runs)."""
+ """Return the results files made from the plan plan_hash.
+
+ When given, the container container_hash (the trial's current raw data,
+ lines and alignment) is matched too, and the scientific solve settings are
+ science; others are left out, with a warning (they are from earlier runs).
+
+ Returns
+ -------
+ list
+ The files made from the plan (and the container, if given) with the solve
+ settings science.
+ """
keep, stale = [], []
for f in files:
ok = (
attr(f, "plan_hash") == plan_hash
and attr(f, "solve_science") == science
- and (
- container_hash is None
- or attr(f, "container_hash") == container_hash
- )
+ and (container_hash is None or attr(f, "container_hash") == container_hash)
)
(keep if ok else stale).append(f)
if stale:
@@ -105,42 +132,70 @@ def _current(
class _OutcomeLoader:
- """Assembles a trial from its results files when called; its sizes
- (``sizes``) and its activity-channel traces (``activity_ls``) can be
+ """Assemble a trial from its results files when called.
+
+ Its sizes (sizes) and its activity-channel traces (activity_ls) can be
read without assembling it (the summaries need those of every trial
- before they write any)."""
+ before they write any).
+ """
- def __init__(self, files: list, solver_params) -> None:
- """The trial's results files and the solver's parameters."""
+ def __init__(self, files: list, solver_params: SolverParams) -> None:
+ """Record the trial's results files and the solver's parameters."""
self.files = files
self.solver_params = solver_params
- def __call__(self):
- """Read the files and assemble the trial."""
+ def __call__(self) -> TrialOutcome:
+ """Read the files and assemble the trial.
+
+ Returns
+ -------
+ TrialOutcome
+ The trial assembled from its results files.
+ """
from ..extraction.raster.results import read_results, trial_outcome
- return trial_outcome(
- [read_results(f) for f in self.files], self.solver_params
- )
+ return trial_outcome([read_results(f) for f in self.files], self.solver_params)
+
+ def sizes(self) -> TrialShape:
+ """Return the trial's sizes.
+
+ See :func:`~giant_python.extraction.raster.results.trial_shape`.
- def sizes(self):
- """The trial's sizes (:func:`~giant_python.extraction.raster.
- results.trial_shape`)."""
+ Returns
+ -------
+ TrialShape
+ The trial's sizes, read without assembling it.
+ """
from ..extraction.raster.results import trial_shape
return trial_shape(self.files, self.solver_params)
- def activity_ls(self):
- """The trial's activity-channel least-squares traces and SNR
- (:func:`~giant_python.extraction.raster.results.trial_ls`)."""
+ def activity_ls(self) -> tuple[np.ndarray, np.ndarray] | None:
+ """Return the trial's activity-channel least-squares traces and SNR.
+
+ See :func:`~giant_python.extraction.raster.results.trial_ls`.
+
+ Returns
+ -------
+ tuple[np.ndarray, np.ndarray] or None
+ (ls, snr): the traces of shape (sources, frames) and the SNR of shape
+ (sources,); None when the trial has no activity.
+ """
from ..extraction.raster.results import trial_ls
return trial_ls(self.files, 0, self.solver_params)
-def _outcome_loader(files: list, solver_params):
- """A function that assembles a trial from its results files
- (:class:`_OutcomeLoader`)."""
+def _outcome_loader(files: list, solver_params: SolverParams) -> _OutcomeLoader:
+ """Return a function that assembles a trial from its results files.
+
+ See :class:`_OutcomeLoader`.
+
+ Returns
+ -------
+ _OutcomeLoader
+ The loader for files; calling it assembles the trial.
+ """
return _OutcomeLoader(files, solver_params)
@@ -148,14 +203,14 @@ def path_result(
session: SiloSession,
params: SiloParams,
d: int,
- baseline_dir=None,
- provenance: Optional[dict] = None,
-) -> Optional[object]:
- """Everything the summaries need of path ``d``, read from its files.
+ baseline_dir: str | Path | None = None,
+ provenance: dict | None = None,
+) -> object | None:
+ """Everything the summaries need of path d, read from its files.
- ``provenance``, if given, gets the network baseline (its identity, as
+ provenance, if given, gets the network baseline (its identity, as
the results files record it) of each trial-path assembled here, keyed
- ``path_trial``: from the files that are used, not from earlier
+ path_trial: from the files that are used, not from earlier
runs' files left in the folder.
Returns
@@ -168,7 +223,7 @@ def path_result(
FileNotFoundError
If a valid trial has neither a skip marker of the current plan nor
results files made from the current plan with the current
- scientific solve settings (``solve_science``).
+ scientific solve settings (solve_science).
"""
from ..extraction.raster.plan import read_plan
from ..extraction.raster.stage_files import read_localization
@@ -246,9 +301,11 @@ def path_result(
def update_trial_table(session: SiloSession, params_matlab: dict) -> None:
- """Write the trial table's ``source_extraction`` fields as SILo does
- (``analysis_params``, ``fn_raw``); the rest of the table is left as it
- is."""
+ """Write the trial table's source_extraction fields as SILo does.
+
+ The fields are analysis_params and fn_raw; the rest of the table is left as it
+ is.
+ """
from .register import _update_trial_table
fn_raw = np.array(
@@ -265,26 +322,26 @@ def update_trial_table(session: SiloSession, params_matlab: dict) -> None:
def collect(
session: SiloSession,
params: SiloParams,
- execution: Optional[SiloExecution] = None,
+ execution: SiloExecution | None = None,
update_table: bool = True,
- start_time: Optional[str] = None,
+ start_time: str | None = None,
save_subproblems_dir: str = "",
- baseline_dir=None,
+ baseline_dir: str | Path | None = None,
) -> dict:
- """Stage ``collect``: the summaries and the trial table's fields.
+ """Stage collect: the summaries and the trial table's fields.
Parameters
----------
session : SiloSession
params : SiloParams
execution : SiloExecution, optional
- Recorded as ``nWorkers`` (``workers``).
+ Recorded as nWorkers (workers).
update_table : bool
- Write ``source_extraction`` into the trial table.
+ Write source_extraction into the trial table.
start_time : str, optional
- ``startTime`` to record (default: now).
+ startTime to record (default: now).
save_subproblems_dir : str
- ``saveSubproblemsDir`` to record.
+ saveSubproblemsDir to record.
baseline_dir : str or Path, optional
Folder of the network's baselines (default: the session's), to
check the results against them; without the files there the
@@ -302,10 +359,7 @@ def collect(
start_time = start_time or now()
t0 = time.perf_counter()
used: dict = {}
- results = [
- path_result(session, params, d, baseline_dir, used)
- for d in range(session.n_paths)
- ]
+ results = [path_result(session, params, d, baseline_dir, used) for d in range(session.n_paths)]
kept = {}
for d, r in enumerate(results):
if r is None:
@@ -350,9 +404,7 @@ def collect(
if used:
f.attrs["network_baseline"] = json.dumps(used, sort_keys=True)
if localized:
- f.attrs["localization_network_baseline"] = json.dumps(
- localized, sort_keys=True
- )
+ f.attrs["localization_network_baseline"] = json.dumps(localized, sort_keys=True)
spots = {}
if any(r is not None for r in results):
from .silo_spots import annotate_spots
@@ -389,9 +441,17 @@ def collect(
def localization_baselines(session: SiloSession) -> dict:
- """The network baselines the planned paths' trials were localized with
- (which decided the seeds), keyed ``path_trial``; empty with
- the moving median."""
+ """Return the network baselines the planned paths' trials were localized with.
+
+ They decided the seeds; keyed path_trial; empty with
+ the moving median.
+
+ Returns
+ -------
+ dict
+ The network baseline of each such trial-path, keyed path_trial;
+ empty with the moving median.
+ """
from .silo import check_plan_localizations, localization_baseline
out = {}
@@ -407,9 +467,16 @@ def localization_baselines(session: SiloSession) -> dict:
return out
-def _baseline_identity(files: list) -> Optional[dict]:
- """The network baseline recorded in a trial's results files (they are
- of one container, so they record the same), or None."""
+def _baseline_identity(files: list) -> dict | None:
+ """Return the network baseline recorded in a trial's results files, or None.
+
+ The files are of one container, so they record the same.
+
+ Returns
+ -------
+ dict or None
+ The recorded network baseline; None if no file records one.
+ """
for f in files:
value = attr(f, "network_baseline")
if value:
@@ -419,8 +486,14 @@ def _baseline_identity(files: list) -> Optional[dict]:
return None
-def read_kept(path) -> dict:
- """Sources per path in an experiment summary (debugging aid)."""
+def read_kept(path: str | Path) -> dict:
+ """Return the sources per path in an experiment summary (debugging aid).
+
+ Returns
+ -------
+ dict
+ The number of sources of each path, by the path's group name.
+ """
out = {}
with h5py.File(path, "r") as f:
for name in f:
diff --git a/src/giant_python/pipeline/silo_session.py b/src/giant_python/pipeline/silo_session.py
index d32ccb25..df4dc0da 100644
--- a/src/giant_python/pipeline/silo_session.py
+++ b/src/giant_python/pipeline/silo_session.py
@@ -3,10 +3,10 @@
What every SILo stage needs to find its inputs and outputs: the trial
table's fields (read without its reference stack), the folders (raw data,
motion correction, source extraction, the stages' work folder), which
-trial-paths pass file verification (``verifyFiles.m``), and the name of
+trial-paths pass file verification (verifyFiles.m), and the name of
every stage file.
-Work folder layout (default ``/source_extraction/silo``; trial and
+Work folder layout (default /source_extraction/silo; trial and
path numbers one-based, as in MATLAB's file names)::
localize/path_trial.h5 per-trial localization
@@ -23,6 +23,7 @@
import concurrent.futures as cf
import json
import os
+from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path, PurePath
@@ -30,6 +31,7 @@
import h5py
import numpy as np
+import numpy.typing as npt
from ..parallel import BLAS_IDLE, THREAD_VARS, _mapped_paths, spawn_pool
@@ -48,19 +50,41 @@
def stage_hash(record: dict) -> str:
- """Settings hash of a stage's unit."""
+ """Return the settings hash of a stage's unit.
+
+ Parameters
+ ----------
+ record : dict
+ The stage's settings; hashed together with :data:`STAGE_VERSION`.
+
+ Returns
+ -------
+ str
+ The settings hash.
+ """
from ..extraction.raster.container import settings_hash
return settings_hash({"stage_version": STAGE_VERSION, **record})
def file_id(path: Path) -> dict:
- """A file's identity for a settings hash: name, size and modification
- time (nanoseconds).
+ """Return a file's identity for a settings hash.
+
+ The identity is its name, size and modification time (nanoseconds).
A changed or replaced input gets a new identity; so does a copied one
(a copy has a new modification time), which only costs a rerun.
Reading every input for a content hash would cost minutes per trial.
+
+ Parameters
+ ----------
+ path : Path
+ The file.
+
+ Returns
+ -------
+ dict
+ name, size and mtime_ns of the file.
"""
st = Path(path).stat()
return {
@@ -71,14 +95,26 @@ def file_id(path: Path) -> dict:
def recording_ids(dat: Path) -> list:
- """Identities (:func:`file_id`) of the files a raw recording is read
- from: its ``.dat`` file (all files of a CYCLE-split recording) and the
- ``.meta`` files whose names begin its name.
+ """Return the identities of the files a raw recording is read from.
+
+ The identities (:func:`file_id`) are those of its .dat file (all
+ files of a CYCLE-split recording) and the
+ .meta files whose names begin its name.
+
+ Parameters
+ ----------
+ dat : Path
+ The recording's .dat file.
+
+ Returns
+ -------
+ list of dict
+ The identity of each file, the .dat files first.
Raises
------
FileNotFoundError
- If the ``.dat`` file is not there (also for a CYCLE-split one).
+ If the .dat file is not there (also for a CYCLE-split one).
"""
import re
@@ -92,23 +128,39 @@ def recording_ids(dat: Path) -> list:
files = sorted(
p
for p in folder.glob(f"{base}*.dat")
- if re.fullmatch(
- re.escape(base) + r"-?CYCLE-?\d+", p.stem, re.IGNORECASE
- )
+ if re.fullmatch(re.escape(base) + r"-?CYCLE-?\d+", p.stem, re.IGNORECASE)
)
- meta = sorted(
- p for p in folder.glob("*.meta") if dat.stem.startswith(p.stem)
- )
+ meta = sorted(p for p in folder.glob("*.meta") if dat.stem.startswith(p.stem))
return [file_id(p) for p in files + meta]
def now() -> str:
- """The time as MATLAB's SILo records it."""
+ """Return the time as MATLAB's SILo records it.
+
+ Returns
+ -------
+ str
+ The local time in ISO 8601 format, to milliseconds.
+ """
return datetime.now().astimezone().isoformat(timespec="milliseconds")
-def attr(path: Path, name: str):
- """An attribute of an HDF5 file, or None if absent or unreadable."""
+def attr(path: Path, name: str) -> object:
+ """Return an attribute of an HDF5 file, or None if absent or unreadable.
+
+ Parameters
+ ----------
+ path : Path
+ The HDF5 file.
+ name : str
+ The attribute's name.
+
+ Returns
+ -------
+ object
+ The attribute's value (bytes decoded to str); None if it is absent
+ or the file is unreadable.
+ """
try:
with h5py.File(path, "r") as f:
v = f.attrs.get(name)
@@ -130,18 +182,26 @@ def attr(path: Path, name: str):
def _loaded_openblas() -> list:
- """Paths of the OpenBLAS libraries loaded into this process (Linux:
- from ``/proc/self/maps``; elsewhere none)."""
+ """Return the paths of the OpenBLAS libraries loaded into this process.
+
+ On Linux these are read from /proc/self/maps; elsewhere there are
+ none.
+
+ Returns
+ -------
+ list of str
+ The library paths.
+ """
return [path for path in _mapped_paths() if "openblas" in path]
def limit_blas_threads(threads: int) -> int:
"""Limit the BLAS thread pools already loaded into this process.
- ``OMP_NUM_THREADS`` and its relatives are read when a numerical
+ OMP_NUM_THREADS and its relatives are read when a numerical
library loads, so setting them afterwards changes nothing: numpy's and
scipy's OpenBLAS keep one thread per core (up to 64 each). This sets
- the count of the loaded libraries themselves: with ``threadpoolctl``
+ the count of the loaded libraries themselves: with threadpoolctl
when it is installed (every BLAS and OpenMP runtime it knows), else
through the OpenBLAS libraries' own setter (Linux).
@@ -176,9 +236,17 @@ def limit_blas_threads(threads: int) -> int:
def set_threads(threads: int) -> None:
- """Give this process ``threads`` numerical threads: the thread
+ """Give this process threads numerical threads.
+
+ These are the thread
variables (for libraries not loaded yet and for child processes), the
- BLAS libraries already loaded (:func:`limit_blas_threads`) and torch."""
+ BLAS libraries already loaded (:func:`limit_blas_threads`) and torch.
+
+ Parameters
+ ----------
+ threads : int
+ The thread count.
+ """
for name in _THREAD_VARS:
os.environ[name] = str(threads)
limit_blas_threads(threads)
@@ -196,20 +264,32 @@ def _worker_init(threads: int) -> None:
torch.set_num_threads(threads)
-def make_pool(
- workers: int, threads: int, blas_idle: bool = False
-) -> cf.ProcessPoolExecutor:
- """A process pool whose workers use ``threads`` threads each.
+def make_pool(workers: int, threads: int, blas_idle: bool = False) -> cf.ProcessPoolExecutor:
+ """Return a process pool whose workers use threads threads each.
The thread variables are set while the workers start, so that the
numerical libraries see them when they load. The workers are spawned
on every platform: a forked worker (Linux's default) inherits the
parent's numerical libraries already loaded with the parent's thread
count (OpenBLAS: all cores), which the variables can no longer change.
- With ``blas_idle`` OpenBLAS's idle threads sleep at once
+ With blas_idle OpenBLAS's idle threads sleep at once
(:data:`~giant_python.parallel.BLAS_IDLE`) rather than spin. All the
workers start before this returns, and a start that fails ends those
started (:func:`~giant_python.parallel.spawn_pool`).
+
+ Parameters
+ ----------
+ workers : int
+ Worker processes.
+ threads : int
+ Threads of each worker.
+ blas_idle : bool
+ Let OpenBLAS's idle threads sleep at once.
+
+ Returns
+ -------
+ concurrent.futures.ProcessPoolExecutor
+ The started pool.
"""
env = dict.fromkeys(_THREAD_VARS, str(threads))
if blas_idle:
@@ -218,10 +298,28 @@ def make_pool(
def run_jobs(
- func, jobs: list, workers: int, threads: int, blas_idle: bool = False
+ func: Callable, jobs: list, workers: int, threads: int, blas_idle: bool = False
) -> list:
- """Run tasks in a process pool (or here, for one worker; ``blas_idle``:
- see :func:`make_pool`)."""
+ """Run tasks in a process pool (or here, for one worker).
+
+ Parameters
+ ----------
+ func : callable
+ Applied to each job (picklable for a pool).
+ jobs : list
+ The jobs.
+ workers : int
+ Worker processes; at most one runs the jobs here.
+ threads : int
+ Threads of each worker.
+ blas_idle : bool
+ See :func:`make_pool`.
+
+ Returns
+ -------
+ list
+ The results of func, in the order of jobs.
+ """
if not jobs:
return []
if workers <= 1 or len(jobs) == 1:
@@ -231,7 +329,18 @@ def run_jobs(
def pool_failure(affected: str) -> RuntimeError:
- """Explain a broken pool without guessing which worker's task died."""
+ """Explain a broken pool without guessing which worker's task died.
+
+ Parameters
+ ----------
+ affected : str
+ What the broken pool was working on.
+
+ Returns
+ -------
+ RuntimeError
+ The error to raise.
+ """
return RuntimeError(
f"a worker process ended without a result ({affected}): it was "
"probably killed for lack of memory; every worker holds one "
@@ -239,15 +348,41 @@ def pool_failure(affected: str) -> RuntimeError:
)
-def _decode(value) -> str:
- """A string element of an HDF5 dataset."""
+def _decode(value: object) -> str:
+ """Return a string element of an HDF5 dataset.
+
+ Parameters
+ ----------
+ value : object
+ The element (bytes or str).
+
+ Returns
+ -------
+ str
+ The element decoded as text.
+ """
if isinstance(value, bytes):
return value.decode("utf-8", "replace")
return str(value)
-def _read(f: h5py.File, name: str, row_major: bool):
- """A dataset in MATLAB orientation (strings decoded), or None."""
+def _read(f: h5py.File, name: str, row_major: bool) -> np.ndarray | None:
+ """Return a dataset in MATLAB orientation (strings decoded), or None.
+
+ Parameters
+ ----------
+ f : h5py.File
+ The open file.
+ name : str
+ The dataset's name.
+ row_major : bool
+ Whether the file stores arrays in row-major order (so no transpose).
+
+ Returns
+ -------
+ np.ndarray or None
+ The dataset; None if it is not in the file.
+ """
if name not in f:
return None
ds = f[name]
@@ -260,8 +395,26 @@ def _read(f: h5py.File, name: str, row_major: bool):
return value
-def _grid(value, shape) -> np.ndarray:
- """A per-path, per-trial grid of the table's shape."""
+def _grid(value: npt.ArrayLike, shape: tuple[int, int]) -> np.ndarray:
+ """Return a per-path, per-trial grid of the table's shape.
+
+ Parameters
+ ----------
+ value : array-like
+ The table's field.
+ shape : tuple of int
+ The table's (paths, trials).
+
+ Returns
+ -------
+ np.ndarray
+ value reshaped to shape.
+
+ Raises
+ ------
+ ValueError
+ If value does not have shape[0] * shape[1] entries.
+ """
a = np.asarray(value)
if a.size == shape[0] * shape[1]:
return a.reshape(shape)
@@ -277,21 +430,21 @@ class SiloSession:
table_path : Path
The trial table.
datadr : Path
- Folder of the raw ``.dat`` files.
+ Folder of the raw .dat files.
savedr : Path
- The session's output folder (trial table ``savedr``).
+ The session's output folder (trial table savedr).
moco_dir : Path
- Motion-correction folder (``/motion_correction``).
+ Motion-correction folder (/motion_correction).
out_dir : Path
- Where the summaries go (``/source_extraction``).
+ Where the summaries go (/source_extraction).
work_dir : Path
The stages' files (see the module docstring).
annotations : Path or None
- ``annotations.h5`` (``/annotations/annotations.h5``).
+ annotations.h5 (/annotations/annotations.h5).
filename, fn_reg_ds, fn_adata : ndarray of object, (paths, trials)
Raw, registered-movie and alignment file names.
first_line, last_line : ndarray of float, (paths, trials)
- Each trial's lines in its raw file (``slap2_info``).
+ Each trial's lines in its raw file (slap2_info).
registration_failed : ndarray of bool, (paths, trials)
keep : ndarray of bool, (paths, trials)
Trial-paths that pass file verification.
@@ -330,12 +483,12 @@ def n_trials(self) -> int:
@classmethod
def open(
cls,
- table,
- moco_dir=None,
- data_dir=None,
- out_dir=None,
- work_dir=None,
- annotations=None,
+ table: str | Path,
+ moco_dir: str | Path | None = None,
+ data_dir: str | Path | None = None,
+ out_dir: str | Path | None = None,
+ work_dir: str | Path | None = None,
+ annotations: str | Path | None = None,
inputs: str = "all",
) -> "SiloSession":
"""Read a trial table and verify the session's files.
@@ -343,14 +496,14 @@ def open(
Parameters
----------
table : str or Path
- ``trial_table.h5``, or the folder holding it.
+ trial_table.h5, or the folder holding it.
moco_dir, data_dir, out_dir, work_dir : str or Path, optional
- Overrides of ``/motion_correction``, the table's
- ``datadr``, ``/source_extraction`` and
- ``/silo``.
+ Overrides of /motion_correction, the table's
+ datadr, /source_extraction and
+ /silo.
annotations : str or Path, optional
The annotations file (default:
- ``/annotations/annotations.h5`` if it exists).
+ /annotations/annotations.h5 if it exists).
inputs : {'all', 'collect'}
Which inputs a trial needs to be kept (see :meth:`verify`).
@@ -385,15 +538,11 @@ def open(
raise ValueError(f"{table} is not a SLAP2 trial table")
if fields["fn_reg_ds"] is None or fields["fn_adata"] is None:
raise ValueError(f"{table} has no registration (giant register)")
- savedr = Path(
- str(savedr.ravel()[0]) if savedr is not None else table.parent
- )
+ savedr = Path(str(savedr.ravel()[0]) if savedr is not None else table.parent)
datadr = Path(
data_dir
if data_dir is not None
- else (
- str(datadr.ravel()[0]) if datadr is not None else table.parent
- )
+ else (str(datadr.ravel()[0]) if datadr is not None else table.parent)
)
moco_dir = Path(moco_dir or savedr / "motion_correction")
out_dir = Path(out_dir or savedr / "source_extraction")
@@ -429,8 +578,20 @@ def open(
return session
def movie(self, d: int, t: int) -> Optional[Path]:
- """Trial-path ``(d, t)``'s registered movie (``.tif`` or ``.h5``),
- if it exists."""
+ """Return trial-path (d, t)'s registered movie, if it exists.
+
+ Parameters
+ ----------
+ d : int
+ Path index (zero-based).
+ t : int
+ Trial index (zero-based).
+
+ Returns
+ -------
+ Path or None
+ The movie (.tif or .h5); None if it does not exist.
+ """
name = str(self.fn_reg_ds[d, t] or "")
if not name:
return None
@@ -442,23 +603,62 @@ def movie(self, d: int, t: int) -> Optional[Path]:
return None
def alignment(self, d: int, t: int) -> Path:
- """Trial-path ``(d, t)``'s alignment file."""
+ """Return trial-path (d, t)'s alignment file.
+
+ Parameters
+ ----------
+ d : int
+ Path index (zero-based).
+ t : int
+ Trial index (zero-based).
+
+ Returns
+ -------
+ Path
+ The alignment file.
+ """
name = PurePath(str(self.fn_adata[d, t]).replace("\\", "/")).stem
return self.moco_dir / (name + ".h5")
def raw(self, d: int, t: int) -> Path:
- """Trial-path ``(d, t)``'s raw ``.dat`` file."""
+ """Return trial-path (d, t)'s raw .dat file.
+
+ Parameters
+ ----------
+ d : int
+ Path index (zero-based).
+ t : int
+ Trial index (zero-based).
+
+ Returns
+ -------
+ Path
+ The raw file.
+ """
return self.datadr / str(self.filename[d, t])
def verify(self, inputs: str = "all") -> None:
- """Set :attr:`keep` as ``verifyFiles.m``: the registered movie, the
+ """Set :attr:`keep` as verifyFiles.m does.
+
+ The registered movie, the
alignment file and the raw file exist, and registration did not
fail; read the channels and frame rate of the first kept trial.
- With ``inputs='collect'`` only the alignment files are required
+ With inputs='collect' only the alignment files are required
(and registration must not have failed): the dispatch and collect
stages need neither the registered movies nor the raw data, and
take the trials to collect from the stages' files.
+
+ Parameters
+ ----------
+ inputs : {'all', 'collect'}
+ Which inputs a trial needs to be kept.
+
+ Raises
+ ------
+ ValueError
+ If inputs is not valid, or no trial passes file
+ verification.
"""
if inputs not in ("all", "collect"):
raise ValueError("inputs must be 'all' or 'collect'")
@@ -467,16 +667,9 @@ def verify(self, inputs: str = "all") -> None:
for t in range(self.n_trials):
if not str(self.filename[d, t] or ""):
continue
- ok = (
- self.alignment(d, t).exists()
- and not self.registration_failed[d, t]
- )
+ ok = self.alignment(d, t).exists() and not self.registration_failed[d, t]
if inputs == "all":
- ok = (
- ok
- and self.movie(d, t) is not None
- and self.raw(d, t).exists()
- )
+ ok = ok and self.movie(d, t) is not None and self.raw(d, t).exists()
keep[d, t] = ok
if not keep.any():
raise ValueError(
@@ -486,33 +679,95 @@ def verify(self, inputs: str = "all") -> None:
self.keep = keep
d, t = (int(i[0]) for i in np.nonzero(keep))
with h5py.File(self.alignment(d, t), "r") as f:
- self.num_channels = int(
- np.asarray(f["numChannels"][()]).ravel()[0]
- )
+ self.num_channels = int(np.asarray(f["numChannels"][()]).ravel()[0])
self.align_hz = float(np.asarray(f["alignHz"][()]).ravel()[0])
# stage files
def localize_file(self, d: int, t: int) -> Path:
- """Localization file of trial-path ``(d, t)`` (zero-based)."""
+ """Return the localization file of trial-path (d, t) (zero-based).
+
+ Parameters
+ ----------
+ d : int
+ Path index.
+ t : int
+ Trial index.
+
+ Returns
+ -------
+ Path
+ The localization file.
+ """
return self.work_dir / "localize" / f"path{d + 1}_trial{t + 1:04d}.h5"
def plan_file(self, d: int) -> Path:
- """Plan file of path ``d`` (zero-based)."""
+ """Return the plan file of path d (zero-based).
+
+ Parameters
+ ----------
+ d : int
+ Path index.
+
+ Returns
+ -------
+ Path
+ The plan file.
+ """
return self.work_dir / "plan" / f"path{d + 1}.h5"
def container_file(self, d: int, t: int) -> Path:
- """Container of trial-path ``(d, t)``."""
- return (
- self.work_dir / "containers" / f"path{d + 1}_trial{t + 1:04d}.h5"
- )
+ """Return the container of trial-path (d, t).
+
+ Parameters
+ ----------
+ d : int
+ Path index (zero-based).
+ t : int
+ Trial index (zero-based).
+
+ Returns
+ -------
+ Path
+ The container file.
+ """
+ return self.work_dir / "containers" / f"path{d + 1}_trial{t + 1:04d}.h5"
def skip_file(self, d: int, t: int) -> Path:
- """Marker of a trial-path that is not extracted."""
+ """Return the marker of a trial-path that is not extracted.
+
+ Parameters
+ ----------
+ d : int
+ Path index (zero-based).
+ t : int
+ Trial index (zero-based).
+
+ Returns
+ -------
+ Path
+ The marker file.
+ """
return self.container_file(d, t).with_suffix(".skip.json")
- def results_file(self, d: int, t: int, span=None) -> Path:
- """Results file of trial-path ``(d, t)`` (or of subproblems
- ``span = (a, b)``, ``a`` to ``b - 1``)."""
+ def results_file(self, d: int, t: int, span: tuple[int, int] | None = None) -> Path:
+ """Return the results file of trial-path (d, t).
+
+ Or of subproblems span = (a, b), a to b - 1.
+
+ Parameters
+ ----------
+ d : int
+ Path index (zero-based).
+ t : int
+ Trial index (zero-based).
+ span : tuple of int, optional
+ The subproblems (a, b); None for the whole trial-path.
+
+ Returns
+ -------
+ Path
+ The results file.
+ """
stem = f"path{d + 1}_trial{t + 1:04d}"
if span is not None:
stem += f"_s{span[0]:04d}-{span[1] - 1:04d}"
@@ -530,16 +785,31 @@ def jobs_dir(self) -> Path:
@property
def baselines_dir(self) -> Path:
- """Default folder of the network's baselines (where ``--f0-ckpt``
- writes them when no ``--baseline-dir`` is given)."""
+ """Default folder of the network's baselines.
+
+ This is where --f0-ckpt
+ writes them when no --baseline-dir is given.
+ """
return self.work_dir / "baselines"
-def write_skip(
- path: Path, reason: str, settings_hash: str, plan_hash: str = ""
-) -> None:
- """Mark a trial-path as not extracted (``*.skip.json``: the reason, the
- settings hash of the prepare stage and the plan's hash)."""
+def write_skip(path: Path, reason: str, settings_hash: str, plan_hash: str = "") -> None:
+ """Mark a trial-path as not extracted.
+
+ The marker is a ``*.skip.json``: the reason, the
+ settings hash of the prepare stage and the plan's hash.
+
+ Parameters
+ ----------
+ path : Path
+ The marker file.
+ reason : str
+ Why the trial-path is not extracted.
+ settings_hash : str
+ The prepare stage's settings hash.
+ plan_hash : str
+ The plan's hash.
+ """
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}.partial")
record = {
@@ -552,8 +822,20 @@ def write_skip(
def skip_hash(path: Path, key: str = "settings_hash") -> Optional[str]:
- """A hash recorded in a skip marker (``settings_hash`` or
- ``plan_hash``; None if there is no marker)."""
+ """Return a hash recorded in a skip marker.
+
+ Parameters
+ ----------
+ path : Path
+ The marker file.
+ key : str
+ settings_hash or plan_hash.
+
+ Returns
+ -------
+ str or None
+ The hash; None if there is no marker.
+ """
try:
return json.loads(path.read_text(encoding="utf-8"))[key]
except (OSError, ValueError, KeyError, TypeError):
diff --git a/src/giant_python/pipeline/silo_solve.py b/src/giant_python/pipeline/silo_solve.py
index ed423637..94a3e4cc 100644
--- a/src/giant_python/pipeline/silo_solve.py
+++ b/src/giant_python/pipeline/silo_solve.py
@@ -13,10 +13,10 @@
Two ways to use a machine's cores, with the same results:
-* ``solver_workers`` processes share one trial's subproblems (the
+* solver_workers processes share one trial's subproblems (the
default): the calling process reads each container, hands its
subproblems to the pool and writes the results, one trial after another;
-* ``trial_workers`` processes each solve a whole trial
+* trial_workers processes each solve a whole trial
(:func:`solve_trials`): reading, solving and writing all run in
parallel, which is several times faster on a workstation once the
containers exist. Each process holds one trial's container.
@@ -33,21 +33,25 @@
"work": 1.2e9}, ...],
"work": 5.0e9, "estimated_seconds": 4000.0}
-``span`` is ``[first, stop)`` in the container's subproblem order; names
+span is [first, stop) in the container's subproblem order; names
are relative to the containers' and results' folders given at run time.
"""
from __future__ import annotations
+import itertools
import json
import shutil
import time
+from collections.abc import Sequence
+from concurrent.futures import Executor, ProcessPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from dataclasses import asdict
from pathlib import Path
-from typing import Optional
+from typing import TYPE_CHECKING
import numpy as np
+import numpy.typing as npt
from ..models.params import SiloExecution, SiloParams
from .silo_session import (
@@ -60,6 +64,11 @@
stage_hash,
)
+if TYPE_CHECKING:
+ from ..extraction.raster.container import Container
+ from ..extraction.raster.solver import SolverOptions, SubproblemResult
+ from ..extraction.raster.solver_setup import SolverParams, Subproblem
+
JOB_FORMAT = "giant-silo-job"
JOB_VERSION = 1
@@ -67,15 +76,29 @@
"""Estimated solve time per unit of :func:`subproblem_work` for one solver
process of 4 threads on the CPU (780125 on a 16-core Threadripper: about
120 s per trial-path of 5.9e8 work with 4 such processes, the trial loader
-running beside them). A job's ``estimated_seconds`` is for one such
+running beside them). A job's estimated_seconds is for one such
process; P processes take about 1/P of it. A guide for shard sizes only."""
-def subproblem_work(n_pixels, n_sources, n_frames) -> np.ndarray:
- """Estimated cost of subproblems: pixels x frames x (sources + 1).
+def subproblem_work(n_pixels: npt.ArrayLike, n_sources: npt.ArrayLike, n_frames: int) -> np.ndarray:
+ """Return the estimated cost of subproblems: pixels x frames x (sources + 1).
The fits' arrays are pixels x frames, and the footprint and activity
fits grow with the sources.
+
+ Parameters
+ ----------
+ n_pixels : array-like
+ Pixels of each subproblem.
+ n_sources : array-like
+ Sources of each subproblem.
+ n_frames : int
+ Frames of the trial.
+
+ Returns
+ -------
+ np.ndarray
+ The estimated cost of each subproblem.
"""
return (
np.asarray(n_pixels, np.float64)
@@ -84,18 +107,44 @@ def subproblem_work(n_pixels, n_sources, n_frames) -> np.ndarray:
)
-def effective_batch(options) -> Optional[float]:
- """The batch size the solver uses: ``batch_bytes``, or on a GPU its
- default of 2e8 (``solve_subproblems``); None (one subproblem at a time)
+def effective_batch(options: SolverOptions) -> float | None:
+ """Return the batch size the solver uses.
+
+ This is batch_bytes, or on a GPU its
+ default of 2e8 (solve_subproblems); None (one subproblem at a time)
on the CPU. Subproblems are batched exactly when this is not None,
- whatever the number of processes."""
+ whatever the number of processes.
+
+ Parameters
+ ----------
+ options : SolverOptions
+ How the fits run.
+
+ Returns
+ -------
+ float or None
+ The batch size in bytes; None on the CPU without batch_bytes.
+ """
if options.batch_bytes is not None:
return float(options.batch_bytes)
return None if str(options.device).split(":")[0] == "cpu" else 2e8
-def _solve_record(params: SiloParams, options) -> dict:
- """What a results file depends on besides its container and range."""
+def _solve_record(params: SiloParams, options: SolverOptions) -> dict:
+ """Return what a results file depends on besides its container and range.
+
+ Parameters
+ ----------
+ params : SiloParams
+ Scientific settings.
+ options : SolverOptions
+ How the fits run.
+
+ Returns
+ -------
+ dict
+ The solve stage's settings and the solver's options.
+ """
return {
"stage": "solve",
"settings": params.stage_settings("solve"),
@@ -111,28 +160,81 @@ def _solve_record(params: SiloParams, options) -> dict:
}
-def solve_settings(params: SiloParams, options) -> str:
- """Hash of how subproblems are solved (the same for every results file
- of one run; recorded as ``solve_settings``)."""
+def solve_settings(params: SiloParams, options: SolverOptions) -> str:
+ """Return the hash of how subproblems are solved.
+
+ It is the same for every results file
+ of one run; recorded as solve_settings.
+
+ Parameters
+ ----------
+ params : SiloParams
+ Scientific settings.
+ options : SolverOptions
+ How the fits run.
+
+ Returns
+ -------
+ str
+ The settings hash.
+ """
return stage_hash(_solve_record(params, options))
-def solve_hash(params: SiloParams, options, container_hash: str, span) -> str:
- """Settings hash of a results file: how, which container, which
- subproblems."""
- return stage_hash(
- {
- **_solve_record(params, options),
- "container": container_hash,
- "span": [int(span[0]), int(span[1])],
- }
- )
+def solve_hash(
+ params: SiloParams, options: SolverOptions, container_hash: str, span: tuple[int, int]
+) -> str:
+ """Return the settings hash of a results file.
+
+ It covers how, which container, which
+ subproblems.
+
+ Parameters
+ ----------
+ params : SiloParams
+ Scientific settings.
+ options : SolverOptions
+ How the fits run.
+ container_hash : str
+ The container's settings hash.
+ span : tuple of int
+ The subproblems (first, stop).
+
+ Returns
+ -------
+ str
+ The settings hash.
+ """
+ return stage_hash({
+ **_solve_record(params, options),
+ "container": container_hash,
+ "span": [int(span[0]), int(span[1])],
+ })
+
+
+def with_f0_frames(
+ subs: list[Subproblem], discard: npt.ArrayLike, params: SiloParams
+) -> list[Subproblem]:
+ """Give a trial's subproblems the frames their F0 images average.
+
+ The frames come from
+ :func:`~giant_python.extraction.raster.solver_setup.f0_image_frames`,
+ when the run makes F0 images (params.f0_im_trim_s).
+ Parameters
+ ----------
+ subs : list of Subproblem
+ The trial's subproblems; modified in place.
+ discard : array-like
+ The trial's discarded frames.
+ params : SiloParams
+ Scientific settings.
-def with_f0_frames(subs: list, discard, params: SiloParams) -> list:
- """Give a trial's subproblems the frames their F0 images average
- (:func:`~giant_python.extraction.raster.solver_setup.f0_image_frames`),
- when the run makes F0 images (``params.f0_im_trim_s``)."""
+ Returns
+ -------
+ list of Subproblem
+ subs.
+ """
from ..extraction.raster.solver_setup import f0_image_frames
if params.f0_im_trim_s is None or not subs:
@@ -143,20 +245,56 @@ def with_f0_frames(subs: list, discard, params: SiloParams) -> list:
return subs
-def _solve_one(sub, params, options):
- """Solve one subproblem (a pool task)."""
+def _solve_one(sub: Subproblem, params: SolverParams, options: SolverOptions) -> SubproblemResult:
+ """Solve one subproblem (a pool task).
+
+ Parameters
+ ----------
+ sub : Subproblem
+ The subproblem.
+ params : SolverParams
+ The solver's parameters.
+ options : SolverOptions
+ How the fits run.
+
+ Returns
+ -------
+ SubproblemResult
+ The subproblem's solution.
+ """
from ..extraction.raster.solver import solve_subproblem
return solve_subproblem(sub, params, options)
-def solve_subproblem_list(subs, params, options, pool=None) -> list:
+def solve_subproblem_list(
+ subs: Sequence[Subproblem],
+ params: SolverParams,
+ options: SolverOptions,
+ pool: Executor | None = None,
+) -> list[SubproblemResult]:
"""Solve subproblems, in a pool if given; results in input order.
When the solver batches (:func:`effective_batch`: always on a GPU)
they are solved together here, with or without a pool, so the results
do not depend on the number of processes. Larger subproblems are
submitted first.
+
+ Parameters
+ ----------
+ subs : sequence of Subproblem
+ The subproblems.
+ params : SolverParams
+ The solver's parameters.
+ options : SolverOptions
+ How the fits run.
+ pool : Executor, optional
+ Workers to solve the subproblems in.
+
+ Returns
+ -------
+ list of SubproblemResult
+ The solutions, in the order of subs.
"""
from ..extraction.raster.solver import solve_subproblems
@@ -168,38 +306,75 @@ def solve_subproblem_list(subs, params, options, pool=None) -> list:
[-s.n_pixels * s.n_frames * (s.n_sources + 1) for s in subs],
kind="stable",
)
- futures = {
- int(i): pool.submit(_solve_one, subs[i], params, options)
- for i in order
- }
+ futures = {int(i): pool.submit(_solve_one, subs[i], params, options) for i in order}
return [futures[i].result() for i in range(len(subs))]
def solve_science(params: SiloParams) -> str:
- """Hash of the scientific solve settings alone (recorded as
- ``solve_science``; the collect stage checks it against its own)."""
+ """Return the hash of the scientific solve settings alone.
+
+ It is recorded as
+ solve_science; the collect stage checks it against its own.
+
+ Parameters
+ ----------
+ params : SiloParams
+ Scientific settings.
+
+ Returns
+ -------
+ str
+ The settings hash.
+ """
return stage_hash({"solve": params.stage_settings("solve")})
def results_attrs(
- container,
+ container: object,
name: str,
container_hash: str,
- span,
- n_sub,
- extracted,
- h,
+ span: tuple[int, int],
+ n_sub: int,
+ extracted: bool,
+ h: str,
params: SiloParams,
- options,
+ options: SolverOptions,
) -> dict:
- """Attributes of a results file.
+ """Return the attributes of a results file.
Besides the settings hash and the container's identity it records
- ``solve_settings`` (:func:`solve_settings`), ``solve_science``
- (:func:`solve_science`) and ``plan_hash`` (the plan the container was
+ solve_settings (:func:`solve_settings`), solve_science
+ (:func:`solve_science`) and plan_hash (the plan the container was
made from), which the collect stage checks, and, when the solver used
- the container's network baseline (a ``baseline_mode`` other than
- 'fit'), ``network_baseline`` (JSON: its identity).
+ the container's network baseline (a baseline_mode other than
+ 'fit'), network_baseline (JSON: its identity).
+
+ Parameters
+ ----------
+ container : object
+ The container, or a view of it, with source, params,
+ pixel_rc, sources_rc and photon_scale.
+ name : str
+ The container's file name.
+ container_hash : str
+ The container's settings hash.
+ span : tuple of int
+ The subproblems solved, (first, stop).
+ n_sub : int
+ Subproblems of the container.
+ extracted : bool
+ Whether the trial is extracted (long enough).
+ h : str
+ The results file's settings hash.
+ params : SiloParams
+ Scientific settings.
+ options : SolverOptions
+ How the fits run.
+
+ Returns
+ -------
+ dict
+ The attributes to write.
"""
src = getattr(container, "source", {}) or {}
cparams = getattr(container, "params", {}) or {}
@@ -207,9 +382,7 @@ def results_attrs(
extra = {}
if cparams.get("baseline") and params.baseline_mode != "fit":
# only a baseline the solver used ('fit' ignores the container's)
- extra["network_baseline"] = json.dumps(
- cparams["baseline"], sort_keys=True
- )
+ extra["network_baseline"] = json.dumps(cparams["baseline"], sort_keys=True)
return {
"settings_hash": h,
"solve_settings": solve_settings(params, options),
@@ -229,10 +402,27 @@ def results_attrs(
}
-def check_container(container, params: SiloParams, name: str) -> None:
- """Refuse to solve a container with other baseline settings or another
+def check_container(container: Container, params: SiloParams, name: str) -> None:
+ """Refuse a container prepared for other settings.
+
+ A container with other baseline settings or another
footprint support than it was prepared for, or without the baseline
- the solver's mode needs."""
+ the solver's mode needs, is refused.
+
+ Parameters
+ ----------
+ container : Container
+ The container.
+ params : SiloParams
+ Scientific settings.
+ name : str
+ The container's name, for the error message.
+
+ Raises
+ ------
+ ValueError
+ If the container does not fit params.
+ """
used = (container.params or {}).get("baseline_source", "median")
if used != params.baseline_source:
raise ValueError(
@@ -265,14 +455,14 @@ def check_container(container, params: SiloParams, name: str) -> None:
def solve_container(
- container_path,
- out_path,
+ container_path: str | Path,
+ out_path: str | Path,
params: SiloParams,
- options,
- span=None,
- pool=None,
+ options: SolverOptions,
+ span: tuple[int, int] | None = None,
+ pool: Executor | None = None,
overwrite: bool = False,
-) -> Optional[dict]:
+) -> dict | None:
"""Solve subproblems of one container into a results file.
Parameters
@@ -286,7 +476,7 @@ def solve_container(
options : SolverOptions
How the fits run.
span : (int, int), optional
- Subproblems ``first`` to ``stop - 1`` (default: all).
+ Subproblems first to stop - 1 (default: all).
pool : Executor, optional
Workers to solve subproblems in.
overwrite : bool
@@ -295,7 +485,12 @@ def solve_container(
Returns
-------
dict or None
- ``seconds`` and the number solved; None if skipped (up to date).
+ seconds and the number solved; None if skipped (up to date).
+
+ Raises
+ ------
+ ValueError
+ If span is outside the container's subproblems.
"""
from ..extraction.raster.container import read_container
from ..extraction.raster.results import (
@@ -322,9 +517,7 @@ def solve_container(
if extracted and span[1] > span[0]:
c = read_container(container_path, data=True)
idx = list(range(*span))
- subs = with_f0_frames(
- [c.subproblem(k, sp) for k in idx], c.discard, params
- )
+ subs = with_f0_frames([c.subproblem(k, sp) for k in idx], c.discard, params)
results = solve_subproblem_list(subs, sp, options, pool)
out_path.parent.mkdir(parents=True, exist_ok=True)
write_results(
@@ -346,8 +539,18 @@ def solve_container(
return {"seconds": time.perf_counter() - t0, "solved": len(subs)}
-def _dispose(container: Path, archive, *, remove: bool = False) -> None:
- """Remove or archive a solved container if requested."""
+def _dispose(container: Path, archive: str | Path | None, *, remove: bool = False) -> None:
+ """Remove or archive a solved container if requested.
+
+ Parameters
+ ----------
+ container : Path
+ The solved container.
+ archive : str or Path, optional
+ The folder to move the container to; None to leave it.
+ remove : bool
+ Delete the container (instead of archiving it).
+ """
if remove:
container.unlink(missing_ok=True)
elif archive is not None:
@@ -357,15 +560,25 @@ def _dispose(container: Path, archive, *, remove: bool = False) -> None:
shutil.move(str(container), str(folder / container.name))
-def _solve_container_job(job: dict) -> Optional[dict]:
- """Solve one container's subproblems in this process (a task of
- :func:`solve_trials`' pool, whose workers have the solver's threads).
+def _solve_container_job(job: dict) -> dict | None:
+ """Solve one container's subproblems in this process.
+
+ This is a task of :func:`solve_trials`' pool, whose workers have the
+ solver's threads.
+
+ Parameters
+ ----------
+ job : dict
+ container, results, params (SiloParams),
+ options (SolverOptions), span, overwrite, then
+ (archive folder), and remove
+ (:func:`_dispose`, applied once the results file is written or found
+ up to date).
- ``job``: ``container``, ``results``, ``params`` (SiloParams),
- ``options`` (SolverOptions), ``span``, ``overwrite``, ``then`` (archive
- folder), and ``remove``
- (:func:`_dispose`, applied once the results file is written or found
- up to date).
+ Returns
+ -------
+ dict or None
+ :func:`solve_container`'s return value.
"""
container = Path(job["container"])
done = solve_container(
@@ -381,28 +594,39 @@ def _solve_container_job(job: dict) -> Optional[dict]:
return done
-def trial_pool(execution: SiloExecution, tasks: int):
- """A pool of ``execution.trial_workers`` processes (at most
- ``tasks``) of ``solver_threads`` threads each, for
- :func:`_solve_container_job`."""
- return make_pool(
- max(1, min(execution.trial_workers, tasks)), execution.solver_threads
- )
+def trial_pool(execution: SiloExecution, tasks: int) -> ProcessPoolExecutor:
+ """Return a pool of execution.trial_workers processes.
+
+ There are at most tasks of them, of solver_threads threads each,
+ for :func:`_solve_container_job`.
+
+ Parameters
+ ----------
+ execution : SiloExecution
+ trial_workers and solver_threads.
+ tasks : int
+ The number of tasks to run.
+
+ Returns
+ -------
+ concurrent.futures.ProcessPoolExecutor
+ The started pool.
+ """
+ return make_pool(max(1, min(execution.trial_workers, tasks)), execution.solver_threads)
def solve_trials(
tasks: list,
params: SiloParams,
- options,
+ options: SolverOptions,
execution: SiloExecution,
- then=None,
+ then: str | Path | None = None,
) -> list:
- """Solve containers ``execution.trial_workers`` at a time, each whole
- in its own process.
+ """Solve containers execution.trial_workers at a time, each whole in its own process.
Every process reads its container, solves its subproblems one after
- another with ``execution.solver_threads`` threads and writes the
- results file: the same solves as a pool of ``solver_workers``
+ another with execution.solver_threads threads and writes the
+ results file: the same solves as a pool of solver_workers
processes sharing one trial's subproblems, without the calling process
reading and writing every trial in turn.
@@ -410,12 +634,12 @@ def solve_trials(
----------
tasks : list of (Path, Path, span)
Per task: the container, the results file, and the subproblem
- range ``(first, stop)`` or None for all.
+ range (first, stop) or None for all.
params : SiloParams
options : SolverOptions
execution : SiloExecution
- ``trial_workers`` processes of ``solver_threads`` threads;
- ``overwrite``.
+ trial_workers processes of solver_threads threads;
+ overwrite.
then : str or Path, optional
Where to archive each container once solved (:func:`_dispose`).
@@ -423,17 +647,22 @@ def solve_trials(
-------
list
Per task, in order: :func:`solve_container`'s return value.
- """
+
+ Raises
+ ------
+ ValueError
+ If then is the results directory of a task.
+ RuntimeError
+ If a worker process ended without a result (:func:`pool_failure`).
+ pool_failure
+ The error :func:`pool_failure` builds, which is the RuntimeError above.
+ """ # noqa: DOC502
if not tasks:
return []
if then is not None:
then = Path(then).resolve()
- if any(
- then == Path(results).parent.resolve() for _, results, _ in tasks
- ):
- raise ValueError(
- "cannot archive containers in the results directory"
- )
+ if any(then == Path(results).parent.resolve() for _, results, _ in tasks):
+ raise ValueError("cannot archive containers in the results directory")
pool = None
try:
pool = trial_pool(execution, len(tasks))
@@ -462,7 +691,24 @@ def solve_trials(
def _containers(session: SiloSession) -> list:
- """Containers of the session's planned, valid trial-paths."""
+ """Return the containers of the session's planned, valid trial-paths.
+
+ Parameters
+ ----------
+ session : SiloSession
+ The session.
+
+ Returns
+ -------
+ list
+ ((d, t), container file) per trial-path, in path and trial
+ order.
+
+ Raises
+ ------
+ FileNotFoundError
+ If a planned trial-path has no container.
+ """
from .silo import _valid_units
out = []
@@ -479,8 +725,20 @@ def _containers(session: SiloSession) -> list:
def _partition(costs: np.ndarray, n: int) -> list:
- """Cut a sequence into at most ``n`` contiguous parts of about equal
- total cost; returns the parts' ``[start, stop)``."""
+ """Cut a sequence into at most n contiguous parts of about equal total cost.
+
+ Parameters
+ ----------
+ costs : np.ndarray
+ The cost of each element.
+ n : int
+ The most parts.
+
+ Returns
+ -------
+ list
+ The parts' (start, stop) ranges ([start, stop)).
+ """
total = float(costs.sum())
if costs.size == 0:
return []
@@ -500,19 +758,19 @@ def _partition(costs: np.ndarray, n: int) -> list:
break
edges.append(cut)
edges.append(costs.size)
- return list(zip(edges[:-1], edges[1:]))
+ return list(itertools.pairwise(edges))
def dispatch(
session: SiloSession,
params: SiloParams,
machines: int,
- execution: Optional[SiloExecution] = None,
+ execution: SiloExecution | None = None,
) -> list:
"""Write job files: shards of about equal estimated work.
The session's subproblems (containers in path and trial order, each
- container's in its order) are cut into ``machines`` contiguous parts
+ container's in its order) are cut into machines contiguous parts
of about equal :func:`subproblem_work`; each part is a job, holding a
range of subproblems of each container it touches. Earlier job files
in the folder are removed.
@@ -530,6 +788,11 @@ def dispatch(
-------
list of Path
The job files.
+
+ Raises
+ ------
+ ValueError
+ If machines is below 1.
"""
from ..extraction.raster.container import read_container
@@ -566,23 +829,17 @@ def dispatch(
items[-1]["work"] += w
continue
span = [0, n_sub] if k is None else [k, k + 1]
- items.append(
- {
- "container": f.name,
- "container_hash": h,
- "span": span,
- "work": w,
- }
- )
+ items.append({
+ "container": f.name,
+ "container_hash": h,
+ "span": span,
+ "work": w,
+ })
for it in items:
whole = it["span"] == [0, _n_sub(entries, it["container"])]
it["results"] = (
Path(it["container"]).stem
- + (
- ""
- if whole
- else "_s%04d-%04d" % (it["span"][0], it["span"][1] - 1)
- )
+ + ("" if whole else "_s%04d-%04d" % (it["span"][0], it["span"][1] - 1))
+ ".h5"
)
work = sum(it["work"] for it in items)
@@ -608,32 +865,59 @@ def dispatch(
def _n_sub(entries: list, name: str) -> int:
- """Subproblems of a container in the dispatch list."""
+ """Return the subproblems of a container in the dispatch list.
+
+ Parameters
+ ----------
+ entries : list
+ The dispatch list's (file, hash, n_sub, k, work) entries.
+ name : str
+ The container's file name.
+
+ Returns
+ -------
+ int
+ The container's number of subproblems; 0 if it is not listed.
+ """
for f, _, n_sub, _, _ in entries:
if f.name == name:
return n_sub
return 0
-def read_job(path) -> dict:
- """Read and check a job file."""
+def read_job(path: str | Path) -> dict:
+ """Read and check a job file.
+
+ Parameters
+ ----------
+ path : str or Path
+ The job file.
+
+ Returns
+ -------
+ dict
+ The job (see the module docstring).
+
+ Raises
+ ------
+ ValueError
+ If the file is not a SILo job file or its format is newer.
+ """
job = json.loads(Path(path).read_text(encoding="utf-8"))
if job.get("format") != JOB_FORMAT:
raise ValueError(f"{path} is not a SILo job file")
if int(job.get("format_version", 0)) > JOB_VERSION:
- raise ValueError(
- f"{path}: job format {job['format_version']} is newer"
- )
+ raise ValueError(f"{path}: job format {job['format_version']} is newer")
return job
def solve_job(
- job_file,
- containers_dir=None,
- results_dir=None,
- execution: Optional[SiloExecution] = None,
+ job_file: str | Path,
+ containers_dir: str | Path | None = None,
+ results_dir: str | Path | None = None,
+ execution: SiloExecution | None = None,
) -> dict:
- """Run one job file (stage ``solve`` on one machine).
+ """Run one job file (stage solve on one machine).
Parameters
----------
@@ -641,11 +925,11 @@ def solve_job(
The job.
containers_dir, results_dir : str or Path, optional
Where the containers are and the results go (default: the job
- folder's siblings ``containers`` and ``results``).
+ folder's siblings containers and results).
execution : SiloExecution, optional
Processes and threads to solve with (the job's device, precision
- and batch size are used): ``solver_workers`` processes sharing
- each item's subproblems, or, with ``trial_workers`` above 0, that
+ and batch size are used): solver_workers processes sharing
+ each item's subproblems, or, with trial_workers above 0, that
many processes solving one item each (:func:`solve_trials`).
Returns
@@ -698,21 +982,48 @@ def solve_job(
def _check_job_container(f: Path, item: dict) -> None:
- """Refuse a container that is not the one the job's item names."""
+ """Refuse a container that is not the one the job's item names.
+
+ Parameters
+ ----------
+ f : Path
+ The container file.
+ item : dict
+ The job's item.
+
+ Raises
+ ------
+ ValueError
+ If the container's settings hash is not the item's.
+ """
if attr(f, "settings_hash") != item["container_hash"]:
- raise ValueError(
- f"{f} is not the container the job was made for "
- "(settings hash differs)"
- )
+ raise ValueError(f"{f} is not the container the job was made for (settings hash differs)")
def solve_containers(
session: SiloSession,
params: SiloParams,
- execution: Optional[SiloExecution] = None,
+ execution: SiloExecution | None = None,
) -> dict:
- """Solve every container of a session here, one results file each
- (``execution.trial_workers`` trials at a time when it is above 0)."""
+ """Solve every container of a session here, one results file each.
+
+ This runs execution.trial_workers trials at a time when that is
+ above 0.
+
+ Parameters
+ ----------
+ session : SiloSession
+ The session.
+ params : SiloParams
+ Scientific settings.
+ execution : SiloExecution, optional
+ Processes and threads to solve with.
+
+ Returns
+ -------
+ dict
+ Per container file name: :func:`solve_container`'s return value.
+ """
ex = execution or SiloExecution()
options = ex.solver_options()
done = {}
@@ -743,10 +1054,24 @@ def solve_containers(
return done
-def _pool(ex: SiloExecution, options):
- """A pool of solver processes, or None to solve here (one process
- asked for, or batches), with this process's threads set to
- ``solver_threads`` then."""
+def _pool(ex: SiloExecution, options: SolverOptions) -> ProcessPoolExecutor | None:
+ """Return a pool of solver processes, or None to solve here.
+
+ None is returned when one process is asked for, or batches; this
+ process's threads are then set to solver_threads.
+
+ Parameters
+ ----------
+ ex : SiloExecution
+ Processes and threads to solve with.
+ options : SolverOptions
+ How the fits run.
+
+ Returns
+ -------
+ concurrent.futures.ProcessPoolExecutor or None
+ The pool; None to solve in this process.
+ """
if ex.solver_workers > 1 and effective_batch(options) is None:
return make_pool(ex.solver_workers, ex.solver_threads)
thread_env(ex.solver_threads)
@@ -762,5 +1087,10 @@ def thread_env(threads: int) -> None:
oversubscribe a 64-core machine several times over).
:func:`~giant_python.pipeline.silo_session.set_threads` also limits
the libraries already loaded.
+
+ Parameters
+ ----------
+ threads : int
+ The thread count.
"""
set_threads(threads)
diff --git a/src/giant_python/pipeline/silo_spots.py b/src/giant_python/pipeline/silo_spots.py
index cd1fac4d..c8ee0aa7 100644
--- a/src/giant_python/pipeline/silo_spots.py
+++ b/src/giant_python/pipeline/silo_spots.py
@@ -4,27 +4,27 @@
Run by :func:`~giant_python.pipeline.silo_collect.collect` after the
summaries are written: the kept sources of each path are grouped into spots
-(linked within ``spot_link_px``), each multi-source spot gets its sources'
+(linked within spot_link_px), each multi-source spot gets its sources'
event-train correlation and, from the registered movies, the event test, and
-``experiment_summary.h5`` gets per path (sizes as MATLAB's ``size()`` and
+experiment_summary.h5 gets per path (sizes as MATLAB's size() and
the README give them; this column-major file's h5py shapes are reversed,
1 x kept sources and 1 x spots):
-* ``sources/spatial/spot_id`` (kept sources x 1): each source's spot
+* sources/spatial/spot_id (kept sources x 1): each source's spot
(one-based);
-* ``sources/spots/`` (spots x 1 each): ``label`` (int8, an index into the
- group's ``labels`` attribute,
+* sources/spots/ (spots x 1 each): label (int8, an index into the
+ group's labels attribute,
:data:`~giant_python.extraction.raster.spots.LABELS`),
- ``n_sources``, ``event_corr``, ``n_events``, ``K``, ``power``,
- ``cloud_major_px``, ``cloud_minor_px``, ``bic_gain``, ``center_row``,
- ``center_col``
- (zero-based canvas); the group's ``settings`` attribute holds the settings
+ n_sources, event_corr, n_events, K, power,
+ cloud_major_px, cloud_minor_px, bic_gain, center_row,
+ center_col
+ (zero-based canvas); the group's settings attribute holds the settings
(JSON).
The sources and their traces are not changed. The event test reads each
trial's registered movie at the spots' pixels only (frames in blocks), the
network baseline there (or, with the moving median, a running median of the
-pixels over ``baseline_window_s``), and SILo's motion discards.
+pixels over baseline_window_s), and SILo's motion discards.
"""
from __future__ import annotations
@@ -34,14 +34,17 @@
import math
import time
import warnings
+from collections.abc import Callable
+from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
-from typing import Optional
import h5py
import numpy as np
+import numpy.typing as npt
from scipy import ndimage
from ..extraction.raster import spots as sp
+from ..extraction.raster.alignment import TrialWarp
from ..extraction.raster.trial import discard_frames
from ..models.params import SiloParams
from .silo_session import SiloSession
@@ -51,7 +54,18 @@
def settings_of(params: SiloParams) -> sp.SpotSettings:
- """The spot settings of a run."""
+ """Return the spot settings of a run.
+
+ Parameters
+ ----------
+ params : SiloParams
+ The run's parameters.
+
+ Returns
+ -------
+ sp.SpotSettings
+ The spot annotation settings taken from params.
+ """
return sp.SpotSettings(
link_px=params.spot_link_px,
split_corr=params.spot_split_corr,
@@ -63,22 +77,59 @@ def settings_of(params: SiloParams) -> sp.SpotSettings:
def _read_pixels(
- path: Path, pages_per_frame: int, page0: int, rows, cols, n_frames=None
+ path: Path,
+ pages_per_frame: int,
+ page0: int,
+ rows: npt.ArrayLike,
+ cols: npt.ArrayLike,
+ n_frames: int | None = None,
) -> np.ndarray:
- """``(frames, pixels)`` float32 of a movie or baseline stored as
- ``(pages, MATLAB cols, MATLAB rows)`` (HDF5: its ``baseline`` dataset or
+ """Return (frames, pixels) float32 of a movie or baseline.
+
+ The movie or baseline is stored as
+ (pages, MATLAB cols, MATLAB rows) (HDF5: its baseline dataset or
the first one; TIFF: its pages, as SILo reads them), at the image
- pixels ``(rows, cols)``, NaN at pixels outside the image: page ``page0 +
- k * pages_per_frame`` is frame ``k``."""
+ pixels (rows, cols), NaN at pixels outside the image: page page0 +
+ k * pages_per_frame is frame k.
+
+ Parameters
+ ----------
+ path : Path
+ The movie or baseline file (HDF5 or TIFF).
+ pages_per_frame : int
+ Pages per frame.
+ page0 : int
+ Page of frame 0.
+ rows, cols : array_like
+ The image pixels to read.
+ n_frames : int, optional
+ Number of frames to read; all the file holds when None.
+
+ Returns
+ -------
+ np.ndarray
+ Float32 (frames, pixels) array, NaN at pixels outside the image.
+ """
rows = np.asarray(rows, dtype=np.int64)
cols = np.asarray(cols, dtype=np.int64)
- def take(blk, n_r, n_c):
- """The pixels of frames ``blk`` of an image ``n_r x n_c``."""
+ def take(blk: np.ndarray, n_r: int, n_c: int) -> np.ndarray:
+ """Return the pixels of frames blk of an image n_r x n_c.
+
+ Parameters
+ ----------
+ blk : np.ndarray
+ The frames' pages (pages, MATLAB cols, MATLAB rows).
+ n_r, n_c : int
+ Image rows and columns.
+
+ Returns
+ -------
+ np.ndarray
+ Float32 (frames, pixels) array, NaN at pixels outside the image.
+ """
inside = (rows >= 0) & (rows < n_r) & (cols >= 0) & (cols < n_c)
- v = blk[
- :, np.where(inside, cols, 0), np.where(inside, rows, 0)
- ].astype(np.float32)
+ v = blk[:, np.where(inside, cols, 0), np.where(inside, rows, 0)].astype(np.float32)
v[:, ~inside] = np.nan
return v
@@ -88,11 +139,7 @@ def take(blk, n_r, n_c):
if path.suffix == ".h5":
with h5py.File(path, "r") as f:
ds = f["baseline"] if "baseline" in f else f[next(iter(f.keys()))]
- n = (
- ds.shape[0] // pages_per_frame
- if n_frames is None
- else int(n_frames)
- )
+ n = ds.shape[0] // pages_per_frame if n_frames is None else int(n_frames)
n_c, n_r = ds.shape[1], ds.shape[2]
_check_pages(path, ds.shape[0], pages_per_frame, page0, n)
out = np.empty((n, rows.size), np.float32)
@@ -112,38 +159,92 @@ def take(blk, n_r, n_c):
# contiguous, or chunks of several pages: in blocks of pages
step = _BLOCK * pages_per_frame
for a in range(0, n * pages_per_frame, step):
- blk = np.asarray(ds[a : min(a + step, n * pages_per_frame)])[
- page0::pages_per_frame
- ]
+ blk = np.asarray(ds[a : min(a + step, n * pages_per_frame)])[page0::pages_per_frame]
k0 = a // pages_per_frame
out[k0 : k0 + blk.shape[0]] = take(blk, n_r, n_c)
return out
-def _page_chunks(ds) -> bool:
- """Whether each page of a dataset ``(pages, ...)`` is stored in chunks
- of its own (a registered movie written deflated): only then can the
+def _page_chunks(ds: h5py.Dataset) -> bool:
+ """Return whether each page of a dataset (pages, ...) is stored in chunks of its own.
+
+ That is, a registered movie written deflated: only then can the
pages of the other channels be skipped, reading one page decompressing
no other, so only then are the pages read one at a time. That saves
the other channels' decompression, which on the registered movies
outweighs the cost of one read per page; it need not on small pages.
With chunks of several pages, or none (contiguous), the other pages
- would be read anyway, and blocks of pages are read."""
+ would be read anyway, and blocks of pages are read.
+
+ Parameters
+ ----------
+ ds : h5py.Dataset
+ The dataset (pages, ...).
+
+ Returns
+ -------
+ bool
+ True when each page is stored in its own chunk.
+ """
return ds.chunks is not None and ds.chunks[0] == 1
-def _check_pages(path, n_pages, pages_per_frame, page0, n) -> None:
- """A file must hold every page of the ``n`` frames asked for."""
+def _check_pages(path: str | Path, n_pages: int, pages_per_frame: int, page0: int, n: int) -> None:
+ """Check that a file holds every page of the n frames asked for.
+
+ Parameters
+ ----------
+ path : str or Path
+ The file.
+ n_pages : int
+ Number of pages in the file.
+ pages_per_frame : int
+ Pages per frame.
+ page0 : int
+ Page of frame 0.
+ n : int
+ Number of frames asked for.
+
+ Raises
+ ------
+ ValueError
+ If the file has too few pages for n frames.
+ """
if n > 0 and page0 + (n - 1) * pages_per_frame >= n_pages:
- raise ValueError(
- f"{Path(path).name}: {n_pages} pages, too few for {n} frames"
- )
+ raise ValueError(f"{Path(path).name}: {n_pages} pages, too few for {n} frames")
+
+def _read_tiff_pixels(
+ path: Path,
+ pages_per_frame: int,
+ page0: int,
+ n_frames: int | None,
+ take: Callable[[np.ndarray, int, int], np.ndarray],
+) -> np.ndarray:
+ """Read :func:`_read_pixels` of a TIFF, one selected page at a time.
+
+ Pages are as :func:`~giant_python.extraction.raster.trial._read_tiff_pages` reads
+ them: one series or a series per page.
+
+ Parameters
+ ----------
+ path : Path
+ The TIFF file.
+ pages_per_frame : int
+ Pages per frame.
+ page0 : int
+ Page of frame 0.
+ n_frames : int or None
+ Number of frames to read; all the file holds when None.
+ take : callable
+ take(blk, n_r, n_c), the pixels of frames blk of an image
+ n_r x n_c.
-def _read_tiff_pixels(path, pages_per_frame, page0, n_frames, take):
- """:func:`_read_pixels` of a TIFF, one selected page at a time (pages
- as :func:`~giant_python.extraction.raster.trial._read_tiff_pages` reads
- them: one series or a series per page)."""
+ Returns
+ -------
+ np.ndarray
+ Float32 (frames, pixels) array; (0, 0) when no frame is read.
+ """
import tifffile
with tifffile.TiffFile(path) as tf:
@@ -162,8 +263,22 @@ def _read_tiff_pixels(path, pages_per_frame, page0, n_frames, take):
def _running_median(x: np.ndarray, window: int) -> np.ndarray:
- """Each pixel's running median over ``window`` frames (NaN filled from
- the nearest valid frame first)."""
+ """Return each pixel's running median over window frames.
+
+ NaN is filled from the nearest valid frame first.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ The pixels (frames, pixels).
+ window : int
+ Window length in frames.
+
+ Returns
+ -------
+ np.ndarray
+ Float64 (frames, pixels) array of running medians.
+ """
y = x.astype(np.float64)
for j in range(y.shape[1]):
v = y[:, j]
@@ -180,9 +295,33 @@ def _running_median(x: np.ndarray, window: int) -> np.ndarray:
return ndimage.median_filter(y, size=(w, 1), mode="nearest")
-def _to_canvas(warp, t: int, r_t, c_t, iters: int = 30):
- """Canvas position of trial-image positions (the inverse of
- ``warp.coords``, by fixed-point iteration)."""
+def _to_canvas(
+ warp: SummaryWarp | TrialWarp,
+ t: int,
+ r_t: npt.ArrayLike,
+ c_t: npt.ArrayLike,
+ iters: int = 30,
+) -> tuple[np.ndarray, np.ndarray]:
+ """Return the canvas position of trial-image positions.
+
+ This is the inverse of warp.coords, by fixed-point iteration.
+
+ Parameters
+ ----------
+ warp : SummaryWarp or TrialWarp
+ The across-trial maps.
+ t : int
+ Trial (zero-based).
+ r_t, c_t : array_like
+ Row and column positions in the trial's image.
+ iters : int
+ Number of fixed-point iterations at most.
+
+ Returns
+ -------
+ tuple of np.ndarray
+ The canvas rows and columns of the positions.
+ """
r = np.asarray(r_t, dtype=np.float64).copy()
c = np.asarray(c_t, dtype=np.float64).copy()
pr, pc = r.copy(), c.copy()
@@ -198,10 +337,37 @@ def _to_canvas(warp, t: int, r_t, c_t, iters: int = 30):
_MISSING = "missing" # a trial to test whose movie or baseline is missing
-def _trial_inputs(session, d, t, warp, baseline_dir):
- """Movie, baseline file (or None), frame rate and ``recNegErr`` of
- trial-path ``(d, t)``; None for a trial left out (excluded or without a
- map), :data:`_MISSING` without its movie or baseline."""
+def _trial_inputs(
+ session: SiloSession,
+ d: int,
+ t: int,
+ warp: SummaryWarp | TrialWarp,
+ baseline_dir: str | Path | None,
+) -> tuple[Path, Path | None, float, np.ndarray] | str | None:
+ """Return the movie, baseline file (or None), frame rate and recNegErr of trial-path.
+
+ The trial-path is (d, t).
+
+ Parameters
+ ----------
+ session : SiloSession
+ The session.
+ d : int
+ Path (zero-based).
+ t : int
+ Trial (zero-based).
+ warp : SummaryWarp or TrialWarp
+ The path's across-trial maps.
+ baseline_dir : str or Path or None
+ The network's baselines, or None for the moving median.
+
+ Returns
+ -------
+ tuple or str or None
+ (movie, baseline file or None, frame rate, recNegErr); None for a
+ trial left out (excluded or without a map), :data:`_MISSING` without
+ its movie or baseline.
+ """
from ..extraction.raster.baseline_map import baseline_file
if not session.keep[d, t] or t >= warp.n_trials or not warp.aligned[t]:
@@ -220,17 +386,35 @@ def _trial_inputs(session, d, t, warp, baseline_dir):
return movie, bfile, align_hz, rne
-def _windows(warp, t, spots, settings):
- """Each spot's centre in trial ``t``'s image and its window's pixels:
- ``(centres, slices, rows, cols)`` with ``rows[slices[j]]`` spot j's."""
+def _windows(
+ warp: SummaryWarp | TrialWarp,
+ t: int,
+ spots: list[dict],
+ settings: sp.SpotSettings,
+) -> tuple[list[tuple[float, float]], list[slice], np.ndarray, np.ndarray]:
+ """Return each spot's centre in trial t's image and its window's pixels.
+
+ Parameters
+ ----------
+ warp : SummaryWarp or TrialWarp
+ The path's across-trial maps.
+ t : int
+ Trial (zero-based).
+ spots : list of dict
+ The multi-source spots, each with center and extent.
+ settings : sp.SpotSettings
+ The spot settings.
+
+ Returns
+ -------
+ tuple
+ (centres, slices, rows, cols) with rows[slices[j]] spot j's.
+ """
centres, slices, rows, cols = [], [], [], []
i0 = 0
for s in spots:
rt, ct = (
- float(v)
- for v in warp.coords(
- t, np.array(s["center"][0]), np.array(s["center"][1])
- )
+ float(v) for v in warp.coords(t, np.array(s["center"][0]), np.array(s["center"][1]))
)
rad = s["extent"] + settings.trim_px + _MARGIN_PX
rr, cc = np.meshgrid(
@@ -248,13 +432,36 @@ def _windows(warp, t, spots, settings):
return centres, slices, np.concatenate(rows), np.concatenate(cols)
-def _delta_f(session, params, inputs, rows, cols):
- """The movie minus its baseline at the pixels ``(frames, pixels)``,
- NaN at SILo's motion discards and outside the image."""
+def _delta_f(
+ session: SiloSession,
+ params: SiloParams,
+ inputs: tuple[Path, Path | None, float, np.ndarray],
+ rows: np.ndarray,
+ cols: np.ndarray,
+) -> np.ndarray:
+ """Return the movie minus its baseline at the pixels (frames, pixels).
+
+ NaN at SILo's motion discards and outside the image.
+
+ Parameters
+ ----------
+ session : SiloSession
+ The session.
+ params : SiloParams
+ The run's parameters.
+ inputs : tuple
+ (movie, baseline file or None, frame rate, recNegErr), as
+ :func:`_trial_inputs` gives them.
+ rows, cols : np.ndarray
+ The pixels.
+
+ Returns
+ -------
+ np.ndarray
+ The movie minus its baseline, (frames, pixels).
+ """
movie, bfile, align_hz, rne = inputs
- x = _read_pixels(
- movie, session.num_channels, params.activity_channel - 1, rows, cols
- )
+ x = _read_pixels(movie, session.num_channels, params.activity_channel - 1, rows, cols)
n_frames = x.shape[0]
disc = discard_frames(
rne[:n_frames],
@@ -272,10 +479,34 @@ def _delta_f(session, params, inputs, rows, cols):
_KEYS = ("r", "c", "se_r", "se_c")
-def _trial_events(job):
- """Events (canvas positions and errors) of each spot in one trial, or
- what :func:`_trial_inputs` gives when it cannot be tested (a pool
- task)."""
+def _trial_events(
+ job: tuple[
+ SiloSession,
+ SiloParams,
+ sp.SpotSettings,
+ int,
+ int,
+ SummaryWarp | TrialWarp,
+ list[dict],
+ str | Path | None,
+ ],
+) -> list[dict[str, np.ndarray]] | str | None:
+ """Return the events (canvas positions and errors) of each spot in one trial.
+
+ Or what :func:`_trial_inputs` gives when it cannot be tested (a pool
+ task).
+
+ Parameters
+ ----------
+ job : tuple
+ (session, params, settings, d, t, warp, spots, baseline_dir).
+
+ Returns
+ -------
+ list of dict or str or None
+ Per spot the events r, c, se_r, se_c; None for a trial
+ left out, :data:`_MISSING` without its movie or baseline.
+ """
session, params, settings, d, t, warp, spots, baseline_dir = job
inputs = _trial_inputs(session, d, t, warp, baseline_dir)
if inputs is None or inputs is _MISSING:
@@ -293,29 +524,54 @@ def _trial_events(job):
s["extent"] + settings.trim_px,
settings,
)
- r, c = (
- _to_canvas(warp, t, ev["r"], ev["c"])
- if ev["r"].size
- else (ev["r"], ev["c"])
- )
+ r, c = _to_canvas(warp, t, ev["r"], ev["c"]) if ev["r"].size else (ev["r"], ev["c"])
out.append(dict(zip(_KEYS, (r, c, ev["se_r"], ev["se_c"]))))
return out
def _spot_events(
- session,
- params,
- settings,
- d,
- warp,
- spots,
- baseline_dir,
- verbose,
- pool=None,
-):
- """Events (canvas positions and errors) of each multi-source spot of
- path ``d`` (zero-based), from every trial that can be tested (the
- trials in ``pool`` when given; the result does not depend on it)."""
+ session: SiloSession,
+ params: SiloParams,
+ settings: sp.SpotSettings,
+ d: int,
+ warp: SummaryWarp | TrialWarp,
+ spots: list[dict],
+ baseline_dir: str | Path | None,
+ verbose: bool,
+ pool: ProcessPoolExecutor | None = None,
+) -> list[dict[str, np.ndarray]]:
+ """Return the events (canvas positions and errors) of each multi-source spot of path d.
+
+ Path d is zero-based; the events are from every trial that can be tested (the
+ trials in pool when given; the result does not depend on it).
+
+ Parameters
+ ----------
+ session : SiloSession
+ The session.
+ params : SiloParams
+ The run's parameters.
+ settings : sp.SpotSettings
+ The spot settings.
+ d : int
+ Path (zero-based).
+ warp : SummaryWarp or TrialWarp
+ The path's across-trial maps.
+ spots : list of dict
+ The multi-source spots, each with center and extent.
+ baseline_dir : str or Path or None
+ The network's baselines, or None for the moving median.
+ verbose : bool
+ Print progress per trial.
+ pool : ProcessPoolExecutor, optional
+ Executor to test the trials in.
+
+ Returns
+ -------
+ list of dict
+ Per spot the events r, c, se_r, se_c (all trials), as
+ float arrays.
+ """
jobs = [
(session, params, settings, d, t, warp, spots, baseline_dir)
for t in range(session.n_trials)
@@ -348,21 +604,37 @@ def _spot_events(
class SummaryWarp:
- """The across-trial maps a summary records (``frame_info``), with
+ """The across-trial maps a summary records (frame_info).
+
+ They come with
:class:`~giant_python.extraction.raster.alignment.TrialWarp`'s
- ``coords``: zero-based canvas pixel ``(r, c)`` lies at ``A @ [r, c, 1]``
- in the trial (``trial_alignment_affine``), or at ``(r, c)`` plus the
- displacement field there (``trial_alignment_displacement``, bilinear,
- edge values beyond it)."""
+ coords: zero-based canvas pixel (r, c) lies at A @ [r, c, 1]
+ in the trial (trial_alignment_affine), or at (r, c) plus the
+ displacement field there (trial_alignment_displacement, bilinear,
+ edge values beyond it).
+ """
- def __init__(self, affine: np.ndarray, field=None) -> None:
- """Maps ``(trials, 2, 3)`` and fields ``(trials, 2, rows, cols)``."""
+ def __init__(self, affine: np.ndarray, field: npt.ArrayLike | None = None) -> None:
+ """Store maps (trials, 2, 3) and fields (trials, 2, rows, cols)."""
self.affine = np.asarray(affine, np.float64).reshape(-1, 2, 3)
self.field = None if field is None else np.asarray(field, np.float64)
@classmethod
- def read(cls, summary, name: str) -> Optional["SummaryWarp"]:
- """A path's maps from ``experiment_summary.h5`` (None without)."""
+ def read(cls, summary: str | Path, name: str) -> SummaryWarp | None:
+ """Read a path's maps from experiment_summary.h5 (None without).
+
+ Parameters
+ ----------
+ summary : str or Path
+ The experiment_summary.h5 file.
+ name : str
+ The path's group, e.g. Path1.
+
+ Returns
+ -------
+ SummaryWarp or None
+ The path's maps, or None when the summary records none.
+ """
with h5py.File(summary, "r") as f:
fi = f"{name}/frame_info"
if f"{fi}/trial_alignment_affine" not in f:
@@ -387,18 +659,29 @@ def aligned(self) -> np.ndarray:
return np.isfinite(self.field.reshape(self.n_trials, -1)).all(1)
return np.isfinite(self.affine.reshape(self.n_trials, -1)).all(1)
- def coords(self, trial: int, rows, cols):
- """Trial-image positions of canvas positions."""
+ def coords(
+ self, trial: int, rows: npt.ArrayLike, cols: npt.ArrayLike
+ ) -> tuple[np.ndarray, np.ndarray]:
+ """Return the trial-image positions of canvas positions.
+
+ Parameters
+ ----------
+ trial : int
+ Trial (zero-based).
+ rows, cols : array_like
+ Canvas rows and columns.
+
+ Returns
+ -------
+ tuple of np.ndarray
+ The rows and columns of the positions in the trial's image.
+ """
r = np.asarray(rows, np.float64)
c = np.asarray(cols, np.float64)
if self.field is not None:
f = self.field[trial]
- fr = ndimage.map_coordinates(
- f[0], [np.ravel(r), np.ravel(c)], order=1, mode="nearest"
- )
- fc = ndimage.map_coordinates(
- f[1], [np.ravel(r), np.ravel(c)], order=1, mode="nearest"
- )
+ fr = ndimage.map_coordinates(f[0], [np.ravel(r), np.ravel(c)], order=1, mode="nearest")
+ fc = ndimage.map_coordinates(f[1], [np.ravel(r), np.ravel(c)], order=1, mode="nearest")
return r + fr.reshape(r.shape), c + fc.reshape(c.shape)
a = self.affine[trial]
return (
@@ -407,22 +690,58 @@ def coords(self, trial: int, rows, cols):
)
-def _event_test_job(job):
- """One spot's event test (a pool task)."""
+def _event_test_job(job: tuple[dict, np.ndarray, sp.SpotSettings, int]) -> dict:
+ """Run one spot's event test (a pool task).
+
+ Parameters
+ ----------
+ job : tuple
+ (events, source_rc, settings, seed).
+
+ Returns
+ -------
+ dict
+ The event test of :func:`~giant_python.extraction.raster.spots.event_test`.
+ """
events, source_rc, settings, seed = job
return sp.event_test(events, source_rc, settings, seed=seed)
-def _event_tests(jobs: list, pool=None) -> list:
- """The spots' event tests, in ``pool`` when given (the results do not
- depend on it: each spot has its own seed)."""
+def _event_tests(jobs: list, pool: ProcessPoolExecutor | None = None) -> list:
+ """Return the spots' event tests, in pool when given.
+
+ The results do not depend on it: each spot has its own seed.
+
+ Parameters
+ ----------
+ jobs : list
+ The spots' jobs, as :func:`_event_test_job` takes them.
+ pool : ProcessPoolExecutor, optional
+ Executor to run the tests in.
+
+ Returns
+ -------
+ list
+ Per job its event test (a dict).
+ """
if pool is None or len(jobs) < 2:
return [_event_test_job(j) for j in jobs]
return list(pool.map(_event_test_job, jobs, chunksize=2))
-def _pool(workers: int):
- """Spawned worker processes, or None for one."""
+def _pool(workers: int) -> ProcessPoolExecutor | None:
+ """Return spawned worker processes, or None for one.
+
+ Parameters
+ ----------
+ workers : int
+ Number of worker processes.
+
+ Returns
+ -------
+ ProcessPoolExecutor or None
+ The pool, or None when workers is 1 or less.
+ """
if int(workers) <= 1:
return None
import multiprocessing
@@ -443,13 +762,41 @@ def _pool(workers: int):
)
-def _recorded_run(summary, params: SiloParams):
- """``params`` with the signal settings the summary's run recorded
- (:data:`_RECORDED`), and whether that run used the network's baselines
- (``localizationBaseline``, ``baselineMode``); the spot settings stay."""
+def _recorded_run(summary: str | Path, params: SiloParams) -> tuple[SiloParams, bool]:
+ """Return params with the signal settings the summary's run recorded.
+
+ The settings are :data:`_RECORDED`; also returned is whether that run used the network's
+ baselines (localizationBaseline, baselineMode); the spot settings stay.
+
+ Parameters
+ ----------
+ summary : str or Path
+ The experiment_summary.h5 file.
+ params : SiloParams
+ The parameters to start from.
- def value(g, key):
- """A recorded scalar, or None."""
+ Returns
+ -------
+ tuple
+ (params, network): the parameters with the recorded signal
+ settings, and whether the run used the network's baselines.
+ """
+
+ def value(g: h5py.Group | None, key: str) -> str | np.generic | None:
+ """Return a recorded scalar, or None.
+
+ Parameters
+ ----------
+ g : h5py.Group or None
+ The params group of the summary.
+ key : str
+ The setting's name.
+
+ Returns
+ -------
+ str or np.generic or None
+ The recorded scalar (bytes decoded), or None when not recorded.
+ """
if g is None or key not in g:
return None
v = np.asarray(g[key][()]).ravel()
@@ -473,38 +820,49 @@ def value(g, key):
return dataclasses.replace(params, **changes), network
-def _path_numbers(summary) -> int:
- """The largest path number of a summary (its paths need not all be
- there: a path without results is left out)."""
+def _path_numbers(summary: str | Path) -> int:
+ """Return the largest path number of a summary.
+
+ Its paths need not all be there: a path without results is left out.
+
+ Parameters
+ ----------
+ summary : str or Path
+ The experiment_summary.h5 file.
+
+ Returns
+ -------
+ int
+ The largest path number, 0 without paths.
+ """
with h5py.File(summary, "r") as f:
- ids = [
- int(k[4:]) for k in f if k.startswith("Path") and k[4:].isdigit()
- ]
+ ids = [int(k[4:]) for k in f if k.startswith("Path") and k[4:].isdigit()]
return max(ids, default=0)
def annotate_spots(
session: SiloSession,
params: SiloParams,
- results: Optional[list] = None,
- baseline_dir=None,
+ results: list | None = None,
+ baseline_dir: str | Path | None = None,
verbose: bool = False,
workers: int = 1,
) -> dict:
- """Group, test and label each path's spots; write them into
- ``experiment_summary.h5``.
+ """Group, test and label each path's spots.
+
+ The spots are written into experiment_summary.h5.
Parameters
----------
session : SiloSession
params : SiloParams
results : list, optional
- The collected paths (``PathResult`` or None), for their plans'
+ The collected paths (PathResult or None), for their plans'
across-trial maps; None reads the maps the summary records (an
- existing summary annotated again, ``giant silo-spots``), and the
+ existing summary annotated again, giant silo-spots), and the
event test then reads the signal the run recorded (activity
channel, motion discards, the network's baselines or the median's
- window) whatever ``params`` say.
+ window) whatever params say.
baseline_dir : str or Path, optional
The network's baselines (the moving median of the movie otherwise).
verbose : bool
@@ -562,10 +920,44 @@ def annotate_spots(
def _annotate_path(
- session, params, settings, summary, d, warp, bdir, verbose, pool
-):
- """Group, test, label and write one path's spots (``d`` zero-based);
- the number of spots per label, or None for a path without sources."""
+ session: SiloSession,
+ params: SiloParams,
+ settings: sp.SpotSettings,
+ summary: str | Path,
+ d: int,
+ warp: SummaryWarp | TrialWarp | None,
+ bdir: str | Path | None,
+ verbose: bool,
+ pool: ProcessPoolExecutor | None,
+) -> dict[str, int] | None:
+ """Group, test, label and write one path's spots (d zero-based).
+
+ Parameters
+ ----------
+ session : SiloSession
+ The session.
+ params : SiloParams
+ The run's parameters.
+ settings : sp.SpotSettings
+ The spot settings.
+ summary : str or Path
+ The experiment_summary.h5 file.
+ d : int
+ Path (zero-based).
+ warp : SummaryWarp or TrialWarp or None
+ The path's across-trial maps; None skips the event test.
+ bdir : str or Path or None
+ The network's baselines, or None for the moving median.
+ verbose : bool
+ Print progress per trial.
+ pool : ProcessPoolExecutor or None
+ Executor for the event tests.
+
+ Returns
+ -------
+ dict or None
+ The number of spots per label, or None for a path without sources.
+ """
name = f"Path{d + 1}"
with h5py.File(summary, "r") as f:
if f"{name}/sources/spatial/coords" not in f:
@@ -574,9 +966,7 @@ def _annotate_path(
rc = rc[1:3].T
# the summary keeps physical channels: take the activity channel
ev = np.asarray(
- f[f"{name}/sources/temporal/events"][()][
- :, params.activity_channel - 1, :
- ],
+ f[f"{name}/sources/temporal/events"][()][:, params.activity_channel - 1, :],
np.float64,
).T
lab = sp.link_groups(rc, settings.link_px)
@@ -588,36 +978,25 @@ def _annotate_path(
src = rc[members[g]]
c = src.mean(0)
extent = float(np.max(np.hypot(*(src - c).T)))
- spots.append(dict(g=g, center=c, extent=extent))
+ spots.append({"g": g, "center": c, "extent": extent})
events = [None] * len(spots)
- if (
- params.spot_event_test
- and spots
- and warp is not None
- and d < session.n_paths
- ):
+ if params.spot_event_test and spots and warp is not None and d < session.n_paths:
try:
- events = _spot_events(
- session, params, settings, d, warp, spots, bdir, verbose, pool
- )
+ events = _spot_events(session, params, settings, d, warp, spots, bdir, verbose, pool)
except Exception as e: # noqa: BLE001
# an annotation never stops a run: without readable movies or
# baselines the spots keep the correlation test alone
warnings.warn(
- f"spot annotation of path {d + 1}: event test skipped "
- f"({type(e).__name__}: {e})",
+ f"spot annotation of path {d + 1}: event test skipped ({type(e).__name__}: {e})",
UserWarning,
stacklevel=3,
)
events = [None] * len(spots)
out = [
- sp.SpotResult(members[g], "single", center=rc[members[g]].mean(0))
- for g in range(n_spots)
+ sp.SpotResult(members[g], "single", center=rc[members[g]].mean(0)) for g in range(n_spots)
]
jobs = [
- (e, rc[members[s["g"]]], settings, s["g"])
- for s, e in zip(spots, events)
- if e is not None
+ (e, rc[members[s["g"]]], settings, s["g"]) for s, e in zip(spots, events) if e is not None
]
done = iter(_event_tests(jobs, pool))
tests = [next(done) if e is not None else {} for e in events]
@@ -654,28 +1033,31 @@ def _write(
del g["spots"]
if "spot_id" in g["spatial"]:
del g["spatial/spot_id"]
- g["spatial"].create_dataset(
- "spot_id", data=(lab + 1).astype(np.int32)[None, :]
- )
+ g["spatial"].create_dataset("spot_id", data=(lab + 1).astype(np.int32)[None, :])
s = g.create_group("spots")
code = {k: i for i, k in enumerate(sp.LABELS)}
- def row(v, dt):
- """A MATLAB row vector."""
+ def row(v: list, dt: type) -> np.ndarray:
+ """Return a MATLAB row vector.
+
+ Parameters
+ ----------
+ v : list
+ The values.
+ dt : type
+ The numpy dtype of the row.
+
+ Returns
+ -------
+ np.ndarray
+ The values as a (1, n) array.
+ """
return np.asarray(v, dtype=dt)[None, :]
- s.create_dataset(
- "label", data=row([code[o.label] for o in out], np.int8)
- )
- s.create_dataset(
- "n_sources", data=row([o.sources.size for o in out], np.int32)
- )
- s.create_dataset(
- "event_corr", data=row([o.event_corr for o in out], np.float64)
- )
- s.create_dataset(
- "n_events", data=row([o.n_events for o in out], np.int32)
- )
+ s.create_dataset("label", data=row([code[o.label] for o in out], np.int8))
+ s.create_dataset("n_sources", data=row([o.sources.size for o in out], np.int32))
+ s.create_dataset("event_corr", data=row([o.event_corr for o in out], np.float64))
+ s.create_dataset("n_events", data=row([o.n_events for o in out], np.int32))
s.create_dataset("K", data=row([o.K for o in out], np.int32))
s.create_dataset("power", data=row([o.power for o in out], np.float64))
s.create_dataset(
@@ -686,23 +1068,31 @@ def row(v, dt):
"cloud_minor_px",
data=row([o.cloud_minor for o in out], np.float64),
)
- s.create_dataset(
- "bic_gain", data=row([o.bic_gain for o in out], np.float64)
- )
- s.create_dataset(
- "center_row", data=row([o.center[0] for o in out], np.float64)
- )
- s.create_dataset(
- "center_col", data=row([o.center[1] for o in out], np.float64)
- )
+ s.create_dataset("bic_gain", data=row([o.bic_gain for o in out], np.float64))
+ s.create_dataset("center_row", data=row([o.center[0] for o in out], np.float64))
+ s.create_dataset("center_col", data=row([o.center[1] for o in out], np.float64))
s.attrs["labels"] = json.dumps(list(sp.LABELS))
s.attrs["settings"] = json.dumps(settings.to_dict())
-def read_spots(summary, d: int) -> Optional[dict]:
- """A path's spot annotation (``d`` one-based), or None without one:
- ``spot_id`` (zero-based, per kept source) and per spot the datasets of
- ``sources/spots`` with ``label`` as strings."""
+def read_spots(summary: str | Path, d: int) -> dict | None:
+ """Read a path's spot annotation (d one-based), or None without one.
+
+ The annotation is spot_id (zero-based, per kept source) and per spot the datasets of
+ sources/spots with label as strings.
+
+ Parameters
+ ----------
+ summary : str or Path
+ The experiment_summary.h5 file.
+ d : int
+ Path (one-based).
+
+ Returns
+ -------
+ dict or None
+ The spot annotation, or None when the path has none.
+ """
with h5py.File(summary, "r") as f:
key = f"Path{d}/sources/spots"
if key not in f:
@@ -711,8 +1101,6 @@ def read_spots(summary, d: int) -> Optional[dict]:
labels = json.loads(g.attrs["labels"])
out = {k: np.asarray(g[k][()]).ravel() for k in g}
out["label"] = np.array([labels[i] for i in out["label"]])
- out["spot_id"] = (
- np.asarray(f[f"Path{d}/sources/spatial/spot_id"][()]).ravel() - 1
- )
+ out["spot_id"] = np.asarray(f[f"Path{d}/sources/spatial/spot_id"][()]).ravel() - 1
out["settings"] = json.loads(g.attrs["settings"])
return out
diff --git a/src/giant_python/pipeline/trial_table.py b/src/giant_python/pipeline/trial_table.py
index 3dc0ac68..41655170 100644
--- a/src/giant_python/pipeline/trial_table.py
+++ b/src/giant_python/pipeline/trial_table.py
@@ -1,36 +1,38 @@
-"""SLAP2 trial tables: GIAnT-MATLAB's ``buildTrialTableSLAP2`` in Python.
+"""SLAP2 trial tables: GIAnT-MATLAB's buildTrialTableSLAP2 in Python.
A trial table lists a session's analysis trials: for each DMD path and trial,
-the ``.dat`` file and the first and last line to read, with the reference
+the .dat file and the first and last line to read, with the reference
stacks and the trial times. :func:`build_trial_table_slap2` writes the same
-``trial_table.h5`` as ``buildTrialTableSLAP2(dr, savedr, true)`` (every file
+trial_table.h5 as buildTrialTableSLAP2(dr, savedr, true) (every file
in one epoch), so registration and SILo, in either language, use it
unchanged. :func:`trim_trial_table` keeps the first seconds of a session, as
-the GIAnT integration-test capsule's ``trimTrialTableSLAP2`` does.
+the GIAnT integration-test capsule's trimTrialTableSLAP2 does.
Files of a path are put in acquisition order by the timestamp and trial
number in their names. Triggered recordings (one file per trial) are lined
up across paths, which also handles SLAP2's trial-numbering bug of Feb 2024
(a path whose trial number failed to increment holds two trials in one
-file). Continuous recordings (``-CYCLE-`` files) are cut into trials of at
+file). Continuous recordings (-CYCLE- files) are cut into trials of at
most 200000 lines. Trial times come from the FPGA line clock when the
-``.meta`` file has ``fpgaTimeReference``, otherwise from file modification
+.meta file has fpgaTimeReference, otherwise from file modification
times.
"""
from __future__ import annotations
import datetime
+import itertools
import json
import math
import os
import re
import warnings
+from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
from pathlib import Path
-from typing import List, Optional, Sequence, Tuple, Union
import numpy as np
+import numpy.typing as npt
LINE_DIFF_THRESH = 2000
"""Line counts closer than this (about 0.2 s) are the same trial length."""
@@ -39,7 +41,7 @@
"""Continuous recordings are cut into trials of at most this many lines."""
_DATENUM_1970 = 719529.0
-"""MATLAB ``datenum(1970, 1, 1)``."""
+"""MATLAB datenum(1970, 1, 1)."""
_MS_PER_DAY = 86400000.0
@@ -55,9 +57,9 @@ class DatInfo:
Attributes
----------
num_lines : int
- Lines in the recording (``totalNumLines``).
+ Lines in the recording (totalNumLines).
first_line_time : float
- MATLAB ``datenum`` of the first line by the FPGA clock, or NaN.
+ MATLAB datenum of the first line by the FPGA clock, or NaN.
line_period_s : float
Line period from the metadata file.
"""
@@ -67,19 +69,19 @@ class DatInfo:
line_period_s: float
-def read_dat_info(path: Union[str, Path]) -> DatInfo:
+def read_dat_info(path: str | Path) -> DatInfo:
"""Line count, first-line time and line period of a SLAP2 recording.
A file of a CYCLE-split recording stands for all its files, as with
- GIAnT-MATLAB's ``Slap2DataFile``. The first line is the earliest first
- line of the files; its time is the ``.meta`` file's
- ``fpgaTimeReference`` plus the line's tick count over
- ``fpgaSystemClock_Hz``.
+ GIAnT-MATLAB's Slap2DataFile. The first line is the earliest first
+ line of the files; its time is the .meta file's
+ fpgaTimeReference plus the line's tick count over
+ fpgaSystemClock_Hz.
Parameters
----------
path : str or Path
- A ``.dat`` file.
+ A .dat file.
Returns
-------
@@ -116,69 +118,79 @@ def read_dat_info(path: Union[str, Path]) -> DatInfo:
def _mtime_datenum(path: Path) -> float:
- """MATLAB ``dir`` datenum: local modification time in days."""
+ """MATLAB dir datenum: local modification time in days.
+
+ Returns
+ -------
+ float
+ The file's modification time as a MATLAB datenum.
+ """
t = datetime.datetime.fromtimestamp(os.stat(path).st_mtime)
midnight = t.replace(hour=0, minute=0, second=0, microsecond=0)
return t.toordinal() + 366 + (t - midnight).total_seconds() / 86400.0
def _later_cycle_file(name: str) -> bool:
- """Whether a file is a later file of a CYCLE-split recording."""
+ """Whether a file is a later file of a CYCLE-split recording.
+
+ Returns
+ -------
+ bool
+ True when the name has a CYCLE number greater than 0.
+ """
m = re.search(r"CYCLE-?(\d+)", name)
return m is not None and int(m.group(1)) > 0
-def _recording_mtime(dat_dir: Path, name: str, all_names) -> float:
- """Modification datenum of a recording: of its file, or for a CYCLE-split
- recording of its last file, written when the recording ended.
+def _recording_mtime(dat_dir: Path, name: str, all_names: Iterable[str]) -> float:
+ """Modification datenum of a recording.
+
+ Of its file, or for a CYCLE-split recording of its last file, written when
+ the recording ended.
MATLAB uses the first file's time for a CYCLE-split recording, which puts
file-time trial times too early by the length of the later files; only
recordings without the FPGA line clock use these times.
+
+ Returns
+ -------
+ float
+ The modification datenum of the recording's file, or of its last file for a
+ CYCLE-split recording.
"""
m = re.search(r"CYCLE-?\d+", name)
if m is None:
return _mtime_datenum(dat_dir / name)
stem = name[: m.start()]
- parts = [
- n
- for n in all_names
- if n.startswith(stem) and re.match(r"CYCLE-?\d+", n[len(stem) :])
- ]
+ parts = [n for n in all_names if n.startswith(stem) and re.match(r"CYCLE-?\d+", n[len(stem) :])]
return max(_mtime_datenum(dat_dir / n) for n in parts)
def _name_timestamp(stamp: str) -> float:
- """``datenum`` of a yyyyMMddHHmmss string, or NaN if not a valid date."""
+ """``datenum`` of a yyyyMMddHHmmss string, or NaN if not a valid date.
+
+ Returns
+ -------
+ float
+ The MATLAB datenum of the timestamp, or NaN when a field is out of range.
+ """
v = [int(stamp[0:4]), int(stamp[4:6]), int(stamp[6:8])]
v += [int(stamp[8:10]), int(stamp[10:12]), int(stamp[12:14])]
- if not (
- 1 <= v[1] <= 12
- and 1 <= v[2] <= 31
- and v[3] < 24
- and v[4] < 60
- and v[5] < 60
- ):
+ if not (1 <= v[1] <= 12 and 1 <= v[2] <= 31 and v[3] < 24 and v[4] < 60 and v[5] < 60):
return math.nan
try:
t = datetime.datetime(*v)
except ValueError: # e.g. 31 February, which MATLAB's datenum rolls over
base = datetime.datetime(v[0], v[1], 1)
- t = base + datetime.timedelta(
- days=v[2] - 1, hours=v[3], minutes=v[4], seconds=v[5]
- )
- return (
- t.toordinal()
- + 366
- + (t.hour * 3600 + t.minute * 60 + t.second) / 86400.0
- )
+ t = base + datetime.timedelta(days=v[2] - 1, hours=v[3], minutes=v[4], seconds=v[5])
+ return t.toordinal() + 366 + (t.hour * 3600 + t.minute * 60 + t.second) / 86400.0
-def acquisition_order(names: Sequence[str]) -> Tuple[np.ndarray, bool]:
- """Order SLAP2 ``.dat`` files by acquisition time, then trial number.
+def acquisition_order(names: Sequence[str]) -> tuple[np.ndarray, bool]:
+ """Order SLAP2 .dat files by acquisition time, then trial number.
- Names look like ``activity_20250314_111223_DMD1-TRIAL000002.dat``; files
- of continuous recordings end in ``-CYCLE-000000`` instead of, or after,
+ Names look like activity_20250314_111223_DMD1-TRIAL000002.dat; files
+ of continuous recordings end in -CYCLE-000000 instead of, or after,
the trial number.
Parameters
@@ -199,9 +211,7 @@ def acquisition_order(names: Sequence[str]) -> Tuple[np.ndarray, bool]:
trial = np.zeros(n)
base = []
for k, name in enumerate(names):
- stem = re.sub(
- r"-CYCLE-?\d+\.dat$|\.dat$", "", name, flags=re.IGNORECASE
- )
+ stem = re.sub(r"-CYCLE-?\d+\.dat$|\.dat$", "", name, flags=re.IGNORECASE)
m = re.search(r"-TRIAL(\d+)$", stem, flags=re.IGNORECASE)
if m:
trial[k] = float(m.group(1))
@@ -235,6 +245,12 @@ def _copy_time_reason(
SLAP2 writes each file as its trial ends, so in acquisition order the
times increase and span at least the recording time of all files but
one. Copies (e.g. from S3) carry the copy time instead.
+
+ Returns
+ -------
+ str
+ The reason the times look like copy times, or an empty string when they
+ look like write times.
"""
if mtimes.size < 2:
return ""
@@ -245,15 +261,19 @@ def _copy_time_reason(
if check_order and np.any(np.diff(mtime_s) < -2):
return "they are out of order relative to the file names"
if span_s < 0.5 * min_span_s:
- return (
- f"they span {span_s:.0f} s, but the trials add up to at least "
- f"{min_span_s:.0f} s"
- )
+ return f"they span {span_s:.0f} s, but the trials add up to at least {min_span_s:.0f} s"
return ""
def matlab_linspace(d1: float, d2: float, n: int) -> np.ndarray:
- """MATLAB ``linspace``, with the same rounding (endpoints exact)."""
+ """MATLAB linspace, with the same rounding (endpoints exact).
+
+ Returns
+ -------
+ np.ndarray
+ n evenly spaced values from d1 to d2 (empty for n < 1;
+ just d2 for n == 1).
+ """
n = int(n)
if n < 1:
return np.zeros(0)
@@ -266,36 +286,55 @@ def matlab_linspace(d1: float, d2: float, n: int) -> np.ndarray:
def _find_reference(dat_dir: Path, dmd: int) -> Path:
- """The reference stack TIFF of one path, searched under ``dat_dir``."""
+ """Find the reference stack TIFF of one path, searched under dat_dir.
- def find(pattern):
- """Files below ``dat_dir`` matching a pattern, sorted."""
+ Returns
+ -------
+ Path
+ The reference stack file of the path (its CONFIG1 .tif when several
+ are found).
+
+ Raises
+ ------
+ FileNotFoundError
+ If no reference stack file is found below dat_dir.
+ ValueError
+ If several reference stacks are found and they cannot be narrowed to a single
+ CONFIG1 .tif file.
+ """
+
+ def find(pattern: str) -> list[Path]:
+ """Files below dat_dir matching a pattern, sorted.
+
+ Returns
+ -------
+ list of Path
+ The matching files, sorted.
+ """
return sorted(p for p in dat_dir.rglob(pattern) if p.is_file())
- found = find(f"*DMD{dmd}*_CONFIG1-REFERENCE*") or find(
- f"*DMD{dmd}*-REFERENCE*"
- )
+ found = find(f"*DMD{dmd}*_CONFIG1-REFERENCE*") or find(f"*DMD{dmd}*-REFERENCE*")
if not found:
- raise FileNotFoundError(
- f"Could not find reference image within folder: {dat_dir}"
- )
+ raise FileNotFoundError(f"Could not find reference image within folder: {dat_dir}")
if len(found) == 1:
return found[0]
tifs = find(f"*DMD{dmd}_CONFIG1-REFERENCE*.tif")
if not tifs:
- raise ValueError(
- "Too many reference stacks found in the specified directory!"
- )
+ raise ValueError("Too many reference stacks found in the specified directory!")
if len(tifs) > 1:
- raise ValueError(
- "Too many CONFIG1 reference stacks found in the specified "
- "directory!"
- )
+ raise ValueError("Too many CONFIG1 reference stacks found in the specified directory!")
return tifs[0]
-def _json_array(value) -> np.ndarray:
- """A JSON number or array as MATLAB's ``jsondecode`` gives it."""
+def _json_array(value: npt.ArrayLike) -> np.ndarray:
+ """Convert a JSON number or array as MATLAB's jsondecode gives it.
+
+ Returns
+ -------
+ np.ndarray
+ A float64 array: 1 x 1 for a scalar, a column for a vector, and
+ unchanged for higher ranks.
+ """
arr = np.asarray(value, dtype=np.float64)
if arr.ndim == 0:
return arr.reshape(1, 1)
@@ -304,23 +343,28 @@ def _json_array(value) -> np.ndarray:
return arr
-def read_reference_stack(path: Union[str, Path]) -> dict:
- """A SLAP2 reference stack, as ``buildTrialTableSLAP2`` stores it.
+def read_reference_stack(path: str | Path) -> dict:
+ """Read a SLAP2 reference stack, as buildTrialTableSLAP2 stores it.
Parameters
----------
path : str or Path
The ``*-REFERENCE*.tif`` file. Each page's ImageDescription is JSON
- with its ``channel``, ``z`` and ``dmdPixel2SampleTransform``.
+ with its channel, z and dmdPixel2SampleTransform.
Returns
-------
dict
- ``IM``: the pages in MATLAB orientation (columns x rows x pages, as
+ IM: the pages in MATLAB orientation (columns x rows x pages, as
ScanImageTiffReader returns them; stored in HDF5 as the pages
- themselves) in their native type; ``channels``: the channels in
- order of appearance; ``Zs``: the z of each page of the first page's
- channel; ``dmdPixel2SampleTransform``: from the last page.
+ themselves) in their native type; channels: the channels in
+ order of appearance; Zs: the z of each page of the first page's
+ channel; dmdPixel2SampleTransform: from the last page.
+
+ Raises
+ ------
+ ValueError
+ If the reference stack's pages are not 2-D.
"""
import tifffile
@@ -333,8 +377,8 @@ def read_reference_stack(path: Union[str, Path]) -> dict:
for k, page in enumerate(pages):
stack[k] = page.asarray()
descs.append(page.description)
- channels: List[float] = []
- zs: List[float] = []
+ channels: list[float] = []
+ zs: list[float] = []
accum = None
meta = {}
for k, desc in enumerate(descs):
@@ -353,9 +397,7 @@ def read_reference_stack(path: Union[str, Path]) -> dict:
"IM": im,
"channels": np.asarray(channels, dtype=np.float64),
"Zs": np.asarray(zs, dtype=np.float64),
- "dmdPixel2SampleTransform": _json_array(
- meta["dmdPixel2SampleTransform"]
- ),
+ "dmdPixel2SampleTransform": _json_array(meta["dmdPixel2SampleTransform"]),
}
@@ -363,7 +405,7 @@ def read_reference_stack(path: Union[str, Path]) -> dict:
class _PathFiles:
"""One path's files in acquisition order, with what trials need."""
- names: List[str]
+ names: list[str]
lines: np.ndarray
clock: np.ndarray
mtime: np.ndarray
@@ -379,7 +421,14 @@ class _Trials:
start: list = field(default_factory=list)
end: list = field(default_factory=list)
- def add(self, files, first, last, start, end):
+ def add(
+ self,
+ files: tuple[str, str],
+ first: tuple[float, float],
+ last: tuple[float, float],
+ start: float,
+ end: float,
+ ) -> None:
"""Append one trial."""
self.files.append(files)
self.first.append(first)
@@ -388,8 +437,20 @@ def add(self, files, first, last, start, end):
self.end.append(end)
-def _path_files(names, order, info, mtime) -> _PathFiles:
- """One path's files in the given order with their counts and times."""
+def _path_files(
+ names: list[str],
+ order: Iterable[int],
+ info: dict[str, DatInfo],
+ mtime: dict[str, float],
+) -> _PathFiles:
+ """One path's files in the given order with their counts and times.
+
+ Returns
+ -------
+ _PathFiles
+ The file names, line counts, first-line clock times and modification
+ times, in the given order.
+ """
ordered = [names[i] for i in order]
return _PathFiles(
ordered,
@@ -399,12 +460,23 @@ def _path_files(names, order, info, mtime) -> _PathFiles:
)
-def _paths_in_order(names, info, mtime):
+def _paths_in_order(
+ names: list[str], info: dict[str, DatInfo], mtime: dict[str, float]
+) -> tuple[_PathFiles, _PathFiles, bool]:
"""Split files into the two paths and order them by acquisition.
Falls back to modification times (with a warning) when the names don't
give an order, as MATLAB does. Returns both paths and whether the names
gave the order.
+
+ Returns
+ -------
+ p1 : _PathFiles
+ Path 1's (DMD1) files in acquisition order.
+ p2 : _PathFiles
+ Path 2's (DMD2) files in acquisition order.
+ names_ok : bool
+ Whether the names gave the order for both paths.
"""
d1 = [n for n in names if "DMD1" in n]
d2 = [n for n in names if "DMD1" not in n]
@@ -426,11 +498,11 @@ def _paths_in_order(names, info, mtime):
return p1, p2, names_ok
-def _warn_copy_times(p1, p2, line_period_s, names_ok) -> None:
+def _warn_copy_times(p1: _PathFiles, p2: _PathFiles, line_period_s: float, names_ok: bool) -> None:
"""Warn when modification times, used for trial times, look like copies."""
- reason = _copy_time_reason(
- p1.mtime, p1.lines, line_period_s, names_ok
- ) or _copy_time_reason(p2.mtime, p2.lines, line_period_s, names_ok)
+ reason = _copy_time_reason(p1.mtime, p1.lines, line_period_s, names_ok) or _copy_time_reason(
+ p2.mtime, p2.lines, line_period_s, names_ok
+ )
if reason:
warnings.warn(
f"File modification times in epoch 1 do not look like acquisition "
@@ -442,8 +514,21 @@ def _warn_copy_times(p1, p2, line_period_s, names_ok) -> None:
)
-def _continuous_trials(p1, p2, use_clock, line_period_s) -> _Trials:
- """Cut each continuous recording into trials of at most 200000 lines."""
+def _continuous_trials(
+ p1: _PathFiles, p2: _PathFiles, use_clock: bool, line_period_s: float
+) -> _Trials:
+ """Cut each continuous recording into trials of at most 200000 lines.
+
+ Returns
+ -------
+ _Trials
+ The trials: file pairs, first and last lines, and start and end times.
+
+ Raises
+ ------
+ ValueError
+ If the two paths have different numbers of files.
+ """
if len(p1.names) != len(p2.names):
raise ValueError(
"There was an unequal amount of DMD1 and DMD2 files for an epoch "
@@ -455,7 +540,7 @@ def _continuous_trials(p1, p2, use_clock, line_period_s) -> _Trials:
n_tot = min(p1.lines[f], p2.lines[f])
n_trials = math.ceil(n_tot / MULTI_CYCLE_LINES_PER_TRIAL)
edges = matlab_linspace(1.0, n_tot + 1.0, n_trials + 1)
- for a, b in zip(edges[:-1], edges[1:]):
+ for a, b in itertools.pairwise(edges):
if use_clock:
start = p1.clock[f] + (a - 1) * line_days
end = p1.clock[f] + (b - 1) * line_days
@@ -466,12 +551,25 @@ def _continuous_trials(p1, p2, use_clock, line_period_s) -> _Trials:
return trials
-def _triggered_trials(p1, p2, use_clock, line_period_s) -> _Trials:
+def _triggered_trials(
+ p1: _PathFiles, p2: _PathFiles, use_clock: bool, line_period_s: float
+) -> _Trials:
"""Line up one-file-per-trial recordings across the two paths.
A trial ends where either path's file ends; a path whose file holds more
lines (its trial number failed to increment) carries the rest over to
the next trial.
+
+ Returns
+ -------
+ _Trials
+ The trials: file pairs, first and last lines, and start and end times.
+
+ Raises
+ ------
+ ValueError
+ If the files of the two paths cannot be lined up (their line counts never agree
+ within the threshold).
"""
line_days = line_period_s / 86400.0
trials = _Trials()
@@ -516,13 +614,28 @@ def _triggered_trials(p1, p2, use_clock, line_period_s) -> _Trials:
return trials
-def _rows(values, n: int, dtype=np.float64) -> np.ndarray:
- """Per-trial pairs (path 1, path 2) as a 2 x n array."""
+def _rows(values: npt.ArrayLike, n: int, dtype: npt.DTypeLike = np.float64) -> np.ndarray:
+ """Per-trial pairs (path 1, path 2) as a 2 x n array.
+
+ Returns
+ -------
+ np.ndarray
+ (2, n) array with the path 1 and path 2 values of each trial.
+ """
return np.array(values, dtype=dtype).reshape(n, 2).T
-def _write_tables(table, out_dir, max_duration_s, line_period_s) -> dict:
- """Write trial_table.h5 (and the untrimmed table when trimming)."""
+def _write_tables(
+ table: dict, out_dir: str | Path, max_duration_s: float | None, line_period_s: float
+) -> dict:
+ """Write trial_table.h5 (and the untrimmed table when trimming).
+
+ Returns
+ -------
+ dict
+ The table as written to trial_table.h5: table itself, or the
+ trimmed table when max_duration_s is given.
+ """
from ..io.hdf5 import save_struct_h5
out_dir = Path(out_dir)
@@ -537,39 +650,47 @@ def _write_tables(table, out_dir, max_duration_s, line_period_s) -> dict:
def build_trial_table_slap2(
- dat_dir: Union[str, Path],
- save_dir: Optional[Union[str, Path]] = None,
- max_duration_s: Optional[float] = None,
+ dat_dir: str | Path,
+ save_dir: str | Path | None = None,
+ max_duration_s: float | None = None,
write: bool = True,
) -> dict:
"""Build (and write) the trial table of a SLAP2 session.
- Python counterpart of GIAnT-MATLAB ``buildTrialTableSLAP2(dr, savedr,
- true)``: every ``.dat`` file of ``dat_dir`` is in one epoch, and the
+ Python counterpart of GIAnT-MATLAB buildTrialTableSLAP2(dr, savedr,
+ true): every .dat file of dat_dir is in one epoch, and the
first file of each CYCLE-split recording stands for all its files.
Parameters
----------
dat_dir : str or Path
- Folder with the ``.dat`` and ``.meta`` files; the reference stacks
- are searched for anywhere below it. Stored as ``datadr``, as given.
+ Folder with the .dat and .meta files; the reference stacks
+ are searched for anywhere below it. Stored as datadr, as given.
save_dir : str or Path, optional
- Where ``trial_table.h5`` is written (``savedr``); default
- ``dat_dir``.
+ Where trial_table.h5 is written (savedr); default
+ dat_dir.
max_duration_s : float, optional
Keep only the first seconds (see :func:`trim_trial_table`); the
- whole table is then also written as ``trial_table_untrimmed.h5``.
+ whole table is then also written as trial_table_untrimmed.h5.
write : bool
Write the HDF5 file(s) (default True).
Returns
-------
dict
- The trial table in MATLAB orientation (as ``load_struct_h5`` reads
- it): ``datadr``, ``savedr``, ``filename`` (2 x trials),
- ``true_trial_ix``, ``epoch``, and ``slap2_info`` with ``ref_stack``,
- ``first_line``, ``last_line``, ``trial_end_time_from_pc`` and
- ``trial_start_time_inferred`` (MATLAB datenums).
+ The trial table in MATLAB orientation (as load_struct_h5 reads
+ it): datadr, savedr, filename (2 x trials),
+ true_trial_ix, epoch, and slap2_info with ref_stack,
+ first_line, last_line, trial_end_time_from_pc and
+ trial_start_time_inferred (MATLAB datenums).
+
+ Raises
+ ------
+ FileNotFoundError
+ If dat_dir holds no .dat files.
+ ValueError
+ If dat_dir mixes continuous (-CYCLE-) and triggered recordings, or if no
+ trials can be lined up across the two paths.
"""
dat_dir_str, dat_dir = str(dat_dir), Path(dat_dir)
save_dir_str = dat_dir_str if save_dir is None else str(save_dir)
@@ -577,10 +698,7 @@ def build_trial_table_slap2(
names = [n for n in all_names if not _later_cycle_file(n)]
if not names:
raise FileNotFoundError(f"No .dat files in {dat_dir}")
- ref_stack = {
- f"Path{d}": read_reference_stack(_find_reference(dat_dir, d))
- for d in (1, 2)
- }
+ ref_stack = {f"Path{d}": read_reference_stack(_find_reference(dat_dir, d)) for d in (1, 2)}
print(f"Loading metadata from {len(names)} DAT files...")
info = {n: read_dat_info(dat_dir / n) for n in names}
mtime = {n: _recording_mtime(dat_dir, n, all_names) for n in names}
@@ -623,30 +741,26 @@ def build_trial_table_slap2(
},
}
if write:
- return _write_tables(
- table, save_dir_str, max_duration_s, line_period_s
- )
+ return _write_tables(table, save_dir_str, max_duration_s, line_period_s)
if max_duration_s is None:
return table
return trim_trial_table(table, max_duration_s, line_period_s)[0]
-def trim_trial_table(
- table: dict, max_duration_s: float, line_period_s: float
-) -> Tuple[dict, dict]:
+def trim_trial_table(table: dict, max_duration_s: float, line_period_s: float) -> tuple[dict, dict]:
"""Keep only the first seconds of a SLAP2 session's trial table.
- As the GIAnT integration-test capsule's ``trimTrialTableSLAP2``: whole
- trials are kept in order while they start before ``max_duration_s``, and
- the last one is shortened so the total is ``max_duration_s``. Raw data
- are not touched; downstream stages read only ``first_line`` to
- ``last_line``.
+ As the GIAnT integration-test capsule's trimTrialTableSLAP2: whole
+ trials are kept in order while they start before max_duration_s, and
+ the last one is shortened so the total is max_duration_s. Raw data
+ are not touched; downstream stages read only first_line to
+ last_line.
Parameters
----------
table : dict
Trial table in MATLAB orientation (from
- :func:`build_trial_table_slap2` or ``load_struct_h5``).
+ :func:`build_trial_table_slap2` or load_struct_h5).
max_duration_s : float
Seconds to keep.
line_period_s : float
@@ -657,8 +771,13 @@ def trim_trial_table(
trimmed : dict
A new table (the reference stacks are shared, not copied).
info : dict
- ``n_trials_untrimmed``, ``duration_untrimmed_s``, ``n_trials_kept``,
- ``duration_kept_s`` and ``last_trial_shortened``.
+ n_trials_untrimmed, duration_untrimmed_s, n_trials_kept,
+ duration_kept_s and last_trial_shortened.
+
+ Raises
+ ------
+ ValueError
+ If no trial starts before max_duration_s.
"""
s2 = table["slap2_info"]
first = np.asarray(s2["first_line"], dtype=np.float64).reshape(2, -1)
@@ -677,15 +796,20 @@ def trim_trial_table(
keep_lines = max(1, math.floor(remaining_s / line_period_s))
last[:, k] = np.minimum(last[:, k], first[:, k] + keep_lines - 1)
- def cols(value):
- """The kept trials (columns) of a per-path, per-trial array."""
+ def cols(value: npt.ArrayLike) -> np.ndarray:
+ """Select the kept trials (columns) of a per-path, per-trial array.
+
+ Returns
+ -------
+ np.ndarray
+ The columns of the kept trials, or value unchanged when it is not a
+ per-path, per-trial array.
+ """
arr = np.asarray(value)
return arr.reshape(2, -1)[:, keep] if arr.size == 2 * n_in else arr
out = dict(table)
- out["filename"] = np.asarray(table["filename"], dtype=object).reshape(
- 2, -1
- )[:, keep]
+ out["filename"] = np.asarray(table["filename"], dtype=object).reshape(2, -1)[:, keep]
out["true_trial_ix"] = cols(table["true_trial_ix"])
out["epoch"] = cols(table["epoch"])
new_s2 = dict(s2)
diff --git a/src/giant_python/progress.py b/src/giant_python/progress.py
index e61444b9..35ad97e1 100644
--- a/src/giant_python/progress.py
+++ b/src/giant_python/progress.py
@@ -1,20 +1,20 @@
"""Shared opt-in verbose logging and progress bars.
The BandSILo port stays quiet by default (headless / batch friendly); the
-reference's unconditional ``print``s and ``tqdm`` bars were dropped. These
-helpers restore that feedback opt-in: when ``verbose`` is set
-(``ExecutionOptions.verbose`` / ``giant ... --verbose``) messages are printed
-and long-running loops show a progress bar. ``tqdm`` is imported lazily, so a
+reference's unconditional prints and tqdm bars were dropped. These
+helpers restore that feedback opt-in: when verbose is set
+(ExecutionOptions.verbose / giant ... --verbose) messages are printed
+and long-running loops show a progress bar. tqdm is imported lazily, so a
non-verbose run neither prints nor imports it.
"""
from __future__ import annotations
-from typing import Iterable, Optional
+from collections.abc import Iterable
def log(message: str, verbose: bool) -> None:
- """Print ``message`` when ``verbose`` is set; otherwise do nothing.
+ """Print message when verbose is set; otherwise do nothing.
Parameters
----------
@@ -32,13 +32,13 @@ def progress(
*,
desc: str,
verbose: bool,
- total: Optional[int] = None,
+ total: int | None = None,
) -> Iterable:
- """Wrap ``iterable`` in a tqdm progress bar when ``verbose`` is set.
+ """Wrap iterable in a tqdm progress bar when verbose is set.
- Returns the iterable unchanged when ``verbose`` is ``False`` so callers can
+ Returns the iterable unchanged when verbose is False so callers can
wrap any loop unconditionally at zero cost (and without importing
- ``tqdm``).
+ tqdm).
Parameters
----------
@@ -49,7 +49,7 @@ def progress(
verbose : bool
Whether to show the bar.
total : int, optional
- Item count, for iterables without a ``len`` (e.g. a generator).
+ Item count, for iterables without a len (e.g. a generator).
Returns
-------
diff --git a/src/giant_python/registration/__init__.py b/src/giant_python/registration/__init__.py
index 6e60b57f..b75a9ebc 100644
--- a/src/giant_python/registration/__init__.py
+++ b/src/giant_python/registration/__init__.py
@@ -1,6 +1,6 @@
"""Motion registration of SLAP2 raster recordings (MultiRoiRegistration).
-A port of GIAnT-MATLAB ``motion_correction/MultiRoiRegistration.m``: frames
+A port of GIAnT-MATLAB motion_correction/MultiRoiRegistration.m: frames
are formed from the raw samples with getImage's exponential kernel, matched
to a growing template by freshness-weighted normalized cross-correlation and
resampled onto a common grid. Outputs use GIAnT-MATLAB's file layout, so its
diff --git a/src/giant_python/registration/compensation.py b/src/giant_python/registration/compensation.py
index 12f9d43f..c966ce22 100644
--- a/src/giant_python/registration/compensation.py
+++ b/src/giant_python/registration/compensation.py
@@ -1,22 +1,22 @@
"""Undoing SLAP2's online motion correction line by line (compensateOnline).
The online correction moves the DMD pattern by integer offsets recorded in
-each line's header. GIAnT-MATLAB (``getLineOnlineOffsets``,
-``frameOnlineOffsets``, ``slap2FrameSums`` with ``CompensateOnline``) undoes
+each line's header. GIAnT-MATLAB (getLineOnlineOffsets,
+frameOnlineOffsets, slap2FrameSums with CompensateOnline) undoes
it within each frame: every sample is moved by its line's offset minus the
frame's own offset (rows follow y, columns follow x), so a frame spanning an
x/y switch is not blurred, and the frame stays in the DMD coordinates of the
uncompensated frame.
-A new y reaches the DMD before the header records it: ``y_lead[0]`` lines
-earlier when x does not change on the same line, ``y_lead[1]`` lines when it
+A new y reaches the DMD before the header records it: y_lead[0] lines
+earlier when x does not change on the same line, y_lead[1] lines when it
does, but never before the previous x/y switch.
"""
from dataclasses import dataclass
-from typing import Tuple
import numpy as np
+from numpy.typing import ArrayLike
from ..io.slap2_raster import RasterLayout, read_line_offsets
@@ -27,8 +27,14 @@
"""Header offset difference [dx; dy] to [row; col] sample displacement."""
-def _mround(x):
- """Round half away from zero (MATLAB ``round``)."""
+def _mround(x: ArrayLike) -> np.ndarray:
+ """Round half away from zero (MATLAB round).
+
+ Returns
+ -------
+ np.ndarray
+ Float64 array of the rounded values, same shape as x.
+ """
x = np.asarray(x, dtype=np.float64)
return np.sign(x) * np.floor(np.abs(x) + 0.5)
@@ -40,19 +46,19 @@ class LineOffsets:
Attributes
----------
x, y : ndarray of int
- Header ``xOffset_pix`` / ``yOffset_pix`` of each line (index
- ``line - 1``). Lines outside ``lines_read`` repeat the first or last
+ Header xOffset_pix / yOffset_pix of each line (index
+ line - 1). Lines outside lines_read repeat the first or last
value read, as in MATLAB.
y_eff : ndarray of int
y on the DMD while each line was acquired.
median_xy : ndarray of float
- Rounded median ``[x, y]`` over the lines read (MATLAB medianXY).
+ Rounded median [x, y] over the lines read (MATLAB medianXY).
switch_lines : ndarray of int
One-based lines whose x or y differs from the previous line's.
lines_read : (int, int)
First and last line whose header was read.
y_lead : (int, int)
- Lead of y switches used for ``y_eff``.
+ Lead of y switches used for y_eff.
"""
x: np.ndarray
@@ -60,12 +66,17 @@ class LineOffsets:
y_eff: np.ndarray
median_xy: np.ndarray
switch_lines: np.ndarray
- lines_read: Tuple[int, int]
- y_lead: Tuple[int, int] = Y_LEAD
+ lines_read: tuple[int, int]
+ y_lead: tuple[int, int] = Y_LEAD
-def dmd_y(x, y, switch_lines, lead=Y_LEAD) -> np.ndarray:
- """y on the DMD: each change of the header y applied ``lead`` earlier.
+def dmd_y(
+ x: np.ndarray,
+ y: np.ndarray,
+ switch_lines: np.ndarray,
+ lead: tuple[int, int] = Y_LEAD,
+) -> np.ndarray:
+ """Y on the DMD: each change of the header y applied lead earlier.
Parameters
----------
@@ -79,7 +90,7 @@ def dmd_y(x, y, switch_lines, lead=Y_LEAD) -> np.ndarray:
Returns
-------
ndarray
- ``yEff`` as GIAnT-MATLAB's ``dmdY`` computes it.
+ yEff as GIAnT-MATLAB's dmdY computes it.
"""
y_eff = y.copy()
y_sw = np.flatnonzero(np.diff(y) != 0) + 1 # zero-based switch lines
@@ -93,9 +104,9 @@ def dmd_y(x, y, switch_lines, lead=Y_LEAD) -> np.ndarray:
def line_offsets(
- layout: RasterLayout, lines: Tuple[int, int], lead=Y_LEAD
+ layout: RasterLayout, lines: tuple[int, int], lead: tuple[int, int] = Y_LEAD
) -> LineOffsets:
- """Read the headers covering ``lines`` (``getLineOnlineOffsets``).
+ """Read the headers covering lines (getLineOnlineOffsets).
Parameters
----------
@@ -110,7 +121,12 @@ def line_offsets(
-------
LineOffsets
Offsets of every line of the recording, exact within the cycles
- covering ``lines`` widened by ``max(lead) + 1`` lines.
+ covering lines widened by max(lead) + 1 lines.
+
+ Raises
+ ------
+ ValueError
+ If lines are outside the recording.
"""
p = layout.lines_per_cycle
n_c = layout.num_cycles
@@ -139,9 +155,9 @@ def line_offsets(
def frame_offsets(
- offsets: LineOffsets, times, dt: int, lines_per_cycle: int
+ offsets: LineOffsets, times: ArrayLike, dt: int, lines_per_cycle: int
) -> np.ndarray:
- """The offset each frame mostly saw (``frameOnlineOffsets``).
+ """Compute the offset each frame mostly saw (frameOnlineOffsets).
Parameters
----------
@@ -152,12 +168,12 @@ def frame_offsets(
dt : int
Kernel time constant in lines.
lines_per_cycle : int
- ``P``; the kernel reaches ``max(3 dt, P)`` lines.
+ P; the kernel reaches max(3 dt, P) lines.
Returns
-------
ndarray of int
- ``(frames, 2)`` [x, y]: kernel-weighted means of ``x`` and ``y_eff``
+ (frames, 2) [x, y]: kernel-weighted means of x and y_eff
over each frame's lines, rounded.
"""
times = np.asarray(times, dtype=np.int64).ravel()
@@ -167,28 +183,28 @@ def frame_offsets(
for f, t in enumerate(times):
ln = np.arange(max(1, t - dt_read), min(n, t + dt_read) + 1)
w = np.exp(-np.abs(t - ln) / dt)
- out[f] = _mround(
- [w @ offsets.x[ln - 1], w @ offsets.y_eff[ln - 1]] / w.sum()
- )
+ out[f] = _mround([w @ offsets.x[ln - 1], w @ offsets.y_eff[ln - 1]] / w.sum())
return out
-def line_shifts(offsets: LineOffsets, lines: np.ndarray, refs: np.ndarray):
- """Row and column displacement of samples on ``lines`` for each frame.
+def line_shifts(
+ offsets: LineOffsets, lines: np.ndarray, refs: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+ """Row and column displacement of samples on lines for each frame.
Parameters
----------
offsets : LineOffsets
Line offsets.
lines : ndarray of int
- ``(frames, ...)`` one-based lines (any trailing shape).
+ (frames, ...) one-based lines (any trailing shape).
refs : ndarray of int
- ``(frames, 2)`` frame reference offsets [x, y].
+ (frames, 2) frame reference offsets [x, y].
Returns
-------
dr, dc : ndarray of int
- ``MAPPING @ [x - ref_x; y_eff - ref_y]``: rows follow y, columns x.
+ MAPPING @ [x - ref_x; y_eff - ref_y]: rows follow y, columns x.
"""
extra = (1,) * (lines.ndim - 1)
idx = np.clip(lines, 1, offsets.x.size) - 1
@@ -198,19 +214,19 @@ def line_shifts(offsets: LineOffsets, lines: np.ndarray, refs: np.ndarray):
def compensation_record(offsets: LineOffsets, refs: np.ndarray) -> dict:
- """The ``slap2/onlineCompensation`` group of the alignment file.
+ """Build the slap2/onlineCompensation group of the alignment file.
Parameters
----------
offsets : LineOffsets
- Line offsets (gives ``refOffset`` and ``yLead``).
+ Line offsets (gives refOffset and yLead).
refs : ndarray of int
- ``(frames, 2)`` reference offsets [x, y] of the DS frames.
+ (frames, 2) reference offsets [x, y] of the DS frames.
Returns
-------
dict
- Fields as MATLAB's ``compensationRecord`` saves them.
+ Fields as MATLAB's compensationRecord saves them.
"""
return {
"enabled": np.int8(1),
diff --git a/src/giant_python/registration/frames.py b/src/giant_python/registration/frames.py
index 5be2d19a..fd351bea 100644
--- a/src/giant_python/registration/frames.py
+++ b/src/giant_python/registration/frames.py
@@ -1,33 +1,49 @@
"""Raster frames from raw SLAP2 samples with getImage's exponential kernel.
-Equivalent to GIAnT-MATLAB ``slap2Frames`` (``Kernel='exp'``, inclusive
+Equivalent to GIAnT-MATLAB slap2Frames (Kernel='exp', inclusive
boundary, invalid samples masked per channel, no online compensation): the
-frame at line time ``t`` weights each sample on line ``l`` by
+frame at line time t weights each sample on line l by
``exp(-|t - l| / dt)`` for ``|t - l| <= max(3 dt, P)``, restricted to lines
of the requested fast-z plane, and each pixel's value is the weighted mean of
its samples. Frames are formed at the sampled pixels only. Registration and
-source extraction read the samples with ``read_raster_samples(...,
-mask_unlit=True)``, so samples taken behind the DMD curtain count as invalid
+source extraction read the samples with read_raster_samples(...,
+mask_unlit=True), so samples taken behind the DMD curtain count as invalid
(see :mod:`giant_python.io.slap2_raster`).
-Source extraction forms its frames with the same sums (``slap2FrameSums``
-with the exclusive boundary of getImages, see ``FrameFormer(exclusive=True)``
+Source extraction forms its frames with the same sums (slap2FrameSums
+with the exclusive boundary of getImages, see FrameFormer(exclusive=True)
and :class:`PixelFormer`).
"""
-from typing import Tuple
+from collections.abc import Callable, Iterator, Sequence
+from typing import Any
import numpy as np
+import numpy.typing as npt
import torch
from ..io.slap2_raster import INVALID_SAMPLE, RasterLayout
-def _bands(lo: np.ndarray, hi: np.ndarray, band: int):
- """Split frames into groups whose cycle ranges span at most ``band``.
+def _bands(lo: np.ndarray, hi: np.ndarray, band: int) -> list[np.ndarray]:
+ """Split frames into groups whose cycle ranges span at most band.
Frames are taken in order of their first cycle; a frame without samples
- (``hi < 0``) joins the current group.
+ (hi < 0) joins the current group.
+
+ Parameters
+ ----------
+ lo : np.ndarray
+ First cycle of each frame.
+ hi : np.ndarray
+ Last cycle of each frame; negative for a frame without samples.
+ band : int
+ Most cycles a group may span.
+
+ Returns
+ -------
+ list[np.ndarray]
+ Frame indices of each group.
"""
order = np.argsort(lo, kind="stable")
groups, cur, start, end = [], [], None, None
@@ -47,7 +63,20 @@ def _bands(lo: np.ndarray, hi: np.ndarray, band: int):
def _ceil_div(a: np.ndarray, b: int) -> np.ndarray:
- """Integer ceil(a / b) for positive b, exact for negative a."""
+ """Integer ceil(a / b) for positive b, exact for negative a.
+
+ Parameters
+ ----------
+ a : np.ndarray
+ Integer numerators.
+ b : int
+ Positive divisor.
+
+ Returns
+ -------
+ np.ndarray
+ ceil(a / b) as integers.
+ """
return -((-a) // b)
@@ -59,17 +88,17 @@ class FrameFormer:
layout : RasterLayout
The recording's layout.
samples : ndarray of int16
- Raw samples ``(channels, slots, cycles)`` of all raster slots, for
- the zero-based cycles ``cycle0 ...``.
+ Raw samples (channels, slots, cycles) of all raster slots, for
+ the zero-based cycles cycle0 ....
cycle0 : int
- Zero-based index of the first cycle in ``samples``.
+ Zero-based index of the first cycle in samples.
z_idx : int
One-based fast-z plane.
device : str or torch.device
Where sums are formed.
exclusive : bool
- Leave out the lines exactly ``max(3 dt, P)`` from a frame's time, as
- getImages does (``slap2FrameSums`` with ``Boundary='exclusive'``;
+ Leave out the lines exactly max(3 dt, P) from a frame's time, as
+ getImages does (slap2FrameSums with Boundary='exclusive';
source extraction's frames). Default: include them, as getImage.
band : int
Most cycles spanned by the frames summed in one matrix product.
@@ -90,10 +119,10 @@ def __init__(
samples: np.ndarray,
cycle0: int,
z_idx: int = 1,
- device="cpu",
+ device: str | torch.device = "cpu",
exclusive: bool = False,
band: int = 256,
- ):
+ ) -> None:
"""Build the pixel-major slot table and move samples to device."""
self.layout = layout
self.device = torch.device(device)
@@ -108,9 +137,7 @@ def __init__(
self.pixels, inv = np.unique(pix, return_inverse=True)
counts = np.bincount(inv, minlength=self.pixels.size)
order = np.argsort(inv, kind="stable")
- rank = np.arange(slots.size) - np.repeat(
- np.cumsum(counts) - counts, counts
- )
+ rank = np.arange(slots.size) - np.repeat(np.cumsum(counts) - counts, counts)
width = int(counts.max()) if counts.size else 0
table = np.full((self.pixels.size, width), -1, dtype=np.int64)
table[inv[order], rank] = slots[order]
@@ -119,9 +146,7 @@ def __init__(
# slots by line index, padded: (P, widest line); a pixel's slots as
# positions in that layout, for turning slot sums into pixel sums
p = layout.lines_per_cycle
- per_line = [
- slots[layout.slot_line[slots] == ln] for ln in range(1, p + 1)
- ]
+ per_line = [slots[layout.slot_line[slots] == ln] for ln in range(1, p + 1)]
self._line_width = max(1, max(len(x) for x in per_line))
line_slots = np.full((p, self._line_width), -1, dtype=np.int64)
flat_of = np.full(layout.slot_line.size, -1, dtype=np.int64)
@@ -131,17 +156,41 @@ def __init__(
self._line_slots = torch.from_numpy(line_slots).to(self.device)
pix_flat = np.where(table >= 0, flat_of[np.maximum(table, 0)], -1)
self._pix_flat = torch.from_numpy(pix_flat).to(self.device)
- self._samples = torch.from_numpy(np.ascontiguousarray(samples)).to(
- self.device
- )
+ self._samples = torch.from_numpy(np.ascontiguousarray(samples)).to(self.device)
@property
def n_pixels(self) -> int:
"""Number of sampled pixels."""
return int(self.pixels.size)
- def _tables(self, times: np.ndarray, dt: int):
- """Local cycle and weight of each (frame, line index, k) sample."""
+ def _tables(
+ self, times: np.ndarray, dt: int
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Local cycle and weight of each (frame, line index, k) sample.
+
+ Parameters
+ ----------
+ times : np.ndarray
+ One-based line times of the frames.
+ dt : int
+ Kernel time constant in lines.
+
+ Returns
+ -------
+ local : np.ndarray
+ (frames, P, k) cycle of each sample, relative to cycle0.
+ w : np.ndarray
+ (frames, P, k) kernel weight of each sample.
+ lines : np.ndarray
+ (frames, P, k) one-based line number of each sample.
+ ok : np.ndarray
+ (frames, P, k) boolean mask of samples inside the kernel.
+
+ Raises
+ ------
+ ValueError
+ If the frame kernel reaches cycles that were not read.
+ """
lay = self.layout
p = lay.lines_per_cycle
dt_read = max(3 * dt, p)
@@ -155,31 +204,50 @@ def _tables(self, times: np.ndarray, dt: int):
c = c_min[:, :, None] + np.arange(k_max)[None, None, :]
ok = c <= c_max[:, :, None]
lines = c * p + line_idx[:, :, None]
- w = np.where(
- ok, np.exp(-np.abs((times[:, None, None] - lines) / dt)), 0.0
- )
+ w = np.where(ok, np.exp(-np.abs((times[:, None, None] - lines) / dt)), 0.0)
local = c - self.cycle0
if np.any(ok & ((local < 0) | (local >= self.n_cycles))):
raise ValueError("frame kernel reaches cycles that were not read")
local = np.clip(local, 0, self.n_cycles - 1)
return local, w, lines, ok
- def _accumulate(self, local, w, channels, band=None):
+ def _accumulate(
+ self,
+ local: np.ndarray,
+ w: np.ndarray,
+ channels: list[int],
+ band: int | None = None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
"""Num and Den at the pixels for given sample cycles and weights.
- ``local`` and ``w`` are ``(frames, P, k)`` NumPy arrays: the local
+ local and w are (frames, P, k) NumPy arrays: the local
cycle and weight of each line index's k-th sample of each frame.
- Frames are taken in groups spanning at most ``band`` cycles (default
- ``self.band``); for each group, every line's samples are weighted by
+ Frames are taken in groups spanning at most band cycles (default
+ self.band); for each group, every line's samples are weighted by
one matrix product (frames x cycles) @ (cycles x slots), in double
precision.
+
+ Parameters
+ ----------
+ local : np.ndarray
+ (frames, P, k) local cycle of each sample.
+ w : np.ndarray
+ (frames, P, k) kernel weight of each sample.
+ channels : list of int
+ Zero-based channels to sum.
+ band : int, optional
+ Most cycles spanned by a group of frames (default: self.band).
+
+ Returns
+ -------
+ num, den : torch.Tensor
+ (channels, frames, pixels) float64 sums of weighted valid
+ samples and of their weights.
"""
band = self.band if band is None else band
dev = self.device
n_f, n_pix = local.shape[0], self.n_pixels
- num = torch.zeros(
- len(channels), n_f, n_pix, dtype=torch.float64, device=dev
- )
+ num = torch.zeros(len(channels), n_f, n_pix, dtype=torch.float64, device=dev)
den = torch.zeros_like(num)
used = w > 0
lo = np.where(used, local, np.iinfo(np.int64).max).min((1, 2))
@@ -196,8 +264,35 @@ def _accumulate(self, local, w, channels, band=None):
)
return num, den
- def _accumulate_band(self, local, w, used, channels, group, num, den):
- """Add one band of frames' sums to ``num`` and ``den`` (in place)."""
+ def _accumulate_band(
+ self,
+ local: np.ndarray,
+ w: np.ndarray,
+ used: np.ndarray,
+ channels: list[int],
+ group: np.ndarray,
+ num: torch.Tensor,
+ den: torch.Tensor,
+ ) -> None:
+ """Add one band of frames' sums to num and den (in place).
+
+ Parameters
+ ----------
+ local : np.ndarray
+ (frames, P, k) local cycle of each sample, for the band's frames.
+ w : np.ndarray
+ (frames, P, k) kernel weight of each sample.
+ used : np.ndarray
+ (frames, P, k) boolean mask of samples with positive weight.
+ channels : list of int
+ Zero-based channels to sum.
+ group : np.ndarray
+ Indices of the band's frames in num and den.
+ num : torch.Tensor
+ (channels, frames, pixels) sums of weighted samples, updated.
+ den : torch.Tensor
+ (channels, frames, pixels) sums of weights, updated.
+ """
dev = self.device
if not used.any():
return
@@ -218,9 +313,7 @@ def _accumulate_band(self, local, w, used, channels, group, num, den):
s_den = torch.bmm(wt, valid.to(torch.float64).transpose(1, 2))
s_num = s_num.permute(1, 0, 2).reshape(nf, -1)
s_den = s_den.permute(1, 0, 2).reshape(nf, -1)
- add_n = torch.zeros(
- nf, self.n_pixels, dtype=torch.float64, device=dev
- )
+ add_n = torch.zeros(nf, self.n_pixels, dtype=torch.float64, device=dev)
add_d = torch.zeros_like(add_n)
for j in range(self._pix_flat.shape[1]):
pos = self._pix_flat[:, j]
@@ -231,8 +324,11 @@ def _accumulate_band(self, local, w, used, channels, group, num, den):
den[k].index_add_(0, rows, add_d)
def sums(
- self, times, dt: int, channels=None
- ) -> Tuple[torch.Tensor, torch.Tensor]:
+ self,
+ times: npt.ArrayLike,
+ dt: int,
+ channels: Sequence[int] | None = None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
"""Weighted sample sums of frames.
Parameters
@@ -247,26 +343,43 @@ def sums(
Returns
-------
num, den : torch.Tensor of float64
- ``(channels, frames, pixels)`` sums of weighted valid samples and
- of their weights (``slap2FrameSums`` Num and Den).
+ (channels, frames, pixels) sums of weighted valid samples and
+ of their weights (slap2FrameSums Num and Den).
"""
times = np.asarray(times, dtype=np.int64).ravel()
channels = self._channels(channels)
local, w, _, _ = self._tables(times, int(dt))
return self._accumulate(local, w, channels)
- def _channels(self, channels) -> list:
- """Zero-based channels, all by default."""
+ def _channels(self, channels: Sequence[int] | None) -> list[int]:
+ """Zero-based channels, all by default.
+
+ Parameters
+ ----------
+ channels : sequence of int or None
+ Requested zero-based channels; None for all.
+
+ Returns
+ -------
+ list[int]
+ The requested channels, or every channel of the layout.
+ """
if channels is None:
return list(range(self.layout.num_channels))
return list(channels)
- def shifted_sums(self, times, dt: int, shift_fn, channels=None):
- """Sums of frames whose samples move by a per-line displacement.
+ def shifted_sums(
+ self,
+ times: npt.ArrayLike,
+ dt: int,
+ shift_fn: Callable[[np.ndarray], tuple[np.ndarray, np.ndarray]],
+ channels: Sequence[int] | None = None,
+ ) -> Iterator[tuple[tuple[int, int], np.ndarray, torch.Tensor, torch.Tensor]]:
+ """Sum frames whose samples move by a per-line displacement.
Each frame's samples are grouped by the integer displacement
- ``shift_fn`` assigns to their line (as ``slap2FrameSums`` does with
- ``CompensateOnline``); each group is summed at the pixels' own
+ shift_fn assigns to their line (as slap2FrameSums does with
+ CompensateOnline); each group is summed at the pixels' own
positions, to be placed at the displaced positions by the caller.
Parameters
@@ -276,7 +389,7 @@ def shifted_sums(self, times, dt: int, shift_fn, channels=None):
dt : int
Kernel time constant in lines.
shift_fn : callable
- ``shift_fn(lines) -> (dr, dc)`` for an ``(frames, P, k)`` array
+ shift_fn(lines) -> (dr, dc) for an (frames, P, k) array
of one-based lines.
channels : sequence of int, optional
Zero-based channels (default: all).
@@ -285,7 +398,7 @@ def shifted_sums(self, times, dt: int, shift_fn, channels=None):
------
(dr, dc), frames, num, den
The displacement, the indices of the frames with samples in the
- group, and the group's Num and Den ``(channels, frames, pixels)``.
+ group, and the group's Num and Den (channels, frames, pixels).
"""
times = np.asarray(times, dtype=np.int64).ravel()
channels = self._channels(channels)
@@ -300,17 +413,29 @@ def shifted_sums(self, times, dt: int, shift_fn, channels=None):
yield (int(r), int(c)), sel, num, den
def frames(
- self, times, dt: int, channels=None
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- """Frames and freshness, as ``slap2Frames`` returns them.
+ self,
+ times: npt.ArrayLike,
+ dt: int,
+ channels: Sequence[int] | None = None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """Frames and freshness, as slap2Frames returns them.
+
+ Parameters
+ ----------
+ times : array_like of int
+ One-based line times of the frames.
+ dt : int
+ Kernel time constant in lines.
+ channels : sequence of int, optional
+ Zero-based channels (default: all).
Returns
-------
values : torch.Tensor of float32
- ``(channels, frames, pixels)`` weighted means, NaN where a pixel
+ (channels, frames, pixels) weighted means, NaN where a pixel
has no valid sample.
freshness : torch.Tensor of float32
- ``(frames, pixels)`` summed weights of the first channel.
+ (frames, pixels) summed weights of the first channel.
"""
num, den = self.sums(times, dt, channels)
values = (num / den).to(torch.float32)
@@ -322,14 +447,14 @@ class PixelFormer(FrameFormer):
Source extraction forms thousands of frames whose kernels each cover a
few cycles. :meth:`pixel_sums` gives the sums of :meth:`sums` and
- :meth:`shifted_sums` (equal to rounding) as ``(channels, pixels,
- frames)``: a pixel's slots are added with one indexed sum per band, and
+ :meth:`shifted_sums` (equal to rounding) as (channels, pixels,
+ frames): a pixel's slots are added with one indexed sum per band, and
the summed weights are formed without the samples where a band has no
invalid sample. On a CPU this is several times faster than the parent's
sums, whose fixed order of additions registration keeps.
"""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None: # noqa: ANN401
"""Map every place of the padded line layout to its pixel."""
super().__init__(*args, **kwargs)
has = self._pix_flat >= 0
@@ -344,19 +469,20 @@ def __init__(self, *args, **kwargs):
)
self._flat_pix[flat] = pix
self._slot_pix = pix
- self._slot_line = torch.div(
- flat, self._line_width, rounding_mode="floor"
- )
+ self._slot_line = torch.div(flat, self._line_width, rounding_mode="floor")
def pixel_sums(
self,
- times,
+ times: npt.ArrayLike,
dt: int,
- channels=None,
- shift_fn=None,
+ channels: Sequence[int] | None = None,
+ shift_fn: Callable[[np.ndarray], tuple[np.ndarray, np.ndarray]] | None = None,
return_w2: bool = False,
- ):
- """Sums of frames, grouped by the displacement of their samples.
+ ) -> Iterator[
+ tuple[tuple[int, int], np.ndarray, torch.Tensor, torch.Tensor]
+ | tuple[tuple[int, int], np.ndarray, torch.Tensor, torch.Tensor, torch.Tensor]
+ ]:
+ """Sum frames, grouped by the displacement of their samples.
Parameters
----------
@@ -367,19 +493,19 @@ def pixel_sums(
channels : sequence of int, optional
Zero-based channels (default: all).
shift_fn : callable, optional
- ``shift_fn(lines) -> (dr, dc)`` as for :meth:`shifted_sums`.
+ shift_fn(lines) -> (dr, dc) as for :meth:`shifted_sums`.
Default: no displacement, one group of all frames.
return_w2 : bool
- Also yield channel 0's summed squared kernel weights ``den2``
- ``(pixels, frames)`` for pooling-conserved variance factors.
+ Also yield channel 0's summed squared kernel weights den2
+ (pixels, frames) for pooling-conserved variance factors.
Yields
------
(dr, dc), frames, num, den[, den2]
The displacement, the indices of the frames with samples in the
- group, and the group's Num and Den ``(channels, pixels,
- frames)`` at the pixels' own positions (plus ``den2`` when
- ``return_w2`` is True).
+ group, and the group's Num and Den (channels, pixels,
+ frames) at the pixels' own positions (plus den2 when
+ return_w2 is True).
"""
times = np.asarray(times, dtype=np.int64).ravel()
channels = self._channels(channels)
@@ -397,16 +523,37 @@ def pixel_sums(
got = self._pixel_accumulate(local[sel], wg, channels, return_w2)
yield (int(r), int(c)), sel, *got
- def _pixel_accumulate(self, local, w, channels, return_w2: bool = False):
- """Num and Den ``(channels, pixels, frames)``, band by band."""
+ def _pixel_accumulate(
+ self,
+ local: np.ndarray,
+ w: np.ndarray,
+ channels: list[int],
+ return_w2: bool = False,
+ ) -> tuple[torch.Tensor, ...]:
+ """Num and Den (channels, pixels, frames), band by band.
+
+ Parameters
+ ----------
+ local : np.ndarray
+ (frames, P, k) local cycle of each sample.
+ w : np.ndarray
+ (frames, P, k) kernel weight of each sample.
+ channels : list of int
+ Zero-based channels to sum.
+ return_w2 : bool
+ Also return channel 0's summed squared kernel weights.
+
+ Returns
+ -------
+ tuple[torch.Tensor, ...]
+ (num, den), or (num, den, den2) when return_w2 is True;
+ num and den are (channels, pixels, frames) and den2
+ is (pixels, frames).
+ """
size = (len(channels), self.n_pixels, local.shape[0])
num = torch.zeros(size, dtype=torch.float64, device=self.device)
den = torch.zeros_like(num)
- den2 = (
- torch.zeros(size[1:], dtype=torch.float64, device=self.device)
- if return_w2
- else None
- )
+ den2 = torch.zeros(size[1:], dtype=torch.float64, device=self.device) if return_w2 else None
used = w > 0
lo = np.where(used, local, np.iinfo(np.int64).max).min((1, 2))
hi = np.where(used, local, -1).max((1, 2))
@@ -423,8 +570,21 @@ def _pixel_accumulate(self, local, w, channels, return_w2: bool = False):
)
return (num, den, den2) if return_w2 else (num, den)
- def _to_pixels(self, sums: torch.Tensor, index: torch.Tensor):
- """Add rows of ``sums`` (places, frames) into their pixels."""
+ def _to_pixels(self, sums: torch.Tensor, index: torch.Tensor) -> torch.Tensor:
+ """Add rows of sums (places, frames) into their pixels.
+
+ Parameters
+ ----------
+ sums : torch.Tensor
+ (places, frames) sums at each place of the padded line layout.
+ index : torch.Tensor
+ Pixel of each place; padded places map to an extra, dropped pixel.
+
+ Returns
+ -------
+ torch.Tensor
+ (pixels, frames) float64 sums per pixel.
+ """
out = torch.zeros(
self.n_pixels + 1,
sums.shape[1],
@@ -433,17 +593,56 @@ def _to_pixels(self, sums: torch.Tensor, index: torch.Tensor):
)
return out.index_add_(0, index, sums)[: self.n_pixels]
- def _add_frames(self, total, group, part) -> None:
- """Add a band's ``(pixels, frames)`` sums into its frames."""
+ def _add_frames(self, total: torch.Tensor, group: np.ndarray, part: torch.Tensor) -> None:
+ """Add a band's (pixels, frames) sums into its frames.
+
+ Parameters
+ ----------
+ total : torch.Tensor
+ (pixels, frames) sums, updated in place.
+ group : np.ndarray
+ Indices of the band's frames in total.
+ part : torch.Tensor
+ (pixels, band frames) sums to add.
+ """
if group.size and np.all(np.diff(group) == 1):
total[:, int(group[0]) : int(group[-1]) + 1] += part
else:
total.index_add_(1, torch.from_numpy(group).to(self.device), part)
def _pixel_band(
- self, local, w, used, channels, group, num, den, den2=None
- ):
- """Add one band of frames' sums to ``num`` and ``den`` (in place)."""
+ self,
+ local: np.ndarray,
+ w: np.ndarray,
+ used: np.ndarray,
+ channels: list[int],
+ group: np.ndarray,
+ num: torch.Tensor,
+ den: torch.Tensor,
+ den2: torch.Tensor | None = None,
+ ) -> None:
+ """Add one band of frames' sums to num and den (in place).
+
+ Parameters
+ ----------
+ local : np.ndarray
+ (frames, P, k) local cycle of each sample, for the band's frames.
+ w : np.ndarray
+ (frames, P, k) kernel weight of each sample.
+ used : np.ndarray
+ (frames, P, k) boolean mask of samples with positive weight.
+ channels : list of int
+ Zero-based channels to sum.
+ group : np.ndarray
+ Indices of the band's frames in num, den and den2.
+ num : torch.Tensor
+ (channels, pixels, frames) sums of weighted samples, updated.
+ den : torch.Tensor
+ (channels, pixels, frames) sums of weights, updated.
+ den2 : torch.Tensor, optional
+ (pixels, frames) channel 0 sums of squared weights, updated
+ when given.
+ """
if not used.any() or self._slot_pix.numel() == 0:
return
c0 = int(local[used].min())
@@ -461,15 +660,11 @@ def _pixel_band(
valid = x != INVALID_SAMPLE
xv = torch.where(valid, x, 0).to(torch.float64)
s_num = torch.bmm(xv, wt).reshape(-1, nf) # places, F
- self._add_frames(
- num[k], group, self._to_pixels(s_num, self._flat_pix)
- )
+ self._add_frames(num[k], group, self._to_pixels(s_num, self._flat_pix))
all_valid = bool(valid.all())
if all_valid:
if den_valid is None:
- den_valid = self._to_pixels(
- wt.sum(1)[self._slot_line], self._slot_pix
- )
+ den_valid = self._to_pixels(wt.sum(1)[self._slot_line], self._slot_pix)
d = den_valid
else:
v_f64 = valid.to(torch.float64)
@@ -478,9 +673,7 @@ def _pixel_band(
self._add_frames(den[k], group, d)
if k == 0 and wt2 is not None:
if all_valid:
- d2 = self._to_pixels(
- wt2.sum(1)[self._slot_line], self._slot_pix
- )
+ d2 = self._to_pixels(wt2.sum(1)[self._slot_line], self._slot_pix)
else:
s_d2 = torch.bmm(valid.to(torch.float64), wt2)
d2 = self._to_pixels(s_d2.reshape(-1, nf), self._flat_pix)
diff --git a/src/giant_python/registration/growth.py b/src/giant_python/registration/growth.py
index 583c5946..b1d4af16 100644
--- a/src/giant_python/registration/growth.py
+++ b/src/giant_python/registration/growth.py
@@ -9,27 +9,27 @@
template are matched first, starting from their consensus motion. Each
becomes an *island* of aligned frames.
2. *Wavefront.* Each sub-round takes, from every island edge, the next
- unaligned frame outward (``frames_per_front`` of them), starting from the
- edge frame's rounded motion with a search radius of ``clip_shift``. All
+ unaligned frame outward (frames_per_front of them), starting from the
+ edge frame's rounded motion with a search radius of clip_shift. All
are matched to the current template in one batch; their registered
images are then added to the template.
3. *Boundary retries.* A frame whose correlation peak lies on the edge of
its search range is matched again in the next sub-round, from that peak
- with a doubled radius (up to ``maxshift``).
-4. *New seeds.* When fewer than ``min_fronts`` fronts remain, or a gap
+ with a doubled radius (up to maxshift).
+4. *New seeds.* When fewer than min_fronts fronts remain, or a gap
between islands is more than twice the median gap, frames at the middle
- of the longest gaps are matched over the whole ``maxshift`` range (FFT).
+ of the longest gaps are matched over the whole maxshift range (FFT).
They become islands only if their peak correlation and peak margin are
- at least the ``seed_accept_quantile`` of the aligned frames', the peak is
+ at least the seed_accept_quantile of the aligned frames', the peak is
not on a search edge, and their motion is plausible given the nearest
aligned frames; otherwise growth reaches them later.
5. *Junctions.* Where two islands meet, a jump in motion larger than
- ``junction_jump_px`` (default: ``max(1, 99.9th percentile of per-frame
- steps)``) means one island may have locked onto a wrong peak: the island
+ junction_jump_px (default: max(1, 99.9th percentile of per-frame
+ steps)) means one island may have locked onto a wrong peak: the island
with the lower median correlation is realigned from the other, and the
solution with the higher mean correlation is kept.
6. *Polish* (optional): every frame is matched again, within
- ``polish_radius`` of its motion, to the final template without its own
+ polish_radius of its motion, to the final template without its own
contribution.
Frames without valid samples are left out of growth (they neither seed nor
@@ -38,17 +38,18 @@
"""
import logging
+from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
-from typing import List, Optional
import numpy as np
import torch
+from ..models.params import MultiRoiRegistrationParams
from .interpolation import interp_frame
from .matching import match_maps, peak_index, peak_margin, wide_correlation
from .outputs import matlab_round
-from .sources import has_samples
-from .template import TemplateState
+from .sources import CompensatedFrames, PlainFrames, has_samples
+from .template import ConsensusResult, TemplateState
log = logging.getLogger(__name__)
@@ -72,8 +73,12 @@ class FrameCache:
"""
def __init__(
- self, source, ds, chunk: int = 64, max_device_bytes: float = 3e9
- ):
+ self,
+ source: PlainFrames | CompensatedFrames,
+ ds: np.ndarray,
+ chunk: int = 64,
+ max_device_bytes: float = 3e9,
+ ) -> None:
"""Form and store all frames."""
self.window = source.window
self.device = source.former.device
@@ -91,34 +96,70 @@ def __init__(
self.freshness[a:b] = f.to(store)
def __len__(self) -> int:
- """Number of frames."""
+ """Return the number of frames.
+
+ Returns
+ -------
+ int
+ The number of frames in the cache.
+ """
return self.freshness.shape[0]
def present(self) -> np.ndarray:
- """Which frames have at least one valid sample."""
+ """Which frames have at least one valid sample.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean per frame: True where the frame has a valid sample.
+ """
return has_samples(self.values)
- def keep(self, mask) -> None:
- """Keep only the frames selected by the boolean ``mask``."""
+ def keep(self, mask: np.ndarray) -> None:
+ """Keep only the frames selected by the boolean mask."""
sel = torch.as_tensor(np.flatnonzero(mask), device=self.values.device)
self.values = self.values[:, sel]
self.freshness = self.freshness[sel]
- def batch(self, idx):
- """``(channels, B, pixels)`` values and ``(B, pixels)`` freshness."""
+ def batch(self, idx: Sequence[int]) -> tuple[torch.Tensor, torch.Tensor]:
+ """(channels, B, pixels) values and (B, pixels) freshness.
+
+ Returns
+ -------
+ values : torch.Tensor
+ (channels, B, pixels) values of the frames idx, on the cache's device.
+ freshness : torch.Tensor
+ (B, pixels) freshness of the same frames.
+ """
sel = torch.as_tensor(np.asarray(idx), device=self.values.device)
return (
self.values[:, sel].to(self.device),
self.freshness[sel].to(self.device),
)
- def moving(self, idx):
- """Matching image ``sqrt(sum of channels)`` and freshness."""
+ def moving(self, idx: Sequence[int]) -> tuple[torch.Tensor, torch.Tensor]:
+ """Return the matching image sqrt(sum of channels) and freshness.
+
+ Returns
+ -------
+ image : torch.Tensor
+ (B, pixels) matching image: the root of the channels' sum.
+ freshness : torch.Tensor
+ (B, pixels) freshness of the frames idx.
+ """
vals, fresh = self.batch(idx)
return torch.sqrt(vals.sum(0)), fresh
- def registered(self, k: int, motion, margin: int):
- """Registered channels and variance factor of frame ``k``."""
+ def registered(
+ self, k: int, motion: np.ndarray, margin: int
+ ) -> list[tuple[torch.Tensor, torch.Tensor]]:
+ """Register the channels and variance factor of frame k.
+
+ Returns
+ -------
+ list
+ One (image, freshness) pair of registered tensors per channel.
+ """
vals, fresh = self.batch([k])
fimg = self.window.image(fresh[0], 0.0)
out = []
@@ -127,8 +168,14 @@ def registered(self, k: int, motion, margin: int):
out.append(interp_frame(img, fimg, motion[0], motion[1], margin))
return out
- def registered_sum(self, ks, motions, margin: int) -> torch.Tensor:
- """``(B, H + 2m, W + 2m)`` registered channel sums of frames."""
+ def registered_sum(self, ks: np.ndarray, motions: np.ndarray, margin: int) -> torch.Tensor:
+ """(B, H + 2m, W + 2m) registered channel sums of frames.
+
+ Returns
+ -------
+ torch.Tensor
+ The registered channel sum of each frame in ks; empty (zero frames) when ks is.
+ """
imgs = []
for k, mot in zip(ks, motions):
regs = self.registered(int(k), mot, margin)
@@ -138,9 +185,7 @@ def registered_sum(self, ks, motions, margin: int) -> torch.Tensor:
imgs.append(total)
h, w = self.window.shape
if not imgs:
- return torch.empty(
- 0, h + 2 * margin, w + 2 * margin, device=self.device
- )
+ return torch.empty(0, h + 2 * margin, w + 2 * margin, device=self.device)
return torch.stack(imgs)
@@ -160,10 +205,10 @@ class GrowthQC:
retries : ndarray of int
Boundary retries.
kind : ndarray of int
- ``GROWN``, ``CONSENSUS``, ``SEED``, ``REGROWN``, ``AT_LIMIT`` or
- ``MISSING`` (no valid samples; not registered).
+ GROWN, CONSENSUS, SEED, REGROWN, AT_LIMIT or
+ MISSING (no valid samples; not registered).
junctions : list
- ``(frame, neighbour, jump, outcome)`` for each conflicting junction.
+ (frame, neighbour, jump, outcome) for each conflicting junction.
seeds_tried, seeds_accepted : int
Wide-search seed candidates and how many became islands.
"""
@@ -174,12 +219,20 @@ class GrowthQC:
anchor: np.ndarray
retries: np.ndarray
kind: np.ndarray
- junctions: List[tuple] = field(default_factory=list)
+ junctions: list[tuple] = field(default_factory=list)
seeds_tried: int = 0
seeds_accepted: int = 0
def fields(self) -> dict:
- """The record as alignment-file fields (MATLAB-style names)."""
+ """Return the record as alignment-file fields (MATLAB-style names).
+
+ Returns
+ -------
+ dict
+ The record's arrays and counts under the alignment file's names (peakCorr,
+ peakMargin, round, anchor (one-based), retries, kind,
+ seedsTried, seedsAccepted and junctionConflicts).
+ """
return {
"peakCorr": self.peak,
"peakMargin": self.margin,
@@ -194,7 +247,13 @@ def fields(self) -> dict:
@classmethod
def missing(cls, n: int) -> "GrowthQC":
- """The record of ``n`` frames none of which has samples."""
+ """Build the record of n frames none of which has samples.
+
+ Returns
+ -------
+ GrowthQC
+ The record with every frame MISSING and NaN peaks and margins.
+ """
return cls(
peak=np.full(n, np.nan),
margin=np.full(n, np.nan),
@@ -205,10 +264,15 @@ def missing(cls, n: int) -> "GrowthQC":
)
def expanded(self, present: np.ndarray) -> "GrowthQC":
- """This record of the ``present`` frames, over all frames.
+ """Expand this record of the present frames over all frames.
Frame indices (anchors, junctions) are mapped back; the other
- frames are ``MISSING``.
+ frames are MISSING.
+
+ Returns
+ -------
+ GrowthQC
+ The record over all frames (self when every frame is present).
"""
if present.all():
return self
@@ -217,14 +281,11 @@ def expanded(self, present: np.ndarray) -> "GrowthQC":
out.peak[idx] = self.peak
out.margin[idx] = self.margin
out.round[idx] = self.round
- out.anchor[idx] = np.where(
- self.anchor >= 0, idx[np.maximum(self.anchor, 0)], -1
- )
+ out.anchor[idx] = np.where(self.anchor >= 0, idx[np.maximum(self.anchor, 0)], -1)
out.retries[idx] = self.retries
out.kind[idx] = self.kind
out.junctions = [
- (int(idx[k]), int(idx[g]), jump, outcome)
- for k, g, jump, outcome in self.junctions
+ (int(idx[k]), int(idx[g]), jump, outcome) for k, g, jump, outcome in self.junctions
]
out.seeds_tried = self.seeds_tried
out.seeds_accepted = self.seeds_accepted
@@ -241,10 +302,10 @@ class Grower:
state : TemplateState
Initial template (its sums include the consensus frames).
params : MultiRoiRegistrationParams
- Settings (``clip_shift``, ``maxshift``, growth options).
+ Settings (clip_shift, maxshift, growth options).
seeds : list of (int, int, int)
Consensus seeds: frame index and starting [row, col] motion
- (clamped to ``maxshift``, like every other starting shift).
+ (clamped to maxshift, like every other starting shift).
candidates : sequence of int
Further seed candidates (frames nearest the other initial frames).
dtype : torch.dtype
@@ -259,12 +320,12 @@ def __init__(
self,
cache: FrameCache,
state: TemplateState,
- params,
- seeds,
- candidates,
- dtype=torch.float32,
- independent=None,
- ):
+ params: MultiRoiRegistrationParams,
+ seeds: list[tuple[int, int, int]],
+ candidates: Sequence[int],
+ dtype: torch.dtype = torch.float32,
+ independent: np.ndarray | None = None,
+ ) -> None:
"""Set up per-frame state."""
self.cache = cache
self.state = state
@@ -287,21 +348,21 @@ def __init__(
)
self.seeds = [(int(k), *self._init_of((r, c))) for k, r, c in seeds]
self.candidates = [int(k) for k in candidates]
- self.independent = (
- np.ones(n, dtype=bool) if independent is None else independent
- )
+ self.independent = np.ones(n, dtype=bool) if independent is None else independent
self.tried = set()
self.retry = {} # frame -> (init_r, init_c, search, anchor)
self.sub_round = 0
# ----------------------------------------------------------- matching
- def _match(self, items):
- """Match ``(frame, init_r, init_c, search)`` items in init groups.
+ def _match(
+ self, items: list[tuple[int, int, int, int]]
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Match (frame, init_r, init_c, search) items in init groups.
Returns
-------
motion : ndarray
- ``(len(items), 2)`` motion.
+ (len(items), 2) motion.
peak, margin : ndarray
Peak correlation and margin.
edge : ndarray of bool
@@ -325,9 +386,7 @@ def _match(self, items):
ks = [items[i][0] for i in idx]
mov, fresh = self.cache.moving(ks)
crop = tmpl[m - r : m - r + h, m - c : m - c + w]
- mot, pk, corr = match_maps(
- mov, fresh, crop, win.rows, win.cols, s, self.dtype
- )
+ mot, pk, corr = match_maps(mov, fresh, crop, win.rows, win.cols, s, self.dtype)
rr, cc, _ = peak_index(corr)
on_edge = (rr == 0) | (rr == 2 * s) | (cc == 0) | (cc == 2 * s)
motion[idx] = mot.cpu().numpy() + np.array([r, c])
@@ -336,14 +395,31 @@ def _match(self, items):
edge[idx] = on_edge.cpu().numpy()
return motion, peak, margin, edge
- def _init_of(self, motion):
- """Rounded, clamped starting shift from a motion estimate."""
+ def _init_of(self, motion: np.ndarray | Sequence[float]) -> tuple[int, int]:
+ """Round and clamp a motion estimate to a starting shift.
+
+ Returns
+ -------
+ row : int
+ The rounded row shift, within +-maxshift.
+ col : int
+ The rounded column shift, within +-maxshift.
+ """
r = int(np.clip(matlab_round(motion[0]), -self.m, self.m))
c = int(np.clip(matlab_round(motion[1]), -self.m, self.m))
return r, c
# ---------------------------------------------------------- accepting
- def _accept(self, ks, motions, peaks, margins, anchors, kinds, roots):
+ def _accept(
+ self,
+ ks: Sequence[int] | np.ndarray,
+ motions: np.ndarray,
+ peaks: np.ndarray,
+ margins: np.ndarray,
+ anchors: Sequence[int] | np.ndarray,
+ kinds: Sequence[int] | np.ndarray,
+ roots: Sequence[int] | np.ndarray,
+ ) -> None:
"""Record aligned frames and add them to the template."""
ks = np.asarray(ks, dtype=np.int64)
if ks.size == 0:
@@ -358,13 +434,11 @@ def _accept(self, ks, motions, peaks, margins, anchors, kinds, roots):
self.root[ks] = roots
for i, (k, a) in enumerate(zip(ks, anchors)):
if a >= 0:
- self.step[k] = np.hypot(*(motions[i] - self.motion[a])) / abs(
- k - a
- )
+ self.step[k] = np.hypot(*(motions[i] - self.motion[a])) / abs(k - a)
imgs = self.cache.registered_sum(ks, motions, self.m)
self.state.update(imgs)
- def _withdraw(self, ks):
+ def _withdraw(self, ks: Sequence[int] | np.ndarray) -> None:
"""Remove aligned frames from the template and mark them unaligned."""
ks = np.asarray(ks, dtype=np.int64)
imgs = self.cache.registered_sum(ks, self.motion[ks], self.m)
@@ -372,7 +446,7 @@ def _withdraw(self, ks):
self.aligned[ks] = False
# -------------------------------------------------------------- seeds
- def _seed_round(self):
+ def _seed_round(self) -> None:
"""Match the consensus seeds (sub-round 0)."""
items = [(k, r, c, self.p.clip_shift) for k, r, c in self.seeds]
self._run_items(
@@ -383,14 +457,27 @@ def _seed_round(self):
)
def _step_limit(self) -> float:
- """Plausible motion change per frame (99.9th percentile of steps)."""
+ """Plausible motion change per frame (99.9th percentile of steps).
+
+ Returns
+ -------
+ float
+ The 99.9th percentile of the frames' steps (at least 0.25); 1.0 with under 50 steps.
+ """
steps = self.step[np.isfinite(self.step)]
if steps.size < 50:
return 1.0
return max(0.25, float(np.quantile(steps, 0.999)))
- def _plausible(self, k: int, motion) -> bool:
- """Whether a seed's motion fits the nearest aligned frames."""
+ def _plausible(self, k: int, motion: np.ndarray) -> bool:
+ """Whether a seed's motion fits the nearest aligned frames.
+
+ Returns
+ -------
+ bool
+ True when the motion is within the plausible step of the nearest aligned frame on each
+ side.
+ """
v = self._step_limit()
al = np.flatnonzero(self.aligned)
for side in (al[al < k][-1:], al[al > k][:1]):
@@ -399,16 +486,10 @@ def _plausible(self, k: int, motion) -> bool:
return False
return True
- def try_seeds(self, ks):
+ def try_seeds(self, ks: Iterable[int]) -> None:
"""Wide-search seed candidates; accept those passing the checks."""
# each frame once: a frame matched twice would be added twice
- ks = list(
- dict.fromkeys(
- int(k)
- for k in ks
- if not self.aligned[k] and k not in self.tried
- )
- )
+ ks = list(dict.fromkeys(int(k) for k in ks if not self.aligned[k] and k not in self.tried))
if not ks:
return
self.tried.update(ks)
@@ -456,7 +537,13 @@ def try_seeds(self, ks):
self.qc.seeds_accepted += len(ok)
def _calibration_set(self) -> np.ndarray:
- """Grown frames independent of the initial template's samples."""
+ """Grown frames independent of the initial template's samples.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean per frame: aligned, independent, with a finite peak, and grown or regrown.
+ """
return (
self.aligned
& self.independent
@@ -465,11 +552,23 @@ def _calibration_set(self) -> np.ndarray:
)
def _calibrated(self) -> bool:
- """Whether enough frames were grown to judge seed candidates."""
+ """Whether enough frames were grown to judge seed candidates.
+
+ Returns
+ -------
+ bool
+ True when the calibration set holds at least 100 frames.
+ """
return int(self._calibration_set().sum()) >= 100
- def _gap_candidates(self, fronts: int):
- """Middle frames of the gaps that most need a seed."""
+ def _gap_candidates(self, fronts: int) -> list[int]:
+ """Middle frames of the gaps that most need a seed.
+
+ Returns
+ -------
+ list
+ Up to 8 frame indices, one at the middle of each of the longest gaps between islands.
+ """
gaps = _runs(~self.aligned)
if not gaps:
return []
@@ -491,8 +590,15 @@ def _gap_candidates(self, fronts: int):
return out
# ------------------------------------------------------------- growth
- def _fronts(self):
- """``(frame, anchor)`` for the next frames outward of every island."""
+ def _fronts(self) -> list[tuple[int, int]]:
+ """(frame, anchor) for the next frames outward of every island.
+
+ Returns
+ -------
+ list
+ (frame, anchor) pairs sorted by frame: each unaligned frame next to an island's edge
+ with the edge frame (of higher peak correlation) that anchors it.
+ """
k_front = int(self.p.frames_per_front)
targets = {}
for a, b in _runs(self.aligned):
@@ -508,8 +614,20 @@ def _fronts(self):
targets[f] = edge
return sorted(targets.items())
- def _run_items(self, items, anchors, kind, roots):
- """Match items; accept, or queue boundary retries."""
+ def _run_items(
+ self,
+ items: list[tuple[int, int, int, int]],
+ anchors: Sequence[int],
+ kind: int,
+ roots: Sequence[int],
+ ) -> list[int]:
+ """Match items; accept, or queue boundary retries.
+
+ Returns
+ -------
+ list
+ The frames of the items that were accepted (those queued for a retry are not).
+ """
motion, peak, margin, edge = self._match(items)
acc = []
for i, (k, r, c, s) in enumerate(items):
@@ -540,7 +658,7 @@ def _run_items(self, items, anchors, kind, roots):
)
return [items[i][0] for i in acc]
- def _sub_round(self):
+ def _sub_round(self) -> None:
"""One wavefront step: retries plus one frame per front."""
self.sub_round += 1
fronts = self._fronts()
@@ -587,12 +705,18 @@ def _sub_round(self):
# ---------------------------------------------------------- junctions
def _jump_limit(self) -> float:
- """Largest plausible motion jump between adjacent frames."""
+ """Largest plausible motion jump between adjacent frames.
+
+ Returns
+ -------
+ float
+ junction_jump_px when set, else max(1, step limit).
+ """
if self.p.junction_jump_px is not None:
return float(self.p.junction_jump_px)
return max(1.0, self._step_limit())
- def _check_junctions(self, ks):
+ def _check_junctions(self, ks: Sequence[int]) -> None:
"""Resolve junctions formed by newly aligned frames."""
limit = self._jump_limit()
for k in ks:
@@ -606,8 +730,20 @@ def _check_junctions(self, ks):
if jump > limit:
self._resolve(k, g, jump)
- def _chain(self, order, start):
- """Realign frames one by one, each from the previous one's motion."""
+ def _chain(
+ self, order: np.ndarray, start: np.ndarray
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Realign frames one by one, each from the previous one's motion.
+
+ Returns
+ -------
+ motion : np.ndarray
+ (len(order), 2) [row, col] motion of the frames in order.
+ peak : np.ndarray
+ Peak correlation of each frame.
+ margin : np.ndarray
+ Peak margin of each frame.
+ """
motion = np.zeros((len(order), 2))
peak = np.zeros(len(order))
margin = np.zeros(len(order))
@@ -627,8 +763,8 @@ def _chain(self, order, start):
prev = mot[0]
return motion, peak, margin
- def _resolve(self, k: int, g: int, jump: float):
- """Realign the weaker of the islands meeting at ``(k, g)``.
+ def _resolve(self, k: int, g: int, jump: float) -> None:
+ """Realign the weaker of the islands meeting at (k, g).
The weaker island (lower median peak correlation) is withdrawn from
the template and realigned frame by frame from the stronger side.
@@ -650,16 +786,11 @@ def _resolve(self, k: int, g: int, jump: float):
}
self._withdraw(order)
new = self._chain(order, self.motion[strong])
- old = self._match(
- [
- (int(f), *self._init_of(mo), 1)
- for f, mo in zip(order, saved["motion"])
- ]
- )
+ old = self._match([
+ (int(f), *self._init_of(mo), 1) for f, mo in zip(order, saved["motion"])
+ ])
better = np.nanmean(new[1]) > np.nanmean(old[1])
- self.qc.junctions.append(
- (int(k), int(g), jump, "regrown" if better else "kept")
- )
+ self.qc.junctions.append((int(k), int(g), jump, "regrown" if better else "kept"))
if better:
anchors = np.concatenate([[strong], order[:-1]])
self._accept(
@@ -685,15 +816,21 @@ def _resolve(self, k: int, g: int, jump: float):
self.step[order] = saved["step"]
# ---------------------------------------------------------------- run
- def run(self, max_rounds: Optional[int] = None):
+ def run(self, max_rounds: int | None = None) -> tuple[np.ndarray, GrowthQC]:
"""Align every frame.
Returns
-------
motion : ndarray
- ``(frames, 2)`` [row, col] motion.
+ (frames, 2) [row, col] motion.
qc : GrowthQC
How each frame was registered.
+
+ Raises
+ ------
+ RuntimeError
+ If the growth has not aligned every frame after max_rounds sub-rounds
+ (default 4 * n + 10).
"""
self._seed_round()
limit = max_rounds or 4 * self.n + 10
@@ -702,8 +839,7 @@ def run(self, max_rounds: Optional[int] = None):
raise RuntimeError("growth did not converge")
self._sub_round()
log.info(
- "grown in %d sub-rounds; %d of %d seed candidates accepted; "
- "%d junction conflicts",
+ "grown in %d sub-rounds; %d of %d seed candidates accepted; %d junction conflicts",
self.sub_round,
self.qc.seeds_accepted,
self.qc.seeds_tried,
@@ -711,8 +847,14 @@ def run(self, max_rounds: Optional[int] = None):
)
return self.motion, self.qc
- def polish(self, radius: int):
- """Rematch every frame near its motion to the template without it."""
+ def polish(self, radius: int) -> np.ndarray:
+ """Rematch every frame near its motion to the template without it.
+
+ Returns
+ -------
+ np.ndarray
+ (frames, 2) [row, col] motion after the rematch.
+ """
st = self.state
h, w = self.cache.window.shape
m = self.m
@@ -722,9 +864,7 @@ def polish(self, radius: int):
sel = ~torch.isnan(img)
total = st.total - torch.where(sel, img, 0.0).to(st.total.dtype)
count = st.count - sel.to(st.count.dtype)
- loo = torch.sqrt(total / count).masked_fill(
- count < st.min_samples, float("nan")
- )
+ loo = torch.sqrt(total / count).masked_fill(count < st.min_samples, float("nan"))
both = (st.initial + loo) / 2
tmpl = torch.where(torch.isnan(st.initial), loo, both)
tmpl = torch.where(torch.isnan(loo), st.initial, tmpl)
@@ -746,13 +886,21 @@ def polish(self, radius: int):
return self.motion
-def _runs(mask: np.ndarray):
- """``(start, stop)`` of the runs of True in a boolean array."""
+def _runs(mask: np.ndarray) -> list[tuple[int, int]]:
+ """(start, stop) of the runs of True in a boolean array.
+
+ Returns
+ -------
+ list
+ One (start, stop) pair per run, stop being one past the last True.
+ """
d = np.diff(np.concatenate([[0], mask.astype(np.int8), [0]]))
return list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1)))
-def seeds_from_consensus(cons, init, ds, reach=None):
+def seeds_from_consensus(
+ cons: ConsensusResult, init: np.ndarray, ds: np.ndarray, reach: int | None = None
+) -> tuple[list[tuple[int, int, int]], list[int], np.ndarray]:
"""Consensus seeds and other candidates as DS frame indices.
Parameters
@@ -768,19 +916,17 @@ def seeds_from_consensus(cons, init, ds, reach=None):
-------
seeds : list of (int, int, int)
DS frame nearest each consensus member, with the member's motion
- relative to the reference (``-motion[:, i, ref]``), rounded.
+ relative to the reference (-motion[:, i, ref]), rounded.
candidates : list of int
DS frames nearest the other initial frames, each listed once.
independent : ndarray of bool
- DS frames more than ``reach`` lines (two kernel half-widths) from
+ DS frames more than reach lines (two kernel half-widths) from
every consensus member, so sharing none of its samples (all frames
- when ``reach`` is None).
+ when reach is None).
"""
near = np.clip(np.searchsorted(ds, init), 0, ds.size - 1)
left = np.clip(near - 1, 0, ds.size - 1)
- near = np.where(
- np.abs(ds[left] - init) <= np.abs(ds[near] - init), left, near
- )
+ near = np.where(np.abs(ds[left] - init) <= np.abs(ds[near] - init), left, near)
ref = cons.reference
seeds, taken = [], set()
for i in cons.members:
@@ -790,12 +936,10 @@ def seeds_from_consensus(cons, init, ds, reach=None):
taken.add(k)
mot = -cons.motion[:, i, ref]
seeds.append((k, int(matlab_round(mot[0])), int(matlab_round(mot[1]))))
- members = set(int(i) for i in cons.members)
+ members = {int(i) for i in cons.members}
candidates = list(
dict.fromkeys(
- int(near[i])
- for i in range(init.size)
- if i not in members and int(near[i]) not in taken
+ int(near[i]) for i in range(init.size) if i not in members and int(near[i]) not in taken
)
)
independent = np.ones(ds.size, dtype=bool)
diff --git a/src/giant_python/registration/interpolation.py b/src/giant_python/registration/interpolation.py
index 4d9f9b9d..e960b335 100644
--- a/src/giant_python/registration/interpolation.py
+++ b/src/giant_python/registration/interpolation.py
@@ -1,26 +1,29 @@
"""Freshness-weighted bilinear resampling of a frame by a rigid shift.
-Equivalent to GIAnT-MATLAB ``interpFrame``: the output pixel ``(i, j)``
-(one-based, ``i = 1 .. H + 2m``) samples the frame at row ``i - m + r`` and
-column ``j - m + c``. Each of the four neighbours is weighted by its
+Equivalent to GIAnT-MATLAB interpFrame: the output pixel (i, j)
+(one-based, i = 1 .. H + 2m) samples the frame at row i - m + r and
+column j - m + c. Each of the four neighbours is weighted by its
bilinear coefficient times its freshness; a neighbour outside the frame makes
the output NaN, as does a NaN neighbour (even one with zero weight). The
variance factor is the reciprocal of the summed weights.
"""
import math
-from typing import Tuple
import numpy as np
import torch
-def _corner(x: torch.Tensor, ri: torch.Tensor, ci: torch.Tensor):
- """Values at rows ``ri`` and columns ``ci``, NaN outside ``x``."""
+def _corner(x: torch.Tensor, ri: torch.Tensor, ci: torch.Tensor) -> torch.Tensor:
+ """Values at rows ri and columns ci, NaN outside x.
+
+ Returns
+ -------
+ torch.Tensor
+ (len(ri), len(ci)) values of x, NaN where a row or column is outside it.
+ """
h, w = x.shape
- out = x.index_select(0, ri.clamp(0, h - 1)).index_select(
- 1, ci.clamp(0, w - 1)
- )
+ out = x.index_select(0, ri.clamp(0, h - 1)).index_select(1, ci.clamp(0, w - 1))
bad_r = (ri < 0) | (ri >= h)
bad_c = (ci < 0) | (ci >= w)
out = out.masked_fill(bad_r[:, None], float("nan"))
@@ -33,26 +36,26 @@ def interp_frame(
motion_r: float,
motion_c: float,
margin: int,
-) -> Tuple[torch.Tensor, torch.Tensor]:
+) -> tuple[torch.Tensor, torch.Tensor]:
"""Resample one frame onto the padded output grid.
Parameters
----------
frame : torch.Tensor
- ``(H, W)`` float32 frame, NaN where unsampled.
+ (H, W) float32 frame, NaN where unsampled.
freshness : torch.Tensor
- ``(H, W)`` float32 freshness, 0 where unsampled.
+ (H, W) float32 freshness, 0 where unsampled.
motion_r, motion_c : float
Row and column offsets added to the output grid.
margin : int
- Padding ``m`` of the output grid on each side.
+ Padding m of the output grid on each side.
Returns
-------
image : torch.Tensor
- ``(H + 2m, W + 2m)`` resampled frame.
+ (H + 2m, W + 2m) resampled frame.
var_factor : torch.Tensor
- Same shape: ``1 / sum(coefficient * freshness)``, NaN where that sum
+ Same shape: 1 / sum(coefficient * freshness), NaN where that sum
is 0 or undefined.
"""
h, w = frame.shape
@@ -85,22 +88,32 @@ def interp_frame(
pr = margin + abs(math.floor(motion_r)) + 2
pc = margin + abs(math.floor(motion_c)) + 2
pads = [
- torch.nn.functional.pad(
- x[None], (pc, pc, pr, pr), value=float("nan")
- )[0]
+ torch.nn.functional.pad(x[None], (pc, pc, pr, pr), value=float("nan"))[0]
for x in (frame, freshness)
]
- def corner(which, ri, ci):
- """Slice of the padded frame (0) or freshness (1)."""
+ def corner(which: int, ri: np.ndarray, ci: np.ndarray) -> torch.Tensor:
+ """Slice of the padded frame (0) or freshness (1).
+
+ Returns
+ -------
+ torch.Tensor
+ The (len(ri), len(ci)) slice of the NaN-padded frame or freshness.
+ """
r0, c0 = int(ri[0]) + pr, int(ci[0]) + pc
return pads[which][r0 : r0 + ri.size, c0 : c0 + ci.size]
else:
dev = frame.device
- def corner(which, ri, ci):
- """Gathered frame (0) or freshness (1), NaN outside."""
+ def corner(which: int, ri: np.ndarray, ci: np.ndarray) -> torch.Tensor:
+ """Gathered frame (0) or freshness (1), NaN outside.
+
+ Returns
+ -------
+ torch.Tensor
+ The (len(ri), len(ci)) values of the frame or freshness, NaN outside it.
+ """
return _corner(
(frame, freshness)[which],
torch.from_numpy(ri).to(dev),
@@ -110,9 +123,7 @@ def corner(which, ri, ci):
r_lo, r_hi, c_lo, c_hi = idx
num = None
den = None
- for k, (ri, ci) in enumerate(
- ((r_lo, c_lo), (r_lo, c_hi), (r_hi, c_lo), (r_hi, c_hi))
- ):
+ for k, (ri, ci) in enumerate(((r_lo, c_lo), (r_lo, c_hi), (r_hi, c_lo), (r_hi, c_hi))):
cf = coef[k] * corner(1, ri, ci)
term = cf * corner(0, ri, ci)
num = term if num is None else num + term
diff --git a/src/giant_python/registration/matching.py b/src/giant_python/registration/matching.py
index 58364251..d184426b 100644
--- a/src/giant_python/registration/matching.py
+++ b/src/giant_python/registration/matching.py
@@ -1,18 +1,16 @@
"""Freshness-weighted normalized cross-correlation over integer shifts.
-Equivalent to GIAnT-MATLAB ``xcorr2_nans_weighted``: for each shift
-``(dr, dc)`` in ``[-S, S]^2``, the Pearson correlation between the frame's
+Equivalent to GIAnT-MATLAB xcorr2_nans_weighted: for each shift
+(dr, dc) in [-S, S]^2, the Pearson correlation between the frame's
valid pixels and the template at the shifted positions (inside the template
and not NaN), with weighted means, variances and covariance, each pixel
weighted by its freshness. The maximum is refined by a parabola fit on each
axis, unless it lies on the edge of the search range.
The correlation for all shifts of a batch of frames is six matrix products
-``(frames x pixels) @ (pixels x shifts)``.
+(frames x pixels) @ (pixels x shifts).
"""
-from typing import Tuple
-
import torch
@@ -25,28 +23,28 @@ def shift_tables(
rows: torch.Tensor,
cols: torch.Tensor,
search: int,
- dtype=torch.float32,
-) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ dtype: torch.dtype = torch.float32,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Template values at each pixel for every shift.
- Shifts are ordered as MATLAB's column-major ``C(drix, dcix)``: the row
+ Shifts are ordered as MATLAB's column-major C(drix, dcix): the row
shift varies fastest.
Parameters
----------
template : torch.Tensor
- ``(H, W)`` template, NaN where invalid.
+ (H, W) template, NaN where invalid.
rows, cols : torch.Tensor of int
Zero-based positions of the frame's pixels in the template.
search : int
- Largest shift ``S`` on each axis.
+ Largest shift S on each axis.
dtype : torch.dtype
Precision of the tables.
Returns
-------
valid, value, value2 : torch.Tensor
- ``(pixels, shifts)``: whether the shifted template pixel is usable,
+ (pixels, shifts): whether the shifted template pixel is usable,
its value (centred by the template's mean, 0 where unusable) and the
value squared.
"""
@@ -57,9 +55,7 @@ def shift_tables(
centre = finite.mean() if finite.numel() else template.new_zeros(())
# NaN padding makes shifts that leave the template unusable
wp = w + 2 * s
- padded = torch.full(
- (h + 2 * s, wp), float("nan"), dtype=dtype, device=template.device
- )
+ padded = torch.full((h + 2 * s, wp), float("nan"), dtype=dtype, device=template.device)
padded[s : s + h, s : s + w] = (template - centre).to(dtype)
sh = torch.arange(-s, s + 1, device=template.device)
offset = sh.repeat(n) * wp + sh.repeat_interleave(n) # dr fastest
@@ -73,7 +69,7 @@ def shift_tables(
def correlation_map(
frames: torch.Tensor,
weights: torch.Tensor,
- tables: Tuple[torch.Tensor, torch.Tensor, torch.Tensor],
+ tables: tuple[torch.Tensor, torch.Tensor, torch.Tensor],
search: int,
) -> torch.Tensor:
"""Weighted Pearson correlation for every shift.
@@ -81,18 +77,18 @@ def correlation_map(
Parameters
----------
frames : torch.Tensor
- ``(B, pixels)`` frame values; ignored where ``weights`` is 0.
+ (B, pixels) frame values; ignored where weights is 0.
weights : torch.Tensor
- ``(B, pixels)`` freshness, 0 at invalid pixels.
+ (B, pixels) freshness, 0 at invalid pixels.
tables : tuple of torch.Tensor
Output of :func:`shift_tables`.
search : int
- Largest shift ``S``.
+ Largest shift S.
Returns
-------
torch.Tensor
- ``(B, 2S + 1, 2S + 1)`` correlations indexed ``[b, dr, dc]``, NaN
+ (B, 2S + 1, 2S + 1) correlations indexed [b, dr, dc], NaN
where undefined.
"""
valid, value, value2 = tables
@@ -120,47 +116,39 @@ def correlation_map(
return corr.reshape(-1, n, n).transpose(1, 2)
-def peak_motion(
- corr: torch.Tensor, search: int
-) -> Tuple[torch.Tensor, torch.Tensor]:
+def peak_motion(corr: torch.Tensor, search: int) -> tuple[torch.Tensor, torch.Tensor]:
"""Motion and correlation at the maximum of correlation maps.
Ties go to the first maximum in MATLAB's column-major order. The motion
- is the negated (sub-pixel) shift, as ``xcorr2_nans_weighted`` returns.
+ is the negated (sub-pixel) shift, as xcorr2_nans_weighted returns.
Parameters
----------
corr : torch.Tensor
- ``(B, n, n)`` maps from :func:`correlation_map`.
+ (B, n, n) maps from :func:`correlation_map`.
search : int
- Largest shift ``S``.
+ Largest shift S.
Returns
-------
motion : torch.Tensor of float64
- ``(B, 2)`` [row, col] motion; NaN where the peak is NaN.
+ (B, 2) [row, col] motion; NaN where the peak is NaN.
peak : torch.Tensor of float64
- ``(B,)`` maximum correlation (NaN if every shift is undefined).
+ (B,) maximum correlation (NaN if every shift is undefined).
"""
b = corr.shape[0]
n = 2 * search + 1
c = corr.to(torch.float64)
rr, cc, peak = peak_index(c)
- shifts = torch.arange(
- -search, search + 1, device=c.device, dtype=torch.float64
- )
+ shifts = torch.arange(-search, search + 1, device=c.device, dtype=torch.float64)
mot = torch.stack([shifts[rr], shifts[cc]], 1)
inner = (rr > 0) & (rr < n - 1) & (cc > 0) & (cc < n - 1)
bi = torch.arange(b, device=c.device)
r1 = rr.clamp(1, n - 2)
c1 = cc.clamp(1, n - 2)
c0 = c[bi, r1, c1]
- ratio_r = torch.clamp(
- (c0 - c[bi, r1 - 1, c1]) / (c0 - c[bi, r1 + 1, c1]), max=1e6
- )
- ratio_c = torch.clamp(
- (c0 - c[bi, r1, c1 - 1]) / (c0 - c[bi, r1, c1 + 1]), max=1e6
- )
+ ratio_r = torch.clamp((c0 - c[bi, r1 - 1, c1]) / (c0 - c[bi, r1 + 1, c1]), max=1e6)
+ ratio_c = torch.clamp((c0 - c[bi, r1, c1 - 1]) / (c0 - c[bi, r1, c1 + 1]), max=1e6)
d_r = (1 - ratio_r) / (1 + ratio_r) / 2
d_c = (1 - ratio_c) / (1 + ratio_c) / 2
sub = torch.stack([mot[:, 0] - d_r, mot[:, 1] - d_c], 1)
@@ -171,7 +159,7 @@ def peak_motion(
return -mot, peak
-def peak_index(corr: torch.Tensor):
+def peak_index(corr: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Integer position and value of each map's maximum.
Ties go to the first maximum in MATLAB's column-major order; NaNs are
@@ -184,26 +172,26 @@ def peak_index(corr: torch.Tensor):
peak : torch.Tensor
The maximum (NaN if the whole map is undefined).
"""
- b, n_r, n_c = corr.shape
+ b, n_r, _n_c = corr.shape
flat = corr.transpose(1, 2).reshape(b, -1)
idx = torch.argmax(torch.nan_to_num(flat, nan=-torch.inf), dim=1)
return idx % n_r, idx // n_r, flat.gather(1, idx[:, None])[:, 0]
def peak_margin(corr: torch.Tensor, exclude: int = 2) -> torch.Tensor:
- """Maximum minus the largest value farther than ``exclude`` shifts.
+ """Maximum minus the largest value farther than exclude shifts.
Parameters
----------
corr : torch.Tensor
- ``(B, n, n)`` correlation maps.
+ (B, n, n) correlation maps.
exclude : int
Chebyshev radius around the maximum left out of the comparison.
Returns
-------
torch.Tensor
- ``(B,)`` margins (NaN when nothing lies outside the radius).
+ (B,) margins (NaN when nothing lies outside the radius).
"""
b, n_r, n_c = corr.shape
rr, cc, peak = peak_index(corr)
@@ -225,18 +213,18 @@ def match_maps(
rows: torch.Tensor,
cols: torch.Tensor,
search: int,
- dtype=torch.float32,
-):
+ dtype: torch.dtype = torch.float32,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Like :func:`match`, also returning the correlation maps.
Returns
-------
motion : torch.Tensor of float64
- ``(B, 2)`` [row, col] motion (NaN where undefined; not raised).
+ (B, 2) [row, col] motion (NaN where undefined; not raised).
peak : torch.Tensor of float64
- ``(B,)`` correlation at the maximum.
+ (B,) correlation at the maximum.
corr : torch.Tensor
- ``(B, 2S + 1, 2S + 1)`` maps indexed ``[b, dr, dc]``.
+ (B, 2S + 1, 2S + 1) maps indexed [b, dr, dc].
"""
search = int(round(search))
tables = shift_tables(template, rows, cols, search, dtype)
@@ -251,22 +239,27 @@ def wide_correlation(
"""Weighted Pearson correlation over every shift within a padded template.
The same statistic as :func:`correlation_map`, evaluated with FFTs for
- all shifts at once: frame pixel ``(r, c)`` is compared with template
- pixel ``(r + m + dr, c + m + dc)``, where the template is the frame
- window padded by ``m`` on each side, for ``|dr|, |dc| <= m``. Unlike
+ all shifts at once: frame pixel (r, c) is compared with template
+ pixel (r + m + dr, c + m + dc), where the template is the frame
+ window padded by m on each side, for ``|dr|, |dc| <= m``. Unlike
MATLAB's search, the template is not cropped around a starting shift.
Parameters
----------
frames, weights : torch.Tensor
- ``(B, H, W)`` frame images (NaN where invalid) and freshness.
+ (B, H, W) frame images (NaN where invalid) and freshness.
template : torch.Tensor
- ``(H + 2m, W + 2m)`` template, NaN where invalid.
+ (H + 2m, W + 2m) template, NaN where invalid.
Returns
-------
torch.Tensor of float64
- ``(B, 2m + 1, 2m + 1)`` maps indexed ``[b, dr + m, dc + m]``.
+ (B, 2m + 1, 2m + 1) maps indexed [b, dr + m, dc + m].
+
+ Raises
+ ------
+ ValueError
+ If the template does not pad the frames equally on every side.
"""
dt = torch.float64
ho, wo = template.shape
@@ -276,9 +269,7 @@ def wide_correlation(
raise ValueError("the template must pad the frames equally")
f = frames.to(dt)
wt = torch.where(torch.isnan(f), 0.0, weights.to(dt))
- mean0 = (wt * torch.nan_to_num(f)).sum((1, 2), keepdim=True) / wt.sum(
- (1, 2), keepdim=True
- )
+ mean0 = (wt * torch.nan_to_num(f)).sum((1, 2), keepdim=True) / wt.sum((1, 2), keepdim=True)
fc = torch.where(wt > 0, f - mean0, 0.0)
t = template.to(dt)
tv = ~torch.isnan(t)
@@ -288,8 +279,15 @@ def wide_correlation(
fb = [torch.fft.rfft2(b) for b in (tv.to(dt), tz, tz * tz)]
n = 2 * reach + 1
- def xc(a, b):
- """Correlation of frame-side ``a`` with template-side ``b``."""
+ def xc(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
+ """Correlation of frame-side a with template-side b.
+
+ Returns
+ -------
+ torch.Tensor
+ Cross-correlation of each frame's transform a with b, cropped to the
+ (B, 2 * reach + 1, 2 * reach + 1) shifts.
+ """
out = torch.fft.irfft2(torch.conj(a) * b[None], s=size)
return out[:, :n, :n]
@@ -301,9 +299,7 @@ def xc(a, b):
v_f = s_ff - sw * m_f * m_f
v_t = s_tt - sw * m_t * m_t
corr = cov / torch.sqrt(v_f * v_t)
- return corr.masked_fill(
- sw < 1e-9 * sw.amax((1, 2), keepdim=True), float("nan")
- )
+ return corr.masked_fill(sw < 1e-9 * sw.amax((1, 2), keepdim=True), float("nan"))
def match(
@@ -313,16 +309,16 @@ def match(
rows: torch.Tensor,
cols: torch.Tensor,
search: int,
- dtype=torch.float32,
-) -> Tuple[torch.Tensor, torch.Tensor]:
- """Register frames to a template (``xcorr2_nans_weighted``).
+ dtype: torch.dtype = torch.float32,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Register frames to a template (xcorr2_nans_weighted).
Parameters
----------
frames, weights : torch.Tensor
- ``(B, pixels)`` frame values and freshness (0 where invalid).
+ (B, pixels) frame values and freshness (0 where invalid).
template : torch.Tensor
- ``(H, W)`` template, NaN where invalid.
+ (H, W) template, NaN where invalid.
rows, cols : torch.Tensor of int
Zero-based pixel positions in the template.
search : int
@@ -333,22 +329,20 @@ def match(
Returns
-------
motion : torch.Tensor of float64
- ``(B, 2)`` [row, col] motion.
+ (B, 2) [row, col] motion.
peak : torch.Tensor of float64
- ``(B,)`` correlation at the maximum.
+ (B,) correlation at the maximum.
Raises
------
RegistrationError
- If a motion is NaN, as ``xcorr2_nans_weighted`` does; this includes
+ If a motion is NaN, as xcorr2_nans_weighted does; this includes
frames whose correlation is undefined at every shift (e.g. frames
without valid samples).
"""
search = int(round(search))
tables = shift_tables(template, rows, cols, search, dtype)
- motion, peak = peak_motion(
- correlation_map(frames, weights, tables, search), search
- )
+ motion, peak = peak_motion(correlation_map(frames, weights, tables, search), search)
if torch.isnan(motion).any():
raise RegistrationError("Computed motion contains NaN.")
return motion, peak
diff --git a/src/giant_python/registration/multiroi.py b/src/giant_python/registration/multiroi.py
index d9a7c7cc..1d19af26 100644
--- a/src/giant_python/registration/multiroi.py
+++ b/src/giant_python/registration/multiroi.py
@@ -1,24 +1,24 @@
-"""Register one SLAP2 raster trial (``alignAsync`` of MultiRoiRegistration).
+"""Register one SLAP2 raster trial (alignAsync of MultiRoiRegistration).
The trial's frames are registered sequentially, as in GIAnT-MATLAB: each DS
frame is matched to the mean of the initial and running templates, starting
from the previous frame's rounded motion with a search radius of
``max(|init|, clip_shift)``; its registered image is then added to the
-running template. With ``compensate_online``, frames are formed with the
+running template. With compensate_online, frames are formed with the
online motion correction undone line by line (see :mod:`.compensation`).
Frames without valid samples (e.g. before a late recording start) are
missing frames: they get NaN motion and an all-NaN movie frame and are not
matched, so they change neither the template nor the next frame's start,
-nor ``registrationFailed``. MATLAB gives them an arbitrary finite motion
+nor registrationFailed. MATLAB gives them an arbitrary finite motion
(the edge of the search range); their registered images are NaN there too.
"""
import logging
import time
+from collections.abc import Sequence
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Optional, Union
import numpy as np
import torch
@@ -45,23 +45,35 @@
rec_neg_err,
settings_record,
)
-from .sources import has_samples, make_source
+from .sources import CompensatedFrames, PlainFrames, has_samples, make_source
from .stats.io import stats_path
from .stats.worker import FAILED, StatsWorker
-from .template import TemplateState, consensus, initial_template
+from .template import ConsensusResult, TemplateState, consensus, initial_template
log = logging.getLogger(__name__)
def matlab_colon(a: float, d: float, b: float) -> np.ndarray:
- """``a:d:b`` as MATLAB computes it, symmetrically from both ends."""
+ """a:d:b as MATLAB computes it, symmetrically from both ends.
+
+ Returns
+ -------
+ np.ndarray
+ The values from a in steps of d up to b.
+ """
n = int(np.floor((b - a) / d + 1e-10))
k = np.arange(n + 1)
return np.where(k <= n / 2, a + k * d, (a + n * d) - (n - k) * d)
def matlab_linspace(a: float, b: float, n: int) -> np.ndarray:
- """``linspace(a, b, n)`` with exact end points."""
+ """linspace(a, b, n) with exact end points.
+
+ Returns
+ -------
+ np.ndarray
+ n evenly spaced values from a to b.
+ """
y = a + np.arange(n) * ((b - a) / (n - 1))
y[0], y[-1] = a, b
return y
@@ -82,7 +94,7 @@ class TrialRegistration:
registration_failed : bool
Whether the motion's standard deviation exceeded 1.5 pixels.
growth : GrowthQC or None
- How each frame was registered, with ``schedule='grow'``.
+ How each frame was registered, with schedule='grow'.
timings : dict
Wall time in seconds of each phase.
"""
@@ -92,21 +104,21 @@ class TrialRegistration:
motion_c: np.ndarray
peak: np.ndarray
registration_failed: bool
- growth: Optional[GrowthQC] = None
+ growth: GrowthQC | None = None
timings: dict = field(default_factory=dict)
class Timer:
"""Wall time of consecutive phases (synchronizing CUDA at each mark)."""
- def __init__(self, device):
+ def __init__(self, device: str | torch.device) -> None:
"""Start timing."""
self.device = torch.device(device)
self.times = {}
self._last = time.perf_counter()
def mark(self, name: str) -> None:
- """Record the time since the previous mark under ``name``."""
+ """Record the time since the previous mark under name."""
if self.device.type == "cuda":
torch.cuda.synchronize(self.device)
now = time.perf_counter()
@@ -115,7 +127,12 @@ def mark(self, name: str) -> None:
def resolve_device(device: str) -> torch.device:
- """``'auto'`` selects CUDA when available, else the CPU.
+ """'auto' selects CUDA when available, else the CPU.
+
+ Returns
+ -------
+ torch.device
+ The device to compute on.
Raises
------
@@ -126,8 +143,7 @@ def resolve_device(device: str) -> torch.device:
device = "cuda" if torch.cuda.is_available() else "cpu"
dev = torch.device(device)
if dev.type == "cuda" and (
- not torch.cuda.is_available()
- or (dev.index or 0) >= torch.cuda.device_count()
+ not torch.cuda.is_available() or (dev.index or 0) >= torch.cuda.device_count()
):
raise ValueError(f"CUDA device {device!r} is not available")
return dev
@@ -148,12 +164,14 @@ def check_layout(layout: RasterLayout) -> None:
raise ValueError("only one- or two-channel recordings are supported")
-def check_recording(dat_path: Union[str, Path]) -> None:
+def check_recording(dat_path: str | Path) -> None:
"""Read a recording's layout and reject it if it is not supported."""
check_layout(raster_layout(dat_path))
-def frame_times(first_line: float, last_line: float, dt: float, n_init: int):
+def frame_times(
+ first_line: float, last_line: float, dt: float, n_init: int
+) -> tuple[np.ndarray, np.ndarray]:
"""Line times of the initial frames and of the registered (DS) frames.
Parameters
@@ -168,16 +186,21 @@ def frame_times(first_line: float, last_line: float, dt: float, n_init: int):
Returns
-------
init, ds : ndarray of int
- ``round(linspace(first, last, n_init + 2))`` without its ends, and
- ``ceil(first:dt:last)``.
+ round(linspace(first, last, n_init + 2)) without its ends, and
+ ceil(first:dt:last).
"""
init = matlab_round(matlab_linspace(first_line, last_line, n_init + 2))
ds = np.ceil(matlab_colon(first_line, dt, last_line))
return init[1:-1].astype(np.int64), ds.astype(np.int64)
-def build_template(source, init, params, dtype):
- """Build the initial template from the ``init`` frames of a source.
+def build_template(
+ source: PlainFrames | CompensatedFrames,
+ init: np.ndarray,
+ params: MultiRoiRegistrationParams,
+ dtype: torch.dtype,
+) -> tuple[TemplateState, ConsensusResult]:
+ """Build the initial template from the init frames of a source.
Returns
-------
@@ -235,30 +258,30 @@ class OutputSink:
device : torch.device
Where the mean images accumulate.
movie_deflate, var_deflate : int
- Deflate levels of an HDF5 movie and of ``varFacDS`` (0: none).
+ Deflate levels of an HDF5 movie and of varFacDS (0: none).
stats : StatsWorker, optional
Accumulates the trial's summary statistics (:mod:`.stats`) from
the frames as they are written (on a GPU, on a thread of its own).
stats_path : Path, optional
- The trial's statistics file. Written with the movie when ``stats``
+ The trial's statistics file. Written with the movie when stats
is given; otherwise an existing one is removed on publishing (it
would describe an earlier registration).
"""
def __init__(
self,
- movie_path,
- adata_path,
- out_shape,
- n_frames,
- n_channels,
- save_tif,
- device,
+ movie_path: str | Path,
+ adata_path: str | Path,
+ out_shape: tuple[int, int],
+ n_frames: int,
+ n_channels: int,
+ save_tif: bool,
+ device: torch.device,
movie_deflate: int = 1,
var_deflate: int = 1,
- stats=None,
- stats_path=None,
- ):
+ stats: StatsWorker | None = None,
+ stats_path: str | Path | None = None,
+ ) -> None:
"""Open the movie and the alignment file."""
ho, wo = out_shape
self.stats = stats
@@ -266,9 +289,7 @@ def __init__(
self.n_frames = int(n_frames)
self.sum = torch.zeros(n_channels, ho, wo, device=device)
self.count = torch.zeros(n_channels, ho, wo, device=device)
- self.movie_ds = np.full(
- (n_frames, ho // 4, wo // 4), np.nan, dtype=np.float32
- )
+ self.movie_ds = np.full((n_frames, ho // 4, wo // 4), np.nan, dtype=np.float32)
self.movie = MovieWriter(
movie_path,
out_shape,
@@ -277,28 +298,33 @@ def __init__(
movie_deflate,
)
try:
- self.adata = AlignmentFile(
- adata_path, out_shape, n_frames, var_deflate
- )
+ self.adata = AlignmentFile(adata_path, out_shape, n_frames, var_deflate)
except BaseException:
self.movie.abort()
raise
def add_missing(self, k: int) -> None:
- """Record frame ``k`` as missing: all-NaN pages and variance."""
- blank = torch.full(
- self.sum.shape[1:], float("nan"), device=self.sum.device
- )
+ """Record frame k as missing: all-NaN pages and variance."""
+ blank = torch.full(self.sum.shape[1:], float("nan"), device=self.sum.device)
nan = float("nan")
self.add(k, [blank] * self.sum.shape[0], blank, (nan, nan))
def add(
- self, k: int, regs, var_factor: torch.Tensor, motion=None
+ self,
+ k: int,
+ regs: Sequence[torch.Tensor],
+ var_factor: torch.Tensor,
+ motion: tuple[float, float] | np.ndarray | None = None,
) -> torch.Tensor:
- """Record frame ``k``'s registered channels; return their sum.
+ """Record frame k's registered channels; return their sum.
- ``motion`` (row, column) is the frame's motion, which the summary
+ motion (row, column) is the frame's motion, which the summary
statistics need.
+
+ Returns
+ -------
+ torch.Tensor
+ The sum of the frame's registered channels.
"""
self.adata.write_var_factor(k, var_factor.cpu().numpy())
total = None
@@ -321,11 +347,17 @@ def stats_seconds(self) -> float:
return 0.0 if self.stats is None else self.stats.seconds
def mean_image(self) -> np.ndarray:
- """Per-channel mean of the registered frames (meanIM)."""
+ """Per-channel mean of the registered frames (meanIM).
+
+ Returns
+ -------
+ np.ndarray
+ The mean image of each channel, NaN where no frame had data.
+ """
mean = self.sum / torch.clamp(self.count, min=1)
return mean.masked_fill(self.count < 1, float("nan")).cpu().numpy()
- def _write_stats(self, fields: dict):
+ def _write_stats(self, fields: dict) -> Path | None:
"""Finish the statistics and write them under a temporary name.
Returns
@@ -363,10 +395,12 @@ def _write_stats(self, fields: dict):
return None
return tmp
- def finish(self, fields: dict, settings: Optional[dict] = None) -> None:
- """Complete the alignment file and publish it with the movie (and
- the statistics file; a failure there is logged and the trial is
- published without statistics)."""
+ def finish(self, fields: dict, settings: dict | None = None) -> None:
+ """Complete the alignment file and publish it with the movie.
+
+ And with the statistics file; a failure there is logged and the trial
+ is published without statistics.
+ """
self.movie.close()
self.adata.finish(fields, settings) # while the maps are formed
try:
@@ -389,14 +423,14 @@ def abort(self) -> None:
def register_sequential(
- source,
+ source: PlainFrames | CompensatedFrames,
state: TemplateState,
- ds,
- params,
+ ds: np.ndarray,
+ params: MultiRoiRegistrationParams,
sink: OutputSink,
- dtype,
+ dtype: torch.dtype,
chunk: int = 32,
-):
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""MATLAB's frame loop: match, resample, add to the template.
Frames without valid samples are missing (NaN motion, all-NaN output)
@@ -408,6 +442,12 @@ def register_sequential(
-------
motion_r, motion_c, peak : ndarray
Per-frame motion and peak correlation.
+
+ Raises
+ ------
+ RegistrationError
+ If the computed motion of a frame with a defined peak correlation
+ contains NaN.
"""
m = int(params.maxshift)
window = source.window
@@ -452,9 +492,7 @@ def register_sequential(
for ch in range(vals.shape[0]):
img = window.image(vals[ch, i], float("nan"))
regs.append(interp_frame(img, fimg, mr, mc, m))
- state.add(
- sink.add(a + i, [r for r, _ in regs], regs[0][1], (mr, mc))
- )
+ state.add(sink.add(a + i, [r for r, _ in regs], regs[0][1], (mr, mc)))
init_r = int(np.clip(matlab_round(mr), -m, m))
init_c = int(np.clip(matlab_round(mc), -m, m))
log.info("%d of %d frames", b, n)
@@ -462,16 +500,16 @@ def register_sequential(
def register_grow(
- source,
- state,
- cons,
- init,
- ds,
- params,
+ source: PlainFrames | CompensatedFrames,
+ state: TemplateState,
+ cons: ConsensusResult,
+ init: np.ndarray,
+ ds: np.ndarray,
+ params: MultiRoiRegistrationParams,
sink: OutputSink,
- dtype,
- timer: Optional[Timer] = None,
-):
+ dtype: torch.dtype,
+ timer: Timer | None = None,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, GrowthQC]:
"""Batched growth from seed frames, then rendering in frame order.
Returns
@@ -491,12 +529,8 @@ def register_grow(
qc = GrowthQC.missing(ds.size)
if present.any():
reach = 2 * max(3 * source.dt, source.former.layout.lines_per_cycle)
- seeds, candidates, independent = seeds_from_consensus(
- cons, init, ds[present], reach
- )
- grower = Grower(
- cache, state, params, seeds, candidates, dtype, independent
- )
+ seeds, candidates, independent = seeds_from_consensus(cons, init, ds[present], reach)
+ grower = Grower(cache, state, params, seeds, candidates, dtype, independent)
grown, qc = grower.run()
timer.mark("grow")
if params.polish:
@@ -516,44 +550,51 @@ def register_grow(
return motion[:, 0].copy(), motion[:, 1].copy(), qc.peak.copy(), qc
-def motion_failed(motion_r, motion_c) -> bool:
- """``registrationFailed``: motion SD above 1.5 pixels on either axis.
+def motion_failed(motion_r: np.ndarray, motion_c: np.ndarray) -> bool:
+ """registrationFailed: motion SD above 1.5 pixels on either axis.
Missing frames (NaN motion) are left out. A trial of several frames
with fewer than two of them with motion counts as failed, so that SILo
- skips it: it interpolates the motion with ``interp1``, which needs two
+ skips it: it interpolates the motion with interp1, which needs two
finite samples (it uses a one-frame trial's motion as a constant). This
includes a trial in which no frame has samples, which MATLAB's drifting
search-edge motion fails too.
+
+ Returns
+ -------
+ bool
+ True when the registration counts as failed.
"""
ok = np.isfinite(motion_r) & np.isfinite(motion_c)
if ok.sum() < min(2, ok.size):
return True
- return bool(
- np.std(motion_c[ok], ddof=1) > 1.5
- or np.std(motion_r[ok], ddof=1) > 1.5
- )
+ return bool(np.std(motion_c[ok], ddof=1) > 1.5 or np.std(motion_r[ok], ddof=1) > 1.5)
def alignment_fields(
layout: RasterLayout,
- source,
- ds,
- motion_r,
- motion_c,
+ source: PlainFrames | CompensatedFrames,
+ ds: np.ndarray,
+ motion_r: np.ndarray,
+ motion_c: np.ndarray,
sink: OutputSink,
- params,
+ params: MultiRoiRegistrationParams,
failed: bool,
-):
- """The ALIGNMENTDATA struct, as MultiRoiRegistration saves it."""
+) -> dict:
+ """Build the ALIGNMENTDATA struct, as MultiRoiRegistration saves it.
+
+ Returns
+ -------
+ dict
+ The alignment data fields (meanIM, DSframes, motionDSr, motionDSc,
+ registrationFailed, slap2, ...) by their MATLAB names.
+ """
m = int(params.maxshift)
window = source.window
h, w = window.shape
record = {"enabled": np.int8(0)}
if source.compensation is not None:
- record = compensation_record(
- source.compensation, source.references(ds)
- )
+ record = compensation_record(source.compensation, source.references(ds))
ho, wo = h + 2 * m, w + 2 * m
x_off, y_off, z_off = read_line_offsets(layout, ds)
return {
@@ -585,13 +626,18 @@ def alignment_fields(
def open_trial(
- dat_path, first_line, last_line, params, device, mask_unlit=True
-):
+ dat_path: str | Path,
+ first_line: float,
+ last_line: float,
+ params: MultiRoiRegistrationParams,
+ device: str | torch.device,
+ mask_unlit: bool = True,
+) -> tuple[RasterLayout, FrameFormer, np.ndarray, np.ndarray, int]:
"""Read a trial's samples and frame times.
- ``mask_unlit`` (default) marks the samples taken behind the DMD curtain
+ mask_unlit (default) marks the samples taken behind the DMD curtain
invalid (see :func:`giant_python.io.slap2_raster.unlit_samples`), as
- registration does since ``slap2/unlitMasked``; False keeps them, as in
+ registration does since slap2/unlitMasked; False keeps them, as in
registrations made before.
Returns
@@ -621,12 +667,19 @@ def open_trial(
def trial_stats(
- source, ds, margin: int, n_channels: int
-) -> Optional[StatsWorker]:
- """Start the trial's statistics (:class:`.stats.worker.StatsWorker`):
- on a GPU their accumulator is set up on a thread of its own while the
+ source: PlainFrames | CompensatedFrames, ds: np.ndarray, margin: int, n_channels: int
+) -> StatsWorker | None:
+ """Start the trial's statistics (:class:`.stats.worker.StatsWorker`).
+
+ On a GPU their accumulator is set up on a thread of its own while the
template is built, and then takes the registered frames there. A
- failure is logged and registration goes on without statistics."""
+ failure is logged and registration goes on without statistics.
+
+ Returns
+ -------
+ StatsWorker or None
+ The statistics worker, or None when it could not be started.
+ """
from .stats import new_accumulator
try:
@@ -639,10 +692,30 @@ def trial_stats(
return None
-def _template_and_sink(source, init, ds, params, dtype, paths, stats, timer):
- """Start the statistics (if ``stats``), build the template and open the
- outputs ``paths`` (movie, alignment file); the statistics are given up
- if either fails."""
+def _template_and_sink(
+ source: PlainFrames | CompensatedFrames,
+ init: np.ndarray,
+ ds: np.ndarray,
+ params: MultiRoiRegistrationParams,
+ dtype: torch.dtype,
+ paths: tuple[str | Path, str | Path],
+ stats: bool,
+ timer: Timer,
+) -> tuple[TemplateState, ConsensusResult, OutputSink]:
+ """Start the statistics, build the template and open the outputs.
+
+ The statistics are started if stats; the outputs are paths (movie,
+ alignment file). The statistics are given up if either fails.
+
+ Returns
+ -------
+ state : TemplateState
+ The initial template and its sums.
+ cons : ConsensusResult
+ The pairwise matching that chose its frames.
+ sink : OutputSink
+ The opened outputs.
+ """
layout = source.former.layout
m = int(params.maxshift)
h, w = source.window.shape
@@ -671,26 +744,26 @@ def _template_and_sink(source, init, ds, params, dtype, paths, stats, timer):
def register_trial(
- dat_path: Union[str, Path],
+ dat_path: str | Path,
first_line: float,
last_line: float,
- movie_path: Union[str, Path],
- adata_path: Union[str, Path],
- params: Optional[MultiRoiRegistrationParams] = None,
- device="cpu",
- dtype=torch.float32,
+ movie_path: str | Path,
+ adata_path: str | Path,
+ params: MultiRoiRegistrationParams | None = None,
+ device: str | torch.device = "cpu",
+ dtype: torch.dtype = torch.float32,
stats: bool = True,
) -> TrialRegistration:
- """Register the lines ``first_line .. last_line`` of a recording.
+ """Register the lines first_line .. last_line of a recording.
Parameters
----------
dat_path : str or Path
- The trial's ``.dat`` file.
+ The trial's .dat file.
first_line, last_line : float
One-based line range of the trial. Kept fractional, as in MATLAB:
- trial tables of continuous recordings cut trials at ``linspace``
- edges, and the frame times are ``ceil(first:dt:last)``.
+ trial tables of continuous recordings cut trials at linspace
+ edges, and the frame times are ceil(first:dt:last).
movie_path, adata_path : str or Path
Destinations of the registered movie and the alignment data.
params : MultiRoiRegistrationParams, optional
@@ -701,7 +774,7 @@ def register_trial(
Precision of the correlation sums.
stats : bool
Also compute the trial's summary statistics (:mod:`.stats`) while
- the movie is written, into ``_REGSTATS-Hz.h5`` next to
+ the movie is written, into _REGSTATS-Hz.h5 next to
it (:func:`.stats.stats_path`). Without, an existing statistics
file of the trial is removed.
@@ -709,12 +782,6 @@ def register_trial(
-------
TrialRegistration
Motion and quality of the trial.
-
- Raises
- ------
- ValueError
- For recordings with more than one fast-z plane or channel counts
- other than 1 or 2.
"""
if params is None:
params = MultiRoiRegistrationParams()
@@ -750,9 +817,7 @@ def register_trial(
source, state, cons, init, ds, params, sink, dtype, timer
)
else:
- motion_r, motion_c, peak = register_sequential(
- source, state, ds, params, sink, dtype
- )
+ motion_r, motion_c, peak = register_sequential(source, state, ds, params, sink, dtype)
timer.mark("register")
sink.movie.close()
timer.mark("movie")
@@ -767,9 +832,7 @@ def register_trial(
)
elif failed:
log.warning("too much motion in %s; saving anyway", dat_path)
- fields = alignment_fields(
- layout, source, ds, motion_r, motion_c, sink, params, failed
- )
+ fields = alignment_fields(layout, source, ds, motion_r, motion_c, sink, params, failed)
if qc is not None:
fields["growthQC"] = qc.fields()
sink.finish(fields, settings_record(params))
@@ -778,9 +841,5 @@ def register_trial(
raise
timer.mark("alignment file")
timer.times["stats (within)"] = sink.stats_seconds
- log.info(
- "timings (s): %s", {k: round(v, 2) for k, v in timer.times.items()}
- )
- return TrialRegistration(
- ds, motion_r, motion_c, peak, failed, qc, timer.times
- )
+ log.info("timings (s): %s", {k: round(v, 2) for k, v in timer.times.items()})
+ return TrialRegistration(ds, motion_r, motion_c, peak, failed, qc, timer.times)
diff --git a/src/giant_python/registration/outputs.py b/src/giant_python/registration/outputs.py
index bf5bb794..2fc3aa34 100644
--- a/src/giant_python/registration/outputs.py
+++ b/src/giant_python/registration/outputs.py
@@ -1,15 +1,15 @@
"""Registration outputs in GIAnT-MATLAB's file layout.
* The registered movie: a BigTIFF with one float32 page per channel per
- frame (``Fast_BigTiff_Write``), or an HDF5 file whose ``/data`` holds the
- same pages (``saveTif = false``).
-* ``_ALIGNMENTDATA.h5``: the alignment struct written column-major by
- ``saveStructToH5``. Its per-frame variance factor is streamed to disk while
+ frame (Fast_BigTiff_Write), or an HDF5 file whose /data holds the
+ same pages (saveTif = false).
+* _ALIGNMENTDATA.h5: the alignment struct written column-major by
+ saveStructToH5. Its per-frame variance factor is streamed to disk while
frames are registered; the file is complete only after :meth:`finish`.
The settings that produced it are recorded as a JSON root attribute
(:data:`SETTINGS_ATTR`), which struct readers ignore.
-Both are written under temporary names (``.partial``) and moved into
+Both are written under temporary names (.partial) and moved into
place together by :func:`publish` once both are complete, the alignment file
last. A run that fails before then leaves an existing pair untouched; one
that fails while publishing leaves no alignment file, so the trial is not
@@ -23,14 +23,16 @@
import warnings
import zlib
from collections import deque
-from concurrent.futures import ThreadPoolExecutor
+from collections.abc import Callable
+from concurrent.futures import Future, ThreadPoolExecutor
from pathlib import Path
-from typing import Optional, Union
import h5py
import numpy as np
+from numpy.typing import ArrayLike
from ..io.hdf5 import write_matlab_value
+from ..models.params import MultiRoiRegistrationParams
log = logging.getLogger(__name__)
@@ -48,22 +50,29 @@
"""
-def unlit_masked(adata_path) -> bool:
- """Whether an alignment file's frames left out the samples taken behind
- the DMD curtain (``slap2/unlitMasked``; False in files registered
- before it was recorded, whose frames kept them)."""
+def unlit_masked(adata_path: str | Path) -> bool:
+ """Whether an alignment file's frames left out the samples taken behind the DMD curtain.
+
+ slap2/unlitMasked; False in files registered before it was recorded,
+ whose frames kept them.
+
+ Returns
+ -------
+ bool
+ True if the frames left out those samples; False if they kept them.
+ """
with h5py.File(adata_path, "r") as f:
if "slap2/unlitMasked" not in f:
return False
return bool(np.asarray(f["slap2/unlitMasked"][()]).ravel()[0])
-def settings_record(params) -> dict:
- """The settings that produced a trial's outputs, as saved with them.
+def settings_record(params: MultiRoiRegistrationParams) -> dict:
+ """Build the record of the settings that produced a trial's outputs, as saved with them.
- The trial table's ``align_params`` fields (MATLAB names) without
- ``overwriteExisting``, which only decides whether outputs are made,
- plus ``frameVersion`` (:data:`FRAME_VERSION`); NaN (no junction limit)
+ The trial table's align_params fields (MATLAB names) without
+ overwriteExisting, which only decides whether outputs are made,
+ plus frameVersion (:data:`FRAME_VERSION`); NaN (no junction limit)
is stored as None.
Parameters
@@ -88,13 +97,13 @@ def settings_record(params) -> dict:
class _Background:
"""Run writes in order on one thread, with a bounded backlog."""
- def __init__(self, max_pending: int = 64):
+ def __init__(self, max_pending: int = 64) -> None:
"""Start the thread."""
self._pool = ThreadPoolExecutor(max_workers=1)
self._pending = deque()
self._max = max_pending
- def submit(self, fn, *args) -> None:
+ def submit(self, fn: Callable[..., object], *args: object) -> None:
"""Queue ``fn(*args)``; wait while too many writes are pending."""
self._pending.append(self._pool.submit(fn, *args))
while len(self._pending) > self._max:
@@ -117,17 +126,27 @@ def close(self) -> None:
def _compressors() -> ThreadPoolExecutor:
- """Shared pool that deflates chunks in parallel (zlib releases the GIL)."""
+ """Shared pool that deflates chunks in parallel (zlib releases the GIL).
+
+ Returns
+ -------
+ ThreadPoolExecutor
+ The module-wide pool, created on first use.
+ """
global _COMPRESSORS
if _COMPRESSORS is None:
- _COMPRESSORS = ThreadPoolExecutor(
- max_workers=max(1, min(8, (os.cpu_count() or 2) // 2))
- )
+ _COMPRESSORS = ThreadPoolExecutor(max_workers=max(1, min(8, (os.cpu_count() or 2) // 2)))
return _COMPRESSORS
def _deflate(page: np.ndarray, level: int) -> bytes:
- """One frame's chunk, transposed to MATLAB layout and deflated."""
+ """One frame's chunk, transposed to MATLAB layout and deflated.
+
+ Returns
+ -------
+ bytes
+ The zlib-compressed page.
+ """
return zlib.compress(np.ascontiguousarray(page.T).tobytes(), level)
@@ -135,17 +154,19 @@ class _ChunkedFrames:
"""An HDF5 dataset of frames, one chunk each, optionally deflated.
Deflated chunks are compressed on a thread pool and stored in order
- with ``write_direct_chunk``; the dataset carries HDF5's standard deflate
- filter, so any reader (MATLAB's ``h5read`` included) decompresses them.
+ with write_direct_chunk; the dataset carries HDF5's standard deflate
+ filter, so any reader (MATLAB's h5read included) decompresses them.
"""
- def __init__(self, group, name, n_frames, shape, level: int):
- """Create the dataset ``(n_frames, cols, rows)`` (MATLAB layout)."""
+ def __init__(
+ self, group: h5py.Group, name: str, n_frames: int, shape: tuple[int, int], level: int
+ ) -> None:
+ """Create the dataset (n_frames, cols, rows) (MATLAB layout)."""
rows, cols = shape
self.level = int(level)
opts = {}
if self.level:
- opts = dict(compression="gzip", compression_opts=self.level)
+ opts = {"compression": "gzip", "compression_opts": self.level}
self.ds = group.create_dataset(
name,
shape=(n_frames, cols, rows),
@@ -154,14 +175,21 @@ def __init__(self, group, name, n_frames, shape, level: int):
**opts,
)
- def prepare(self, page: np.ndarray):
- """Start compressing a page; returns what :meth:`store` needs."""
+ def prepare(self, page: np.ndarray) -> np.ndarray | Future[bytes]:
+ """Start compressing a page; returns what :meth:`store` needs.
+
+ Returns
+ -------
+ np.ndarray or Future[bytes]
+ The page as float32 when the dataset is not deflated, else the pending
+ compression of it.
+ """
page = np.asarray(page, np.float32)
if not self.level:
return page
return _compressors().submit(_deflate, page, self.level)
- def store(self, index: int, prepared) -> None:
+ def store(self, index: int, prepared: np.ndarray | Future[bytes]) -> None:
"""Write a prepared page (call in frame order, from one thread)."""
if not self.level:
self.ds[index] = prepared.T
@@ -170,7 +198,13 @@ def store(self, index: int, prepared) -> None:
def partial_path(path: Path) -> Path:
- """Temporary name of an output until it is published."""
+ """Temporary name of an output until it is published.
+
+ Returns
+ -------
+ Path
+ path with .partial appended.
+ """
return path.with_name(path.name + ".partial")
@@ -180,27 +214,27 @@ class MovieWriter:
Parameters
----------
path : str or Path
- Final destination; the pages go to ``.partial`` until
+ Final destination; the pages go to .partial until
:func:`publish`.
shape : (int, int)
- Page shape ``(rows, cols)``.
+ Page shape (rows, cols).
n_pages : int
Pages to be written (frames x channels); needed for HDF5.
tiff : bool
- Write a BigTIFF (else HDF5 ``/data``, one chunk per page, MATLAB
- dimensions ``[rows cols pages]``).
+ Write a BigTIFF (else HDF5 /data, one chunk per page, MATLAB
+ dimensions [rows cols pages]).
deflate : int
HDF5 movies: deflate level (0 for none; MATLAB writes 4).
"""
def __init__(
self,
- path: Union[str, Path],
- shape,
+ path: str | Path,
+ shape: tuple[int, int],
n_pages: int,
tiff: bool = True,
deflate: int = 1,
- ):
+ ) -> None:
"""Open the temporary file."""
self.path = Path(path)
self.tmp = partial_path(self.path)
@@ -215,17 +249,15 @@ def __init__(
self._tw = tifffile.TiffWriter(self.tmp, bigtiff=True)
else:
self._h5 = h5py.File(self.tmp, "w")
- self._frames = _ChunkedFrames(
- self._h5, "data", n_pages, shape, deflate
- )
+ self._frames = _ChunkedFrames(self._h5, "data", n_pages, shape, deflate)
self._bg = _Background()
def write(self, page: np.ndarray) -> None:
- """Append one ``(rows, cols)`` page.
+ """Append one (rows, cols) page.
- Pages are stored as MATLAB's ``Fast_BigTiff_Write`` stores them:
+ Pages are stored as MATLAB's Fast_BigTiff_Write stores them:
column-major, so a TIFF reader that is not MATLAB's (e.g.
- ``tifffile``) returns each page transposed, ``(cols, rows)``.
+ tifffile) returns each page transposed, (cols, rows).
"""
page = np.asarray(page, np.float32)
if not self.tiff:
@@ -233,7 +265,7 @@ def write(self, page: np.ndarray) -> None:
self._bg.submit(self._write, page, self.n)
self.n += 1
- def _write(self, page, index: int) -> None:
+ def _write(self, page: np.ndarray | Future[bytes], index: int) -> None:
"""Write one page (on the background thread)."""
if self.tiff:
self._tw.write(
@@ -270,28 +302,28 @@ def abort(self) -> None:
class AlignmentFile:
- """Build ``_ALIGNMENTDATA.h5`` under a temporary name.
+ """Build _ALIGNMENTDATA.h5 under a temporary name.
Parameters
----------
path : str or Path
- Final destination; the file is ``.partial`` until
+ Final destination; the file is .partial until
:func:`publish`.
var_shape : (int, int)
- Shape of each frame's variance factor ``(rows, cols)``.
+ Shape of each frame's variance factor (rows, cols).
n_frames : int
Number of registered frames.
deflate : int
- Deflate level of ``varFacDS`` (0 for none, as MATLAB writes it).
+ Deflate level of varFacDS (0 for none, as MATLAB writes it).
"""
def __init__(
self,
- path: Union[str, Path],
- var_shape,
+ path: str | Path,
+ var_shape: tuple[int, int],
n_frames: int,
deflate: int = 1,
- ):
+ ) -> None:
"""Create the temporary file and the variance-factor dataset."""
self.path = Path(path)
self.tmp = partial_path(self.path)
@@ -308,17 +340,17 @@ def __init__(
self._bg = _Background()
def write_var_factor(self, index: int, var_factor: np.ndarray) -> None:
- """Queue frame ``index``'s ``(rows, cols)`` variance factor."""
+ """Queue frame index's (rows, cols) variance factor."""
self._bg.submit(self._var.store, index, self._var.prepare(var_factor))
- def finish(self, fields: dict, settings: Optional[dict] = None) -> None:
+ def finish(self, fields: dict, settings: dict | None = None) -> None:
"""Write the remaining fields and close the (still temporary) file.
Parameters
----------
fields : dict
- Struct fields as accepted by ``write_matlab_value``; entries of a
- ``'slap2'`` dict go into the existing ``/slap2`` group.
+ Struct fields as accepted by write_matlab_value; entries of a
+ 'slap2' dict go into the existing /slap2 group.
settings : dict, optional
:func:`settings_record` of the registration, saved as the root
attribute :data:`SETTINGS_ATTR`.
@@ -352,8 +384,8 @@ def abort(self) -> None:
def publish(
movie: MovieWriter,
adata: AlignmentFile,
- stats_tmp: Optional[Path] = None,
- stats_path: Optional[Path] = None,
+ stats_tmp: Path | None = None,
+ stats_path: Path | None = None,
) -> None:
"""Move a finished movie and alignment file into place, as a pair.
@@ -369,10 +401,10 @@ def publish(
adata : AlignmentFile
A finished alignment file.
stats_tmp : Path, optional
- A finished statistics file (``registration.stats``), moved to
- ``stats_path`` with the movie.
+ A finished statistics file (registration.stats), moved to
+ stats_path with the movie.
stats_path : Path, optional
- The trial's statistics file; without ``stats_tmp`` an existing one
+ The trial's statistics file; without stats_tmp an existing one
(made from an earlier registration) is removed. Failures here are
logged and do not stop the movie and alignment file
(:func:`_publish_stats`).
@@ -384,13 +416,13 @@ def publish(
os.replace(adata.tmp, adata.path)
-def _publish_stats(stats_tmp: Optional[Path], stats_path: Path) -> None:
+def _publish_stats(stats_tmp: Path | None, stats_path: Path) -> None:
"""Move the statistics file into place, or remove an earlier one.
The statistics are optional: if the file cannot be moved, the trial is
published without statistics (an earlier file is removed, and one that
cannot be removed either names the earlier registration in its
- ``alignment_digest``); the error is logged.
+ alignment_digest); the error is logged.
"""
try:
if stats_tmp is not None:
@@ -409,16 +441,26 @@ def _publish_stats(stats_tmp: Optional[Path], stats_path: Path) -> None:
def downsample2(image: np.ndarray) -> np.ndarray:
- """Sum 2 x 2 blocks (trailing odd row/column dropped; NaN propagates)."""
+ """Sum 2 x 2 blocks (trailing odd row/column dropped; NaN propagates).
+
+ Returns
+ -------
+ np.ndarray
+ The block sums, with the last two dimensions halved.
+ """
h, w = image.shape[-2] // 2 * 2, image.shape[-1] // 2 * 2
x = image[..., :h, :w]
- return (x[..., 0::2, 0::2] + x[..., 0::2, 1::2] + x[..., 1::2, 0::2]) + x[
- ..., 1::2, 1::2
- ]
+ return (x[..., 0::2, 0::2] + x[..., 0::2, 1::2] + x[..., 1::2, 0::2]) + x[..., 1::2, 1::2]
+
+def matlab_round(x: ArrayLike) -> np.ndarray:
+ """Round half away from zero, as MATLAB's round.
-def matlab_round(x):
- """Round half away from zero, as MATLAB's ``round``."""
+ Returns
+ -------
+ np.ndarray
+ The rounded values, as float64.
+ """
x = np.asarray(x, dtype=np.float64)
return np.sign(x) * np.floor(np.abs(x) + 0.5)
@@ -429,21 +471,21 @@ def rec_neg_err(movie_ds: np.ndarray, align_hz: float) -> np.ndarray:
Frames are taken in chunks of at most 10 s; each chunk's template is its
NaN-ignoring median (NaN where more than 20% of frames are NaN). The
error is the RMS of the template's excess over the frame, relative to
- the template, both scaled by ``sqrt(max(0, template) + 10)``. As in
+ the template, both scaled by sqrt(max(0, template) + 10). As in
MATLAB, pixels where either is NaN count as zero in the numerator's mean
but are left out of the denominator's.
Parameters
----------
movie_ds : ndarray of float32
- ``(frames, rows, cols)`` spatially downsampled registered frames.
+ (frames, rows, cols) spatially downsampled registered frames.
align_hz : float
Frame rate.
Returns
-------
ndarray of float64
- ``(frames,)`` errors.
+ (frames,) errors.
"""
n = movie_ds.shape[0]
out = np.full(n, np.nan)
diff --git a/src/giant_python/registration/sources.py b/src/giant_python/registration/sources.py
index 0389df68..71fe2b8c 100644
--- a/src/giant_python/registration/sources.py
+++ b/src/giant_python/registration/sources.py
@@ -2,28 +2,28 @@
A frame source returns, for given frame times, each window pixel's value per
channel (NaN where it has no valid sample) and its freshness (0 there), as
-MultiRoiRegistration's ``getImageWrapper`` does after trimming:
+MultiRoiRegistration's getImageWrapper does after trimming:
-* :class:`PlainFrames`: ``slap2Frames`` frames, trimmed to the bounding box
+* :class:`PlainFrames`: slap2Frames frames, trimmed to the bounding box
of the pixels valid in the first initial frame (if it has none, of those
valid in any initial frame; MATLAB's window would be empty). Samples
behind the DMD curtain count as valid here (they were taken, only
unlit; see :mod:`giant_python.io.slap2_raster`), so that the window does
not depend on the online offsets.
-* :class:`CompensatedFrames`: ``slap2Frames(..., CompensateOnline=true,
- RefOffset= )`` frames, trimmed to the raster's extent. A
+* :class:`CompensatedFrames`: slap2Frames(..., CompensateOnline=true,
+ RefOffset= ) frames, trimmed to the raster's extent. A
sample moved by its line's online offset can land on a pixel the raster
does not sample; the window's pixel list is the union of every position
the trial's samples reach.
"""
from dataclasses import dataclass
-from typing import Optional
import numpy as np
import torch
+from numpy.typing import ArrayLike
-from ..io.slap2_raster import read_raster_samples
+from ..io.slap2_raster import RasterLayout, read_raster_samples
from .compensation import (
LineOffsets,
frame_offsets,
@@ -40,13 +40,13 @@ def has_samples(values: torch.Tensor) -> np.ndarray:
Parameters
----------
values : torch.Tensor
- ``(channels, frames, pixels)`` frame values, NaN where a pixel has
+ (channels, frames, pixels) frame values, NaN where a pixel has
no valid sample.
Returns
-------
ndarray of bool
- ``(frames,)``.
+ (frames,).
"""
return (~torch.isnan(values.sum(0))).any(-1).cpu().numpy()
@@ -71,11 +71,18 @@ class Window:
@property
def shape(self) -> tuple:
- """Window ``(rows, cols)``."""
+ """Window (rows, cols)."""
return self.trim_rows.size, self.trim_cols.size
def image(self, values: torch.Tensor, fill: float) -> torch.Tensor:
- """Place per-pixel values ``(..., pixels)`` into window images."""
+ """Place per-pixel values (..., pixels) into window images.
+
+ Returns
+ -------
+ torch.Tensor
+ The values scattered into images of the window's shape, with fill where the
+ window has no pixel.
+ """
flat = self.rows * self.shape[1] + self.cols
return window_image(values, flat, self.shape, fill)
@@ -94,20 +101,23 @@ class PlainFrames:
Kernel time constant in lines.
"""
- compensation: Optional[LineOffsets] = None
+ compensation: LineOffsets | None = None
- def __init__(self, former: FrameFormer, valid: np.ndarray, dt: int):
- """Trim the window to the valid pixels' bounding box."""
+ def __init__(self, former: FrameFormer, valid: np.ndarray, dt: int) -> None:
+ """Trim the window to the valid pixels' bounding box.
+
+ Raises
+ ------
+ ValueError
+ If valid has no valid pixel.
+ """
if not valid.any():
raise ValueError("the first initial frame has no samples")
dev = former.device
r0, r1 = former.rows[valid].min(), former.rows[valid].max()
c0, c1 = former.cols[valid].min(), former.cols[valid].max()
inside = np.flatnonzero(
- (former.rows >= r0)
- & (former.rows <= r1)
- & (former.cols >= c0)
- & (former.cols <= c1)
+ (former.rows >= r0) & (former.rows <= r1) & (former.cols >= c0) & (former.cols <= c1)
)
self.former = former
self.dt = int(dt)
@@ -119,14 +129,29 @@ def __init__(self, former: FrameFormer, valid: np.ndarray, dt: int):
cols=torch.from_numpy(former.cols[inside] - c0).to(dev),
)
- def frames(self, times):
- """``(channels, frames, pixels)`` values and ``(frames, pixels)``
- freshness at the window's pixels."""
+ def frames(self, times: ArrayLike) -> tuple[torch.Tensor, torch.Tensor]:
+ """Form (channels, frames, pixels) values and (frames, pixels) freshness.
+
+ Both are at the window's pixels.
+
+ Returns
+ -------
+ values : torch.Tensor
+ Pixel values, shape (channels, frames, pixels).
+ fresh : torch.Tensor
+ Freshness of each pixel, shape (frames, pixels).
+ """
vals, fresh = self.former.frames(times, self.dt)
return vals[:, :, self.pixels], fresh[:, self.pixels]
- def references(self, times) -> Optional[np.ndarray]:
- """Frame reference offsets (none without compensation)."""
+ def references(self, times: ArrayLike) -> np.ndarray | None:
+ """Frame reference offsets (none without compensation).
+
+ Returns
+ -------
+ None
+ Always, as uncompensated frames have no reference offsets.
+ """
return None
@@ -146,8 +171,8 @@ class CompensatedFrames:
"""
def __init__(
- self, former: FrameFormer, offsets: LineOffsets, dt: int, times
- ):
+ self, former: FrameFormer, offsets: LineOffsets, dt: int, times: ArrayLike
+ ) -> None:
"""Trim to the raster's extent and list every reachable pixel."""
self.former = former
self.compensation = offsets
@@ -158,9 +183,7 @@ def __init__(
trim_rows = np.arange(self._r0, r1 + 1) + 1
trim_cols = np.arange(self._c0, c1 + 1) + 1
self._shape = (trim_rows.size, trim_cols.size)
- reach = [
- self._landing(dr, dc) for dr, dc in self._displacements(times)
- ]
+ reach = [self._landing(dr, dc) for dr, dc in self._displacements(times)]
cand = np.unique(np.concatenate([f[f >= 0] for f in reach]))
self._lookup = np.full(self._shape[0] * self._shape[1], -1)
self._lookup[cand] = np.arange(cand.size)
@@ -172,8 +195,14 @@ def __init__(
cols=torch.from_numpy(cand % self._shape[1]).to(dev),
)
- def references(self, times) -> np.ndarray:
- """``(frames, 2)`` [x, y] offset each frame mostly saw."""
+ def references(self, times: ArrayLike) -> np.ndarray:
+ """(frames, 2) [x, y] offset each frame mostly saw.
+
+ Returns
+ -------
+ np.ndarray
+ The [x, y] line offset each frame mostly saw, shape (frames, 2).
+ """
return frame_offsets(
self.compensation,
times,
@@ -181,8 +210,14 @@ def references(self, times) -> np.ndarray:
self.former.layout.lines_per_cycle,
)
- def _displacements(self, times) -> np.ndarray:
- """Every (dr, dc) a sample of these frames can be moved by."""
+ def _displacements(self, times: ArrayLike) -> np.ndarray:
+ """Every (dr, dc) a sample of these frames can be moved by.
+
+ Returns
+ -------
+ np.ndarray
+ The distinct (dr, dc) row and column displacements, one per row.
+ """
times = np.asarray(times, dtype=np.int64).ravel()
refs = self.references(times)
p = self.former.layout.lines_per_cycle
@@ -197,15 +232,36 @@ def _displacements(self, times) -> np.ndarray:
return np.unique(np.concatenate(pairs), axis=0)
def _landing(self, dr: int, dc: int) -> np.ndarray:
- """Window flat index of each former pixel moved by (dr, dc)."""
+ """Window flat index of each former pixel moved by (dr, dc).
+
+ Returns
+ -------
+ np.ndarray
+ The flat index in the window image of each former pixel; -1 where the moved pixel
+ lies outside the window.
+ """
h, w = self._shape
r = self.former.rows - self._r0 + dr
c = self.former.cols - self._c0 + dc
inside = (r >= 0) & (r < h) & (c >= 0) & (c < w)
return np.where(inside, r * w + c, -1)
- def _destination(self, dr: int, dc: int):
- """Pixel-list index of each former pixel moved by (dr, dc)."""
+ def _destination(self, dr: int, dc: int) -> tuple[torch.Tensor, torch.Tensor]:
+ """Pixel-list index of each former pixel moved by (dr, dc).
+
+ Returns
+ -------
+ keep : torch.Tensor
+ Indices of the former pixels that land inside the frame.
+ dest : torch.Tensor
+ The pixel-list index each of those pixels lands on.
+
+ Raises
+ ------
+ ValueError
+ If a pixel moved by (dr, dc) lands inside the frame on a pixel that is not in
+ the pixel list.
+ """
key = (dr, dc)
if key not in self._dest:
flat = self._landing(dr, dc)
@@ -220,26 +276,37 @@ def _destination(self, dr: int, dc: int):
)
return self._dest[key]
- def frames(self, times):
- """``(channels, frames, pixels)`` values and ``(frames, pixels)``
- freshness at the window's pixels, samples moved per line."""
+ def frames(self, times: ArrayLike) -> tuple[torch.Tensor, torch.Tensor]:
+ """Form (channels, frames, pixels) values and (frames, pixels) freshness.
+
+ Both are at the window's pixels, samples moved per line.
+
+ Returns
+ -------
+ values : torch.Tensor
+ Pixel values, shape (channels, frames, pixels).
+ fresh : torch.Tensor
+ Freshness of each pixel, shape (frames, pixels).
+ """
times = np.asarray(times, dtype=np.int64).ravel()
refs = self.references(times)
n_ch = self.former.layout.num_channels
n = self.window.rows.numel()
dev = self.former.device
- num = torch.zeros(
- n_ch, times.size * n, dtype=torch.float64, device=dev
- )
+ num = torch.zeros(n_ch, times.size * n, dtype=torch.float64, device=dev)
den = torch.zeros_like(num)
- def shifts(lines):
- """Displacement of each sample's line for its frame."""
+ def shifts(lines: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Displacement of each sample's line for its frame.
+
+ Returns
+ -------
+ tuple[np.ndarray, np.ndarray]
+ The row and column displacement of each sample's line.
+ """
return line_shifts(self.compensation, lines, refs)
- for (dr, dc), sel, num_g, den_g in self.former.shifted_sums(
- times, self.dt, shifts
- ):
+ for (dr, dc), sel, num_g, den_g in self.former.shifted_sums(times, self.dt, shifts):
keep, dest = self._destination(dr, dc)
frames = torch.from_numpy(sel).to(dev)
flat = (frames[:, None] * n + dest[None, :]).reshape(-1)
@@ -250,8 +317,8 @@ def shifts(lines):
return (num / den).to(torch.float32), den[0].to(torch.float32)
-def _window_pixels(former: FrameFormer, init, dt: int) -> np.ndarray:
- """The former's pixels whose bounding box is the registration window.
+def _window_pixels(former: FrameFormer, init: np.ndarray, dt: int) -> np.ndarray:
+ """Select the former's pixels whose bounding box is the registration window.
MATLAB trims to the pixels valid in the first initial frame. When that
frame has no samples (e.g. a trial whose recording starts late), the
@@ -259,6 +326,12 @@ def _window_pixels(former: FrameFormer, init, dt: int) -> np.ndarray:
samples may cover only part of the raster. When no initial frame has
samples, the whole raster. Samples behind the DMD curtain count as
valid (:func:`_sampled`).
+
+ Returns
+ -------
+ np.ndarray
+ Boolean mask over the former's pixels: those valid in the first initial frame, else
+ in any initial frame, else every pixel.
"""
valid = _sampled(former, init[:1], dt)[0]
if valid.any():
@@ -269,15 +342,21 @@ def _window_pixels(former: FrameFormer, init, dt: int) -> np.ndarray:
return np.ones(former.rows.size, dtype=bool)
-def _sampled(former: FrameFormer, times, dt: int) -> np.ndarray:
- """``(frames, pixels)``: whether each frame has a valid sample of each
- of the former's pixels in every channel, counting the samples taken
- behind the DMD curtain.
+def _sampled(former: FrameFormer, times: ArrayLike, dt: int) -> np.ndarray:
+ """Whether each frame has a valid sample of each of the former's pixels in every channel.
+
+ Returns (frames, pixels), counting the samples taken behind the DMD
+ curtain.
The former's samples behind the curtain are marked invalid (see
:func:`giant_python.io.slap2_raster.unlit_samples`); with a curtain,
each frame is formed again from the raw samples of its cycles, as
without the mask.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean array of shape (frames, pixels).
"""
times = np.asarray(times, dtype=np.int64).ravel()
lay = former.layout
@@ -304,9 +383,16 @@ def _sampled(former: FrameFormer, times, dt: int) -> np.ndarray:
def make_source(
- layout, former, first_line, last_line, init, ds, dt, compensate: bool
-):
- """The trial's frame source.
+ layout: RasterLayout,
+ former: FrameFormer,
+ first_line: float,
+ last_line: float,
+ init: np.ndarray,
+ ds: np.ndarray,
+ dt: int,
+ compensate: bool,
+) -> PlainFrames | CompensatedFrames:
+ """Make the trial's frame source.
Parameters
----------
diff --git a/src/giant_python/registration/stats/__init__.py b/src/giant_python/registration/stats/__init__.py
index a7612144..f0140071 100644
--- a/src/giant_python/registration/stats/__init__.py
+++ b/src/giant_python/registration/stats/__init__.py
@@ -1,8 +1,8 @@
"""Per-trial summary statistics of a registered SLAP2 movie.
Computed from the registered movie alone, relative to photon noise, for the
-F0 network's next version (``slap2-F0-network``, plan
-``slap2-F0-network_next-version-plan.md``): single-frame moments and the
+F0 network's next version (slap2-F0-network, plan
+slap2-F0-network_next-version-plan.md): single-frame moments and the
share of zeros, the variance of 64-frame block means (slow), the second
and third moments of the frame minus its 65-frame running mean (fast), and
the top three shared modes of the binned movie (SVD). Every moment comes
@@ -11,13 +11,16 @@
normalised maps read 0 for photon noise at any brightness.
Registration computes them while it writes the movie
-(:mod:`..multiroi`); ``giant reg-stats`` computes the same maps for movies
-registered earlier, MATLAB's included. See ``docs/source/reg_stats.rst``.
+(:mod:`..multiroi`); giant reg-stats computes the same maps for movies
+registered earlier, MATLAB's included. See docs/source/reg_stats.rst.
"""
from __future__ import annotations
import logging
+from typing import TYPE_CHECKING
+
+import numpy.typing as npt
from .accumulate import TrialStatsAccumulator
from .gain import GainCurve, measure_gain_curves, validity_mismatch
@@ -31,6 +34,9 @@
)
from .session import combine_trials
+if TYPE_CHECKING:
+ from ..sources import CompensatedFrames, PlainFrames
+
log = logging.getLogger(__name__)
__all__ = [
@@ -48,8 +54,10 @@
]
-def new_accumulator(source, ds, margin: int, n_channels: int):
- """The statistics accumulator of a trial.
+def new_accumulator(
+ source: PlainFrames | CompensatedFrames, ds: npt.ArrayLike, margin: int, n_channels: int
+) -> TrialStatsAccumulator:
+ """Create the statistics accumulator of a trial.
Parameters
----------
@@ -58,7 +66,7 @@ def new_accumulator(source, ds, margin: int, n_channels: int):
ds : array_like of int
Frame times of the registered frames.
margin : int
- ``maxshift`` (padding of the registered grid).
+ maxshift (padding of the registered grid).
n_channels : int
Channels.
@@ -70,9 +78,7 @@ def new_accumulator(source, ds, margin: int, n_channels: int):
lay = source.former.layout
samples = source.former._samples
- gains = measure_gain_curves(
- samples, next_slots(lay.slot_line, lay.slot_pos)
- )
+ gains = measure_gain_curves(samples, next_slots(lay.slot_line, lay.slot_pos))
differ = validity_mismatch(samples)
for ch, n in enumerate(differ):
if n:
diff --git a/src/giant_python/registration/stats/accumulate.py b/src/giant_python/registration/stats/accumulate.py
index d729066e..95fc22b7 100644
--- a/src/giant_python/registration/stats/accumulate.py
+++ b/src/giant_python/registration/stats/accumulate.py
@@ -1,21 +1,21 @@
"""Streaming accumulation of a trial's statistics, frame by frame.
:class:`TrialStatsAccumulator` takes the registered frames in order (as
-registration writes them, or as ``giant reg-stats`` reads them back). Every
+registration writes them, or as giant reg-stats reads them back). Every
:data:`GEO_CHUNK` frames it forms their photon-noise sums
(:class:`.geometry.FrameGeometry`), reduced per frame and channel to
-* ``G0 = A2(t, t)`` and ``R0 = A3(t, t, t)`` (shared by the channels),
-* ``F(t) = sum_l A2(t, t + l)`` (pairs with later frames),
-* ``B(t) = sum_l A2(t - l, t)`` (pairs with earlier frames),
-* ``C(t)``: the sum over pairs ``(u, u')`` with ``u <= t < u'`` (pairs that
- cross the end of frame ``t``),
-* ``K(t) = sum_u A3(t, t, u)`` over ``|u - t| <= n_lags``,
+* G0 = A2(t, t) and R0 = A3(t, t, t) (shared by the channels),
+* F(t) = sum_l A2(t, t + l) (pairs with later frames),
+* B(t) = sum_l A2(t - l, t) (pairs with earlier frames),
+* C(t): the sum over pairs (u, u') with u <= t < u' (pairs that
+ cross the end of frame t),
+* K(t) = sum_u A3(t, t, u) over ``|u - t| <= n_lags``,
each over pairs of frames that are both valid at the pixel in that channel.
-Sums of ``A2`` over any run of frames follow from these exactly: the pairs
-within frames ``a .. b`` are ``sum_{a..b} F - C(b)``. Every
-:data:`BLOCK` frames (once ``FAST_HALF`` frames past the block have their
+Sums of A2 over any run of frames follow from these exactly: the pairs
+within frames a .. b are sum_{a..b} F - C(b). Every
+:data:`BLOCK` frames (once FAST_HALF frames past the block have their
sums) the block is added to the per-pixel sums. Frames are kept in ring
buffers of :data:`RING` frames.
@@ -25,13 +25,15 @@
Moments are summed in float64 from the float32 frames, photon-noise sums in
float32; the mean is also accumulated in float32 exactly as registration
-forms ``meanIM``, so the ``mean`` map equals the alignment file's ``meanIM``.
+forms meanIM, so the mean map equals the alignment file's meanIM.
"""
from __future__ import annotations
import functools
import time
+from collections.abc import Callable, Sequence
+from typing import TYPE_CHECKING, Concatenate, ParamSpec, TypeVar
import numpy as np
import torch
@@ -39,6 +41,13 @@
from .maps import ZERO_NU, finish_maps
+if TYPE_CHECKING:
+ from .gain import GainCurve
+ from .geometry import FrameGeometry
+
+_P = ParamSpec("_P")
+_R = TypeVar("_R")
+
BLOCK = 64
"""Frames per block of the slow part (and per processing step)."""
BLOCK_MIN = 48
@@ -64,21 +73,35 @@
def _capacity(n: int, cap: int) -> int:
- """Pixel capacity for ``n`` pixels (grown by half when exceeded)."""
+ """Pixel capacity for n pixels (grown by half when exceeded).
+
+ Returns
+ -------
+ int
+ cap if n fits in it, otherwise the grown capacity (at least 1024).
+ """
return cap if n <= cap else max(n, cap + cap // 2, 1024)
-def _widen(buf: torch.Tensor, cap: int, fill) -> torch.Tensor:
- """``buf`` with its last axis padded to ``cap`` with ``fill``."""
+def _widen(buf: torch.Tensor, cap: int, fill: float | bool) -> torch.Tensor:
+ """``buf`` with its last axis padded to cap with fill.
+
+ Returns
+ -------
+ torch.Tensor
+ buf with the last axis extended to length cap, the new entries set to fill.
+ """
pad = buf.new_full(buf.shape[:-1] + (cap - buf.shape[-1],), fill)
return torch.cat([buf, pad], -1)
class _Accumulators:
- """Per-pixel float64 sums ``(channels, n_idx)``, extended on growth
- (stored with spare pixel capacity)."""
+ """Per-pixel float64 sums (channels, n_idx), extended on growth.
+
+ Stored with spare pixel capacity.
+ """
- def __init__(self, n_channels: int, device):
+ def __init__(self, n_channels: int, device: torch.device) -> None:
"""No sums yet."""
self.c = n_channels
self.device = device
@@ -87,7 +110,13 @@ def __init__(self, n_channels: int, device):
self.data = {}
def __getitem__(self, name: str) -> torch.Tensor:
- """The sums ``name`` (zeros on first use), a view of ``n`` pixels."""
+ """Return the sums name (zeros on first use), a view of n pixels.
+
+ Returns
+ -------
+ torch.Tensor
+ The (channels, n) view of the sums name.
+ """
if name not in self.data:
self.data[name] = torch.zeros(
(self.c, self.cap), dtype=torch.float64, device=self.device
@@ -95,7 +124,7 @@ def __getitem__(self, name: str) -> torch.Tensor:
return self.data[name][:, : self.n]
def extend(self, n_new: int) -> None:
- """Add ``n_new`` pixels (zeros)."""
+ """Add n_new pixels (zeros)."""
self.n += n_new
cap = _capacity(self.n, self.cap)
if cap != self.cap:
@@ -104,28 +133,36 @@ def extend(self, n_new: int) -> None:
class _Ring:
- """Per-frame arrays ``(..., frames, n_idx)``; frame ``t`` is row
- ``t % frames``. Extended with each field's fill value on growth (stored
- with spare pixel capacity)."""
+ """Per-frame arrays (..., frames, n_idx); frame t is row t % frames.
+
+ Extended with each field's fill value on growth (stored with spare pixel
+ capacity).
+ """
- def __init__(self, frames: int):
+ def __init__(self, frames: int) -> None:
"""Empty fields."""
self.frames = frames
self.n = 0
self.cap = 0
self.fields = {}
- def _slots(self, frames, device) -> torch.Tensor:
- """Rows of frames ``frames``."""
+ def _slots(self, frames: Sequence[int], device: torch.device) -> torch.Tensor:
+ """Rows of frames frames.
+
+ Returns
+ -------
+ torch.Tensor
+ Ring rows (frame % frames) of the given frames, on device.
+ """
return torch.tensor([f % self.frames for f in frames], device=device)
- def put(self, name: str, frames, values: torch.Tensor, fill) -> None:
- """Store ``values`` ``(..., len(frames), n)`` as frames ``frames``."""
+ def put(
+ self, name: str, frames: Sequence[int], values: torch.Tensor, fill: float | bool
+ ) -> None:
+ """Store values (..., len(frames), n) as frames frames."""
if name not in self.fields:
shape = values.shape[:-2] + (self.frames, self.cap)
- buf = torch.full(
- shape, fill, dtype=values.dtype, device=values.device
- )
+ buf = torch.full(shape, fill, dtype=values.dtype, device=values.device)
self.fields[name] = (buf, fill)
buf = self.fields[name][0][..., : self.n]
if len(frames) == 1:
@@ -133,41 +170,74 @@ def put(self, name: str, frames, values: torch.Tensor, fill) -> None:
return
buf.index_copy_(buf.ndim - 2, self._slots(frames, buf.device), values)
- def rows(self, name: str, frames) -> torch.Tensor:
- """Frames ``frames`` of field ``name``: ``(..., len, n)``."""
+ def rows(self, name: str, frames: Sequence[int]) -> torch.Tensor:
+ """Frames frames of field name: (..., len, n).
+
+ Returns
+ -------
+ torch.Tensor
+ The stored values of the given frames, shaped (..., len(frames), n).
+ """
buf = self.fields[name][0][..., : self.n]
return buf.index_select(buf.ndim - 2, self._slots(frames, buf.device))
def extend(self, n_new: int) -> None:
- """Add ``n_new`` pixels (fill values) to every field."""
+ """Add n_new pixels (fill values) to every field."""
self.n += n_new
cap = _capacity(self.n, self.cap)
if cap != self.cap:
self.cap = cap
self.fields = {
- k: (_widen(buf, cap, fill), fill)
- for k, (buf, fill) in self.fields.items()
+ k: (_widen(buf, cap, fill), fill) for k, (buf, fill) in self.fields.items()
}
-def _window(cs: torch.Tensor, lo: torch.Tensor, hi: torch.Tensor):
- """Sums of rows ``lo .. hi`` (inclusive) from a cumulative sum with a
- leading zero row; ``lo`` and ``hi`` are row indices per centre."""
+def _window(cs: torch.Tensor, lo: torch.Tensor, hi: torch.Tensor) -> torch.Tensor:
+ """Sum rows lo .. hi (inclusive) from a cumulative sum with a leading zero row.
+
+ lo and hi are row indices per centre.
+
+ Returns
+ -------
+ torch.Tensor
+ The window sums, one per centre.
+ """
return cs[hi + 1] - cs[lo]
def _cumsum0(x: torch.Tensor) -> torch.Tensor:
- """Cumulative sum over rows with a leading zero row."""
+ """Cumulative sum over rows with a leading zero row.
+
+ Returns
+ -------
+ torch.Tensor
+ The cumulative sum of x over rows, with one more row than x.
+ """
return torch.cat([torch.zeros_like(x[:1]), torch.cumsum(x, 0)], 0)
-def _timed(fn):
- """Time a method into ``self.timing`` when ``self.profile`` is set
- (synchronizing the device; for measuring the cost only)."""
+def _timed(
+ fn: Callable[Concatenate[TrialStatsAccumulator, _P], _R],
+) -> Callable[Concatenate[TrialStatsAccumulator, _P], _R]:
+ """Time a method into self.timing when self.profile is set.
+
+ Synchronizes the device; for measuring the cost only.
+
+ Returns
+ -------
+ Callable
+ The wrapped method, with the same signature and return value as fn.
+ """
@functools.wraps(fn)
- def wrapper(self, *args, **kwargs):
- """Run ``fn``, timed if profiling."""
+ def wrapper(self: TrialStatsAccumulator, *args: _P.args, **kwargs: _P.kwargs) -> _R:
+ """Run fn, timed if profiling.
+
+ Returns
+ -------
+ _R
+ Whatever fn returns.
+ """
if not self.profile:
return fn(self, *args, **kwargs)
if self.device.type == "cuda":
@@ -179,9 +249,7 @@ def wrapper(self, *args, **kwargs):
if self.device.type == "cuda":
torch.cuda.synchronize(self.device)
key = fn.__name__.strip("_")
- self.timing[key] = self.timing.get(key, 0.0) + (
- time.perf_counter() - t0
- )
+ self.timing[key] = self.timing.get(key, 0.0) + (time.perf_counter() - t0)
self.timing["n_" + key] = self.timing.get("n_" + key, 0) + 1
return wrapper
@@ -193,15 +261,17 @@ class TrialStatsAccumulator:
Parameters
----------
geometry : FrameGeometry
- The trial's frame geometry (its ``ds`` are the frames to come).
+ The trial's frame geometry (its ds are the frames to come).
gains : list of GainCurve
Photon-noise gains per channel.
n_channels : int
Channels per frame.
"""
- def __init__(self, geometry, gains, n_channels: int):
- """Empty sums for ``geometry.ds.size`` frames."""
+ def __init__(
+ self, geometry: FrameGeometry, gains: Sequence[GainCurve], n_channels: int
+ ) -> None:
+ """Empty sums for geometry.ds.size frames."""
self.geo = geometry
self.gains = list(gains)
self.device = geometry.device
@@ -220,9 +290,7 @@ def __init__(self, geometry, gains, n_channels: int):
self.geo_chunk = GEO_CHUNK.get(kind, GEO_CHUNK["cpu"])
# frames from a pending block's first window frame to the newest
# (geometry lags by up to geo_chunk + n_lags frames), with margin
- self.ring = _Ring(
- BLOCK + 2 * FAST_HALF + self.geo_chunk + self.n_lags + 8
- )
+ self.ring = _Ring(BLOCK + 2 * FAST_HALF + self.geo_chunk + self.n_lags + 8)
self.hist = None
self.lagbuf = None
self.motion = np.full((self.n_frames, 2), np.nan)
@@ -240,19 +308,30 @@ def __init__(self, geometry, gains, n_channels: int):
# ---------------------------------------------------------------- intake
- def add(self, k: int, regs, var_factor: torch.Tensor, motion) -> None:
- """Take registered frame ``k``.
+ def add(
+ self,
+ k: int,
+ regs: Sequence[torch.Tensor],
+ var_factor: torch.Tensor,
+ motion: Sequence[float] | np.ndarray,
+ ) -> None:
+ """Take registered frame k.
Parameters
----------
k : int
Frame index (frames must come in order).
regs : sequence of torch.Tensor
- ``(rows, cols)`` float32 frame of each channel.
+ (rows, cols) float32 frame of each channel.
var_factor : torch.Tensor
- ``(rows, cols)`` variance factor of the frame.
+ (rows, cols) variance factor of the frame.
motion : (float, float)
The frame's row and column motion (NaN for a missing frame).
+
+ Raises
+ ------
+ ValueError
+ If k is not the next frame in order.
"""
if k != self.n_added:
raise ValueError(f"frame {k} came after {self.n_added - 1}")
@@ -261,8 +340,14 @@ def add(self, k: int, regs, var_factor: torch.Tensor, motion) -> None:
self._advance(final=False)
@_timed
- def _intake(self, k: int, regs, var_factor, motion) -> None:
- """Add frame ``k`` to the mean and the ring buffers."""
+ def _intake(
+ self,
+ k: int,
+ regs: Sequence[torch.Tensor],
+ var_factor: torch.Tensor,
+ motion: Sequence[float] | np.ndarray,
+ ) -> None:
+ """Add frame k to the mean and the ring buffers."""
x = torch.stack([r.to(self.device, torch.float32) for r in regs])
good = ~torch.isnan(x)
self.sum32 += torch.where(good, x, 0.0)
@@ -281,7 +366,7 @@ def _intake(self, k: int, regs, var_factor, motion) -> None:
self.present[k] = bool(np.all(np.isfinite(motion)))
def add_missing(self, k: int) -> None:
- """Take frame ``k`` as missing (no samples)."""
+ """Take frame k as missing (no samples)."""
blank = torch.full(self.shape, float("nan"), device=self.device)
self.add(k, [blank] * self.c, blank, (np.nan, np.nan))
@@ -299,9 +384,7 @@ def _grow(self, new: torch.Tensor) -> None:
self.acc.extend(n_new)
self.ring.extend(n_new)
if self.hist is not None and self.hist.shape[1] < self.acc.cap:
- pad = self.hist.new_zeros(
- (self.c, self.acc.cap - self.hist.shape[1], ZERO_NU.size)
- )
+ pad = self.hist.new_zeros((self.c, self.acc.cap - self.hist.shape[1], ZERO_NU.size))
self.hist = torch.cat([self.hist, pad], 1)
if self.lagbuf is not None:
self.lagbuf = {
@@ -314,18 +397,14 @@ def _grow(self, new: torch.Tensor) -> None:
def _advance(self, final: bool) -> None:
"""Form the frame sums and blocks whose inputs have all arrived."""
end = self.n_added if final else self.n_added - self.n_lags
- while self.geo_done < end and (
- final or end - self.geo_done >= self.geo_chunk
- ):
+ while self.geo_done < end and (final or end - self.geo_done >= self.geo_chunk):
g1 = min(end, self.geo_done + self.geo_chunk)
self._geometry(self.geo_done, g1)
self.geo_done = g1
n_blocks = -(-self.n_frames // BLOCK)
while self.block_done < n_blocks:
b1 = min(self.n_frames, (self.block_done + 1) * BLOCK)
- if not (
- final or self.geo_done >= min(self.n_frames, b1 + FAST_HALF)
- ):
+ if not (final or self.geo_done >= min(self.n_frames, b1 + FAST_HALF)):
break
self._block(self.block_done)
self.block_done += 1
@@ -334,7 +413,7 @@ def _advance(self, final: bool) -> None:
@_timed
def _geometry(self, g0: int, g1: int) -> None:
- """Photon-noise sums of frames ``[g0, g1)``, reduced per frame."""
+ """Photon-noise sums of frames [g0, g1), reduced per frame."""
lag = self.n_lags
f_ext = min(self.n_added, g1 + lag)
out = self.geo.registered(
@@ -355,11 +434,21 @@ def _geometry(self, g0: int, g1: int) -> None:
for name in PER_CHANNEL:
self.ring.put(name, frames, per[name], 0.0)
- def _lag_history(self, out: dict, g0: int):
- """Per-lag ``A2`` and ``A3(t, t + l, t + l)`` of the ``n_lags``
- frames before ``g0`` and of the chunk: ``(n_lags, lag + n, n_idx)``
- each (zero rows before frame 0); keeps the last rows for the next
- chunk."""
+ def _lag_history(self, out: dict, g0: int) -> tuple[torch.Tensor, torch.Tensor]:
+ """Per-lag A2 and A3(t, t + l, t + l) of recent frames and the chunk.
+
+ The frames are the n_lags before g0 and those of the chunk:
+ (n_lags, lag + n, n_idx) each (zero rows before frame 0); keeps
+ the last rows for the next chunk.
+
+ Returns
+ -------
+ g_all : torch.Tensor
+ (n_lags, lag + n, n_idx) per-lag A2 of the previous n_lags frames and
+ the chunk.
+ rp_all : torch.Tensor
+ (n_lags, lag + n, n_idx) per-lag A3(t, t + l, t + l) of the same frames.
+ """
lag = self.n_lags
g_new, rp_new = out["G"][1:], out["Rp"]
if self.lagbuf is None or g0 == 0:
@@ -371,8 +460,15 @@ def _lag_history(self, out: dict, g0: int):
return g_all, rp_all
def _per_channel(self, g0: int, g1: int, f_ext: int, out: dict) -> dict:
- """``F``, ``B``, ``C`` and ``K`` of frames ``[g0, g1)`` per channel
- ``(channels, g1 - g0, n_idx)`` (see the module text)."""
+ """F, B, C and K of frames [g0, g1) per channel.
+
+ Each is (channels, g1 - g0, n_idx) (see the module text).
+
+ Returns
+ -------
+ dict
+ F, B, C and K tensors, keyed by those names.
+ """
lag, n = self.n_lags, g1 - g0
n_idx = self.index.numel()
v = self.ring.rows("v", range(max(0, g0 - lag), f_ext)).float()
@@ -407,8 +503,7 @@ def _per_channel(self, g0: int, g1: int, f_ext: int, out: dict) -> dict:
return res
def _spatial_factor(self, g0: int, g1: int) -> None:
- """Add frames' bilinear and pair factors (2 x 2 sums) to the trial
- mean."""
+ """Add frames' bilinear and pair factors (2 x 2 sums) to the trial mean."""
from .geometry import pair_bin_factor, spatial_factor
_, _, frac = self.geo.corners(self.motion[g0:g1], self.present[g0:g1])
@@ -421,16 +516,13 @@ def _spatial_factor(self, g0: int, g1: int) -> None:
@_timed
def _block(self, j: int) -> None:
- """Add block ``j`` to every per-pixel sum."""
+ """Add block j to every per-pixel sum."""
b0 = j * BLOCK
b1 = min(self.n_frames, b0 + BLOCK)
s0 = max(0, b0 - FAST_HALF)
s1 = min(self.n_frames, b1 + FAST_HALF)
span = range(s0, s1)
- rows = {
- name: self.ring.rows(name, span)
- for name in ("x", "v") + SHARED + PER_CHANNEL
- }
+ rows = {name: self.ring.rows(name, span) for name in ("x", "v") + SHARED + PER_CHANNEL}
bins = []
for ch in range(self.c):
blk = _BlockChannel(self, ch, rows, (s0, b0, b1))
@@ -441,26 +533,44 @@ def _block(self, j: int) -> None:
# -------------------------------------------------------------- finish
def finish(self) -> dict:
- """Process the remaining frames and return the trial's statistics
- (see :func:`.maps.finish_maps`)."""
+ """Process the remaining frames and return the trial's statistics.
+
+ See :func:`.maps.finish_maps`.
+
+ Returns
+ -------
+ dict
+ The trial's statistics, as :func:`.maps.finish_maps` returns them.
+
+ Raises
+ ------
+ ValueError
+ If fewer or more frames were added than the trial has.
+ """
if self.n_added != self.n_frames:
- raise ValueError(
- f"{self.n_added} of {self.n_frames} frames were added"
- )
+ raise ValueError(f"{self.n_added} of {self.n_frames} frames were added")
self._advance(final=True)
return self._maps()
@_timed
def _maps(self) -> dict:
- """:func:`.maps.finish_maps` of this accumulator."""
+ """:func:`.maps.finish_maps` of this accumulator.
+
+ Returns
+ -------
+ dict
+ The result of :func:`.maps.finish_maps` for this accumulator.
+ """
return finish_maps(self)
class _BlockChannel:
- """One channel's sums over one block (frames ``[b0, b1)``)."""
+ """One channel's sums over one block (frames [b0, b1))."""
- def __init__(self, owner, ch, rows: dict, span):
- """Rows of the span ``[s0, ...)`` for channel ``ch``."""
+ def __init__(
+ self, owner: TrialStatsAccumulator, ch: int, rows: dict, span: tuple[int, int, int]
+ ) -> None:
+ """Rows of the span [s0, ...) for channel ch."""
self.o = owner
self.ch = ch
self.acc = owner.acc
@@ -490,11 +600,17 @@ def add_all(self) -> None:
self._zeros()
def _add(self, name: str, value: torch.Tensor) -> None:
- """Add to the per-pixel sums ``name`` of this channel."""
+ """Add to the per-pixel sums name of this channel."""
self.acc[name][self.ch] += value
def _pairs_within(self, a: int, b: int) -> torch.Tensor:
- """``sum_{t, u in [a, b)} A2(t, u)`` over valid pairs (span rows)."""
+ """sum_{t, u in [a, b)} A2(t, u) over valid pairs (span rows).
+
+ Returns
+ -------
+ torch.Tensor
+ Per-pixel sum of A2(t, u) over the valid pairs of frames in [a, b).
+ """
own = self.g0[a:b].sum(0) + 2 * self.f[a:b].sum(0)
return own - 2 * self.cr[b - 1]
@@ -512,8 +628,10 @@ def _single(self) -> None:
self._add("sq", self.qa2[rows].sum(0).double())
def _slow(self) -> None:
- """The mean of the block, its photon-noise variance and its
- covariance with the mean of the previous block."""
+ """Add the mean of the block, its photon-noise variance and covariance.
+
+ The covariance is with the mean of the previous block.
+ """
a, b = self.rows.start, self.rows.stop
nj = self.v[a:b].sum(0)
okj = nj >= BLOCK_MIN
@@ -537,9 +655,16 @@ def _slow(self) -> None:
self.acc["slow_prev_n"][self.ch] = nj
def _bins(self) -> torch.Tensor:
- """Means of the full 8-frame bins of the block (NaN where fewer
- than :data:`BIN_T_MIN` frames are valid); adds their photon-noise
- variances."""
+ """Means of the full 8-frame bins of the block; adds their photon-noise variances.
+
+ A bin's mean is NaN where fewer than :data:`BIN_T_MIN` frames are
+ valid.
+
+ Returns
+ -------
+ torch.Tensor of float32
+ (bins, n_idx) bin means, with no rows when the block holds no full bin.
+ """
a = self.rows.start
nb = (self.b1 - self.b0) // BIN_T
n = self.v.shape[1]
@@ -560,8 +685,16 @@ def _bins(self) -> torch.Tensor:
self._add("n8", ok.double().sum(0))
return torch.where(ok, mean, float("nan")).float()
- def _fast_rows(self):
- """Centres of the block (span rows) and their window bounds."""
+ def _fast_rows(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None:
+ """Centres of the block (span rows) and their window bounds.
+
+ Returns
+ -------
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor] or None
+ The centres rc and their window bounds rc - FAST_HALF and
+ rc + FAST_HALF (span rows), or None when the block has no centre with a full
+ window.
+ """
nf = self.o.n_frames
c0 = max(self.b0, FAST_HALF)
c1 = min(self.b1, nf - FAST_HALF)
@@ -591,15 +724,24 @@ def _fast(self) -> None:
for name, v in ph.items():
self._add(name, torch.where(ok, v.double(), zero).sum(0))
- def _fast_photon(self, rc, lo, hi, n):
- """Photon-noise variance and third cumulant of the fast part of
- each centre, per unit ``g2 mu`` and ``g3 mu`` (see the docs).
+ def _fast_photon(
+ self, rc: torch.Tensor, lo: torch.Tensor, hi: torch.Tensor, n: torch.Tensor
+ ) -> dict[str, torch.Tensor]:
+ """Photon-noise variance and third cumulant of the fast part of each centre.
+
+ Both are per unit g2 mu and g3 mu (see the docs).
- ``Var(Z_t) = A2(t, t) - 2 L_t / n + P_t / n^2`` with ``L_t`` the
- sum of ``A2(t, u)`` over the window and ``P_t`` the sum over pairs
- of window frames; ``kappa3(Z_t) = R0 - 3 K_t / n + 3 L_t^2 / n^2 -
- sum_u L_u^2 / n^3`` (the last two terms approximate the products of
+ Var(Z_t) = A2(t, t) - 2 L_t / n + P_t / n^2 with L_t the
+ sum of A2(t, u) over the window and P_t the sum over pairs
+ of window frames; kappa3(Z_t) = R0 - 3 K_t / n + 3 L_t^2 / n^2 -
+ sum_u L_u^2 / n^3 (the last two terms approximate the products of
three coefficients of which two are of other frames).
+
+ Returns
+ -------
+ dict[str, torch.Tensor]
+ Per-centre q2 (variance), q2l, qa, q3 (third cumulant), q3a and
+ q3b.
"""
lsum = self.g0 + self.f + self.b
cs_pairs = _cumsum0(self.g0 + 2 * self.f)
@@ -626,9 +768,11 @@ def _fast_photon(self, rc, lo, hi, n):
}
def _zeros(self) -> None:
- """Add ``exp(-nu N_eff)`` of every valid frame at the rates
- :data:`ZERO_NU`, with ``N_eff = N0 - shared M0`` (pairs of
- consecutive samples share zero events)."""
+ """Add exp(-nu N_eff) of every valid frame at the rates :data:`ZERO_NU`.
+
+ Here N_eff = N0 - shared M0 (pairs of consecutive samples share
+ zero events).
+ """
o = self.o
rows = self.rows
n = self.v.shape[1]
diff --git a/src/giant_python/registration/stats/gain.py b/src/giant_python/registration/stats/gain.py
index a8e24469..6d4489b3 100644
--- a/src/giant_python/registration/stats/gain.py
+++ b/src/giant_python/registration/stats/gain.py
@@ -2,35 +2,35 @@
A raw sample is the summed height of the photon pulses that arrived during
it. Pulse heights vary (a single photon gives about 1 to 250 raw units), so a
-sample with mean ``mu`` has, under photon noise alone, variance
-``g2 * mu`` and third cumulant ``g3 * mu`` (compound Poisson), where
-``g2 = E[A^2] / E[A]`` and ``g3 = E[A^3] / E[A]`` for pulse height ``A``. On
-SLAP2 both depend on brightness (``g2`` is about 110 in the dimmest slots and
+sample with mean mu has, under photon noise alone, variance
+g2 * mu and third cumulant g3 * mu (compound Poisson), where
+g2 = E[A^2] / E[A] and g3 = E[A^3] / E[A] for pulse height A. On
+SLAP2 both depend on brightness (g2 is about 110 in the dimmest slots and
130-140 in bright ones), so each is measured per channel as a curve over the
slots' mean.
The curve comes from the trial's own raw samples: for every slot and every
-three successive cycles ``x0, x1, x2`` with valid samples, the second
-difference ``d = 2 x1 - x0 - x2`` has ``E[d^2] = 6 kappa2`` and
-``E[d^3] = 6 kappa3`` and is insensitive to linear drift. Slots are sorted by
+three successive cycles x0, x1, x2 with valid samples, the second
+difference d = 2 x1 - x0 - x2 has E[d^2] = 6 kappa2 and
+E[d^3] = 6 kappa3 and is insensitive to linear drift. Slots are sorted by
their mean and split into :data:`N_BINS` groups of equal size; per group
-``g2 = sum(d^2) / (6 sum(x1))`` and ``g3 = sum(d^3) / (6 sum(x1))``. All
+g2 = sum(d^2) / (6 sum(x1)) and g3 = sum(d^3) / (6 sum(x1)). All
sums are exact integers, so the curve does not depend on the device.
The share of exact zeros gives the rate of non-zero samples per sample,
-``nu = -log(zero share)``, stored per unit mean (``nu / mu``); it gives the
-photon-noise share of zeros of a frame (see ``accumulate``).
+nu = -log(zero share), stored per unit mean (nu / mu); it gives the
+photon-noise share of zeros of a frame (see accumulate).
Consecutive samples on a line share photons: a pulse that falls on the
boundary between two samples is split between them, so the sample and the
next one (usually the neighbouring pixel) are correlated (about 0.13-0.25 on
-SLAP2). For every pair of consecutive samples ``(s, n)`` the same second
-differences give ``E[d_s d_n] = 6 cov``, ``E[d_s^2 d_n] = 6 kappa(s, s, n)``
-and ``E[d_s d_n^2] = 6 kappa(s, n, n)``; pairs are grouped by their mean like
-slots, and each is stored per unit mean (``c2``, ``c3a``, ``c3b``). The
+SLAP2). For every pair of consecutive samples (s, n) the same second
+differences give E[d_s d_n] = 6 cov, E[d_s^2 d_n] = 6 kappa(s, s, n)
+and E[d_s d_n^2] = 6 kappa(s, n, n); pairs are grouped by their mean like
+slots, and each is stored per unit mean (c2, c3a, c3b). The
excess of exact zeros in both samples over independence gives the rate of
-shared non-zero events, ``nu_s = log(P(both 0) / (P(s 0) P(n 0)))``, stored
-relative to the samples' own rate (``zero_shared = nu_s / nu``).
+shared non-zero events, nu_s = log(P(both 0) / (P(s 0) P(n 0))), stored
+relative to the samples' own rate (zero_shared = nu_s / nu).
"""
from __future__ import annotations
@@ -39,6 +39,7 @@
import numpy as np
import torch
+from numpy.typing import ArrayLike
from ...io.slap2_raster import INVALID_SAMPLE
@@ -52,7 +53,13 @@
def _pass_size(device: torch.device) -> int:
- """:data:`SLOTS_PER_PASS` of a device."""
+ """:data:`SLOTS_PER_PASS` of a device.
+
+ Returns
+ -------
+ int
+ Number of slots to sum per pass on the device type (CPU size for unknown types).
+ """
return SLOTS_PER_PASS.get(device.type, SLOTS_PER_PASS["cpu"])
@@ -63,15 +70,15 @@ class GainCurve:
Attributes
----------
mu : ndarray of float64
- ``(K,)`` mean raw value per sample of each brightness group
+ (K,) mean raw value per sample of each brightness group
(increasing).
g2, g3 : ndarray of float64
- ``(K,)`` variance and third cumulant per unit mean.
+ (K,) variance and third cumulant per unit mean.
nu_per_mu : ndarray of float64
- ``(K,)`` rate of non-zero samples per unit mean (NaN for a group
+ (K,) rate of non-zero samples per unit mean (NaN for a group
without zeros).
n_slots : ndarray of int64
- ``(K,)`` slots in each group.
+ (K,) slots in each group.
"""
mu: np.ndarray
@@ -86,19 +93,19 @@ class GainCurve:
zero_shared: np.ndarray = field(default_factory=lambda: np.zeros(0))
n_pairs: np.ndarray = field(default_factory=lambda: np.zeros(0, np.int64))
- def at(self, mean) -> dict:
- """Gains at per-sample means ``mean`` (any shape).
+ def at(self, mean: ArrayLike) -> dict:
+ """Gains at per-sample means mean (any shape).
- Linear in ``log(mean)`` between the groups' means and constant
+ Linear in log(mean) between the groups' means and constant
beyond the first and last group (0 for the pair terms of a curve
without pairs). The non-zero rate uses the groups that have zeros
(NaN if none has).
Returns
-------
- dict of ndarray (float64, the shape of ``mean``)
- ``g2``, ``g3``, ``nu`` (non-zero rate per sample), and the pair
- terms ``c2``, ``c3a``, ``c3b`` (per unit mean).
+ dict of ndarray (float64, the shape of mean)
+ g2, g3, nu (non-zero rate per sample), and the pair
+ terms c2, c3a, c3b (per unit mean).
"""
mean = np.asarray(mean, dtype=np.float64)
x = np.log(np.maximum(mean, 1e-12))
@@ -120,16 +127,32 @@ def at(self, mean) -> dict:
return {k: np.where(bad, np.nan, v) for k, v in out.items()}
def shared_zero_fraction(self) -> float:
- """The pairs' rate of shared non-zero events relative to their own
- rate, over the dimmer half of the pair groups (where zeros are
- frequent; 0 without pairs)."""
+ """Compute the pairs' rate of shared non-zero events relative to their own rate.
+
+ Over the dimmer half of the pair groups (where zeros are frequent; 0
+ without pairs).
+
+ Returns
+ -------
+ float
+ Median shared-zero rate over the dimmer half of the pair groups;
+ 0.0 when there are no finite values.
+ """
z = self.zero_shared[np.isfinite(self.zero_shared)]
if z.size == 0:
return 0.0
return float(np.median(z[: max(1, (z.size + 1) // 2)]))
def describe(self) -> dict:
- """The curve as arrays (for the statistics file)."""
+ """Return the curve as arrays (for the statistics file).
+
+ Returns
+ -------
+ dict
+ The curve arrays by field name: mu, g2, g3, nu_per_mu,
+ n_slots, mu_pair, c2, c3a, c3b, zero_shared
+ and n_pairs.
+ """
return {
k: getattr(self, k)
for k in (
@@ -144,29 +167,43 @@ def describe(self) -> dict:
def _sums(columns: list, bound: float, n: int) -> np.ndarray:
- """Per-slot sums of ``columns`` ``(slots, n)`` each: exact int64 when
- ``n`` terms of magnitude at most ``bound`` cannot overflow it, float64
- otherwise (long trials of extreme samples; second differences reach
- ``4 * 32767``, so cubes over more than about 2000 cycles could)."""
+ """Per-slot sums of columns (slots, n) each.
+
+ Exact int64 when n terms of magnitude at most bound cannot
+ overflow it, float64 otherwise (long trials of extreme samples; second
+ differences reach 4 * 32767, so cubes over more than about 2000
+ cycles could).
+
+ Returns
+ -------
+ np.ndarray
+ (slots, len(columns)) sums, int64 or float64 as described above.
+ """
if bound * max(n, 1) < INT64_SAFE:
return torch.stack([c.sum(1) for c in columns], 1).cpu().numpy()
return torch.stack([c.double().sum(1) for c in columns], 1).cpu().numpy()
def _cube_bound(*xs: torch.Tensor) -> float:
- """Worst-case magnitude of a product of three second differences."""
+ """Worst-case magnitude of a product of three second differences.
+
+ Returns
+ -------
+ float
+ ``(4 * max|x|) ** 3``, with the maximum taken over all given tensors.
+ """
big = max((int(x.abs().max()) if x.numel() else 0) for x in xs)
return float(4 * big) ** 3
def _slot_sums(x: torch.Tensor) -> np.ndarray:
- """Exact per-slot sums of one channel's samples ``(slots, cycles)``.
+ """Exact per-slot sums of one channel's samples (slots, cycles).
Returns
-------
ndarray of int64 (float64 where int64 could overflow, see :func:`_sums`)
- ``(slots, 7)``: valid samples, their sum, zeros, triples, and the
- sums of ``x1``, ``d^2`` and ``d^3`` over triples.
+ (slots, 7): valid samples, their sum, zeros, triples, and the
+ sums of x1, d^2 and d^3 over triples.
"""
x = x.to(torch.int64)
valid = x != INVALID_SAMPLE
@@ -180,40 +217,41 @@ def _slot_sums(x: torch.Tensor) -> np.ndarray:
def slot_sums(samples: torch.Tensor, channel: int) -> np.ndarray:
- """:func:`_slot_sums` of every slot, in passes of
- :data:`SLOTS_PER_PASS`.
+ """:func:`_slot_sums` of every slot, in passes of :data:`SLOTS_PER_PASS`.
Parameters
----------
samples : torch.Tensor of int16
- ``(channels, slots, cycles)`` raw samples (as a frame former holds
+ (channels, slots, cycles) raw samples (as a frame former holds
them).
channel : int
Zero-based channel.
+
+ Returns
+ -------
+ np.ndarray
+ (slots, 7) sums as in :func:`_slot_sums`, concatenated over the passes.
"""
n = samples.shape[1]
if samples.shape[2] < 3:
return np.zeros((n, 7), dtype=np.int64)
step = _pass_size(samples.device)
- parts = [
- _slot_sums(samples[channel, a : a + step]) for a in range(0, n, step)
- ]
+ parts = [_slot_sums(samples[channel, a : a + step]) for a in range(0, n, step)]
return np.concatenate(parts) if parts else np.zeros((0, 7), np.int64)
def validity_mismatch(samples: torch.Tensor) -> list:
- """Per channel, the samples whose validity differs from the first
- channel's.
+ """Per channel, the samples whose validity differs from the first channel's.
Frames are formed from each channel's own valid samples, but
- registration's freshness and ``varFacDS``, and so the photon-noise
+ registration's freshness and varFacDS, and so the photon-noise
model, follow the first channel's; where another channel's invalid
samples differ, its expectations assume the first channel's samples.
Parameters
----------
samples : torch.Tensor of int16
- ``(channels, slots, cycles)`` raw samples.
+ (channels, slots, cycles) raw samples.
Returns
-------
@@ -231,7 +269,14 @@ def validity_mismatch(samples: torch.Tensor) -> list:
def next_slots(slot_line: np.ndarray, slot_pos: np.ndarray) -> np.ndarray:
- """The slot sampled right after each slot on its line (-1 for none)."""
+ """Find the slot sampled right after each slot on its line (-1 for none).
+
+ Returns
+ -------
+ np.ndarray
+ int64 array, one entry per slot: index of the next slot on the same line,
+ or -1 when there is none.
+ """
order = np.lexsort((slot_pos, slot_line))
nxt = np.full(slot_line.size, -1, dtype=np.int64)
a, b = order[:-1], order[1:]
@@ -241,23 +286,29 @@ def next_slots(slot_line: np.ndarray, slot_pos: np.ndarray) -> np.ndarray:
def _pair_sums(xa: torch.Tensor, xb: torch.Tensor) -> np.ndarray:
- """Exact sums over cycles of consecutive-sample pairs ``(slots,
- cycles)`` each.
+ """Exact sums over cycles of consecutive-sample pairs (slots, cycles) each.
Returns
-------
ndarray of int64 (float64 where int64 could overflow)
- ``(pairs, 9)``: triples valid in both, ``sum(x1_a + x1_b)``,
- ``sum(d_a d_b)``, ``sum(d_a^2 d_b)``, ``sum(d_a d_b^2)``; cycles
- valid in both, and of them the zeros of ``a``, of ``b`` and of
+ (pairs, 9): triples valid in both, sum(x1_a + x1_b),
+ sum(d_a d_b), sum(d_a^2 d_b), sum(d_a d_b^2); cycles
+ valid in both, and of them the zeros of a, of b and of
both.
"""
xa, xb = xa.to(torch.int64), xb.to(torch.int64)
va, vb = xa != INVALID_SAMPLE, xb != INVALID_SAMPLE
a0, b0 = torch.where(va, xa, 0), torch.where(vb, xb, 0)
- def second(x0, v):
- """Second differences and where they are defined."""
+ def second(x0: torch.Tensor, v: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """Second differences and where they are defined.
+
+ Returns
+ -------
+ tuple[torch.Tensor, torch.Tensor]
+ The second differences 2 x1 - x0 - x2 and a boolean mask of the
+ cycle triples whose three samples are all valid.
+ """
ok = v[:, :-2] & v[:, 1:-1] & v[:, 2:]
return 2 * x0[:, 1:-1] - x0[:, :-2] - x0[:, 2:], ok
@@ -273,8 +324,15 @@ def second(x0, v):
return _sums(cols, _cube_bound(a0, b0), xa.shape[1])
-def pair_sums(samples: torch.Tensor, channel: int, nxt: np.ndarray):
- """:func:`_pair_sums` of every slot with a next slot, in passes."""
+def pair_sums(samples: torch.Tensor, channel: int, nxt: np.ndarray) -> np.ndarray:
+ """:func:`_pair_sums` of every slot with a next slot, in passes.
+
+ Returns
+ -------
+ np.ndarray
+ (pairs, 9) sums as in :func:`_pair_sums`, one row per slot with a next
+ slot; shape (0, 9) when there are no pairs.
+ """
first = np.flatnonzero(nxt >= 0)
if samples.shape[2] < 3 or first.size == 0:
return np.zeros((0, 9), dtype=np.int64)
@@ -292,12 +350,16 @@ def pair_curve(sums: np.ndarray, n_bins: int = N_BINS) -> dict:
"""Pair terms of :class:`GainCurve` from :func:`pair_sums`.
Pairs with at least 3 triples and a positive mean are sorted by their
- mean and split into ``n_bins`` groups of equal size.
+ mean and split into n_bins groups of equal size.
+
+ Returns
+ -------
+ dict
+ Arrays of the pair groups: mu_pair, c2, c3a, c3b,
+ zero_shared (float64) and n_pairs (int64).
"""
# group sums in float64: exact below 2^53, no int64 overflow
- n_trip, s_mid, s2, s3a, s3b, n_both, za, zb, zab = np.asarray(
- sums, dtype=np.float64
- ).T
+ n_trip, s_mid, s2, s3a, s3b, n_both, za, zb, zab = np.asarray(sums, dtype=np.float64).T
use = np.flatnonzero((n_trip >= 3) & (s_mid > 0))
order = use[np.argsort(s_mid[use] / n_trip[use], kind="stable")]
rows = []
@@ -312,11 +374,7 @@ def pair_curve(sums: np.ndarray, n_bins: int = N_BINS) -> dict:
zb[grp].sum() / nb,
zab[grp].sum() / nb,
)
- nu = (
- -0.5 * (np.log(pa) + np.log(pb))
- if 0 < pa < 1 and 0 < pb < 1
- else np.nan
- )
+ nu = -0.5 * (np.log(pa) + np.log(pb)) if 0 < pa < 1 and 0 < pb < 1 else np.nan
shared = np.log(pab / (pa * pb)) / nu if pab > 0 and nu > 0 else np.nan
rows.append(
(mid / n_trip[grp].sum(), s2[grp].sum() / den,
@@ -335,17 +393,21 @@ def pair_curve(sums: np.ndarray, n_bins: int = N_BINS) -> dict:
def curve_from_sums(sums: np.ndarray, n_bins: int = N_BINS) -> GainCurve:
- """The gain curve of per-slot sums (:func:`slot_sums`).
+ """Compute the gain curve of per-slot sums (:func:`slot_sums`).
Slots with at least 3 triples and a positive mean are sorted by mean
- (ties by slot) and split into ``n_bins`` groups of equal size (sizes
+ (ties by slot) and split into n_bins groups of equal size (sizes
differ by at most one); groups without photons are dropped. A group
without zeros keeps its gains; its non-zero rate is NaN.
+
+ Returns
+ -------
+ GainCurve
+ The single-sample gain curve (mu, g2, g3, nu_per_mu,
+ n_slots) with one entry per brightness group.
"""
# group sums in float64: exact below 2^53, no int64 overflow
- n_valid, total, zeros, n_trip, s1, s2, s3 = np.asarray(
- sums, dtype=np.float64
- ).T
+ n_valid, total, zeros, n_trip, s1, s2, s3 = np.asarray(sums, dtype=np.float64).T
use = np.flatnonzero((n_trip >= 3) & (total > 0))
mean = total[use] / n_valid[use]
order = use[np.argsort(mean, kind="stable")]
@@ -357,9 +419,7 @@ def curve_from_sums(sums: np.ndarray, n_bins: int = N_BINS) -> GainCurve:
zero = zeros[grp].sum() / n_valid[grp].sum()
nu = -np.log(zero) if 0 < zero < 1 else np.nan
den = 6.0 * float(s1[grp].sum())
- rows.append(
- (mu, s2[grp].sum() / den, s3[grp].sum() / den, nu / mu, grp.size)
- )
+ rows.append((mu, s2[grp].sum() / den, s3[grp].sum() / den, nu / mu, grp.size))
arr = np.array(rows, dtype=np.float64).reshape(-1, 5)
keep = np.isfinite(arr[:, :3]).all(1)
arr = arr[keep]
@@ -373,14 +433,14 @@ def curve_from_sums(sums: np.ndarray, n_bins: int = N_BINS) -> GainCurve:
def measure_gain_curves(
- samples: torch.Tensor, nxt=None, n_bins: int = N_BINS
+ samples: torch.Tensor, nxt: np.ndarray | None = None, n_bins: int = N_BINS
) -> list:
"""Every channel's :class:`GainCurve` from a trial's raw samples.
Parameters
----------
samples : torch.Tensor of int16
- ``(channels, slots, cycles)``, e.g. ``FrameFormer._samples``.
+ (channels, slots, cycles), e.g. FrameFormer._samples.
nxt : ndarray of int, optional
:func:`next_slots` of the layout (without, no pair terms).
n_bins : int
@@ -395,9 +455,7 @@ def measure_gain_curves(
for ch in range(samples.shape[0]):
curve = curve_from_sums(slot_sums(samples, ch), n_bins)
if nxt is not None:
- for k, v in pair_curve(
- pair_sums(samples, ch, nxt), n_bins
- ).items():
+ for k, v in pair_curve(pair_sums(samples, ch, nxt), n_bins).items():
setattr(curve, k, v)
out.append(curve)
return out
diff --git a/src/giant_python/registration/stats/geometry.py b/src/giant_python/registration/stats/geometry.py
index fd6b4cf2..c3ff6297 100644
--- a/src/giant_python/registration/stats/geometry.py
+++ b/src/giant_python/registration/stats/geometry.py
@@ -1,31 +1,31 @@
"""Which raw samples enter each registered pixel, and with what weight.
A registered frame is linear in the raw samples. Frame formation gives raw
-pixel ``k`` at frame ``t`` the weighted mean ``sum_s w_s(t) x_s / F1_k(t)``
+pixel k at frame t the weighted mean sum_s w_s(t) x_s / F1_k(t)
of its samples, with exp-kernel weights ``w_s(t) = exp(-|t - l_s| / dt)``
-for samples within ``max(3 dt, P)`` lines (:mod:`..frames`). Registration
-resamples it by a rigid shift with bilinear coefficients ``c_t(a, b)`` on
+for samples within max(3 dt, P) lines (:mod:`..frames`). Registration
+resamples it by a rigid shift with bilinear coefficients c_t(a, b) on
the four raw pixels around each output pixel, weighted by their summed
weights (:mod:`..interpolation`):
X_t(p) = sum_ab c_t(ab) sum_{s in k_ab} w_s(t) x_s / D_t(p),
D_t(p) = sum_ab c_t(ab) F1_{k_ab}(t) = 1 / varFacDS.
-So ``X_t(p) = sum_s a_ts x_s`` with ``a_ts = c_t(ab) w_s(t) / D_t(p)``.
-Under photon noise (:mod:`.gain`) and a pixel brightness ``mu`` that is the
-same for those samples, ``Cov(X_t, X_u) = g2 mu A2(t, u)`` and the third
-cross-cumulant is ``g3 mu A3(t, t, u)``, where
+So X_t(p) = sum_s a_ts x_s with a_ts = c_t(ab) w_s(t) / D_t(p).
+Under photon noise (:mod:`.gain`) and a pixel brightness mu that is the
+same for those samples, Cov(X_t, X_u) = g2 mu A2(t, u) and the third
+cross-cumulant is g3 mu A3(t, t, u), where
A2(t, u) = sum_s a_ts a_us,
A3(t, t, u) = sum_s a_ts^2 a_us, A3(t, u, u) = sum_s a_ts a_us^2.
-Frames ``t`` and ``t + l`` share samples only for ``l <= n_lags`` (both
-kernels must reach the sample: ``l * spacing <= 2 max(3 dt, P)``; 6 at
+Frames t and t + l share samples only for l <= n_lags (both
+kernels must reach the sample: l * spacing <= 2 max(3 dt, P); 6 at
80 Hz on SLAP2). This module computes these sums exactly from the raster's
layout and the frame times, assuming every sample in reach is valid, and
-rescales them with the actual ``D_t(p)`` from ``varFacDS``: where samples
+rescales them with the actual D_t(p) from varFacDS: where samples
were invalid, the sums of the remaining ones are taken as proportional
-(``F_j ~ (D_actual / D_all_valid) F_j``), which is exact when none is.
+(F_j ~ (D_actual / D_all_valid) F_j), which is exact when none is.
With online compensation (:class:`..sources.CompensatedFrames`) each
sample is placed by its line's displacement for the frame; a sample shared
@@ -34,36 +34,42 @@
Per frame the outputs are, at a set of output pixels:
-* ``G[0] = A2(t, t)``, ``G[l] = A2(t, t + l)`` (``l = 1 .. n_lags``);
-* ``R0 = A3(t, t, t)``, ``R[l] = A3(t, t, t + l)``,
- ``Rp[l] = A3(t, t + l, t + l)``;
-* ``N0``: the number of samples with a non-zero coefficient (for the
+* G[0] = A2(t, t), G[l] = A2(t, t + l) (l = 1 .. n_lags);
+* R0 = A3(t, t, t), R[l] = A3(t, t, t + l),
+ Rp[l] = A3(t, t + l, t + l);
+* N0: the number of samples with a non-zero coefficient (for the
photon-noise share of zeros).
Consecutive samples on a line share photons (:mod:`.gain`), so a registered
-pixel's photon noise also has terms from pairs ``(s, n)`` of consecutive
+pixel's photon noise also has terms from pairs (s, n) of consecutive
samples that both enter it (in two of its raw pixels, usually neighbours
-along the line): ``2 c2 mu sum a_s a_n`` in the variance and ``3 mu sum
-(c3a a_s^2 a_n + c3b a_s a_n^2)`` in the third cumulant. Both samples are
+along the line): 2 c2 mu sum a_s a_n in the variance and 3 mu sum
+(c3a a_s^2 a_n + c3b a_s a_n^2) in the third cumulant. Both samples are
on the same line, so they have the same kernel weight. Per frame:
-* ``QA2 = sum a_s a_n``, ``QA3a = sum a_s^2 a_n``, ``QA3b = sum a_s a_n^2``
- over such pairs, and ``M0``, the number of pairs both of whose samples
+* QA2 = sum a_s a_n, QA3a = sum a_s^2 a_n, QA3b = sum a_s a_n^2
+ over such pairs, and M0, the number of pairs both of whose samples
have a non-zero coefficient.
These are exact for a frame with itself; for two frames that share samples
-the accumulator scales them by the pixel's own ratio (see ``maps``).
+the accumulator scales them by the pixel's own ratio (see maps).
"""
from __future__ import annotations
import math
+from collections.abc import Sequence
+from typing import TYPE_CHECKING
import numpy as np
+import numpy.typing as npt
import torch
from ..compensation import line_shifts
+if TYPE_CHECKING:
+ from ..sources import CompensatedFrames, PlainFrames
+
MAX_LAGS = 7
"""Largest lag supported: below the SVD's 8-frame bins, so that a pair of
frames that share samples never spans a whole bin (SLAP2 rasters reach it
@@ -75,17 +81,22 @@
pixels; bounds memory)."""
CORNERS = ((0, 0), (0, 1), (1, 0), (1, 1))
-"""Bilinear neighbours ``(a, b)`` in ``interp_frame``'s order."""
+"""Bilinear neighbours (a, b) in interp_frame's order."""
-NEIGHBOURS = tuple(
- (dr, dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1) if (dr, dc) != (0, 0)
-)
+NEIGHBOURS = tuple((dr, dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1) if (dr, dc) != (0, 0))
"""Directions from a sample's pixel to the next sample's pixel that two
corners of one output pixel can have."""
-def corner_pairs(delta):
- """``[(k, k2)]``: corners ``k`` and ``k2`` with ``k2 = k + delta``."""
+def corner_pairs(delta: Sequence[int]) -> list[tuple[int, int]]:
+ """[(k, k2)]: corners k and k2 with k2 = k + delta.
+
+ Returns
+ -------
+ list[tuple[int, int]]
+ The (k, k2) corner index pairs, in CORNERS order of k, for which
+ both corners exist.
+ """
out = []
for k, (a, b) in enumerate(CORNERS):
a2, b2 = a + delta[0], b + delta[1]
@@ -94,13 +105,15 @@ def corner_pairs(delta):
return out
-def bilinear_corners(motion_r: float, motion_c: float, margin: int):
- """Offsets and coefficients of ``interp_frame``'s four neighbours.
+def bilinear_corners(
+ motion_r: float, motion_c: float, margin: int
+) -> tuple[int, int, np.ndarray, tuple[float, float]]:
+ """Offsets and coefficients of interp_frame's four neighbours.
- Output pixel ``(i, j)`` reads raw window pixels ``(i + off_r + a,
- j + off_c + b)`` for ``a, b`` in ``{0, 1}`` with coefficients in the
- order ``(0, 0), (0, 1), (1, 0), (1, 1)``, rounded to float32 as
- ``interp_frame`` rounds them.
+ Output pixel (i, j) reads raw window pixels (i + off_r + a,
+ j + off_c + b) for a, b in {0, 1} with coefficients in the
+ order (0, 0), (0, 1), (1, 0), (1, 1), rounded to float32 as
+ interp_frame rounds them.
Returns
-------
@@ -113,80 +126,93 @@ def bilinear_corners(motion_r: float, motion_c: float, margin: int):
first_c = 1 - margin + float(motion_c)
fr = first_r - math.floor(first_r)
fc = first_c - math.floor(first_c)
- coef = np.array(
- [
- float(np.float32(v))
- for v in (
- (1 - fc) * (1 - fr),
- fc * (1 - fr),
- (1 - fc) * fr,
- fc * fr,
- )
- ]
- )
+ coef = np.array([
+ float(np.float32(v))
+ for v in (
+ (1 - fc) * (1 - fr),
+ fc * (1 - fr),
+ (1 - fc) * fr,
+ fc * fr,
+ )
+ ])
return math.floor(first_r) - 1, math.floor(first_c) - 1, coef, (fr, fc)
-def spatial_factor(frac) -> float:
- """Variance of a 2 x 2 sum of registered pixels relative to four times
- one pixel's, from the shared raw pixels of bilinear interpolation
- (equal raw pixels assumed): ``(1 + rho_r) (1 + rho_c)``."""
+def spatial_factor(frac: Sequence[float] | np.ndarray) -> float:
+ """Variance of a 2 x 2 sum of registered pixels relative to four times one pixel's.
+
+ From the shared raw pixels of bilinear interpolation (equal raw pixels
+ assumed): (1 + rho_r) (1 + rho_c).
+
+ Returns
+ -------
+ float
+ The relative variance of the 2 x 2 sum, (1 + rho_r) (1 + rho_c), for the
+ fractional shifts frac.
+ """
out = 1.0
for f in frac:
out *= 1.0 + f * (1 - f) / ((1 - f) ** 2 + f**2)
return out
-def pair_bin_factor(frac, shares: dict) -> float:
- """Consecutive-sample pairs inside a 2 x 2 sum of registered pixels,
- relative to four times one pixel's own single-sample variance (equal
- raw pixels assumed, as :func:`spatial_factor`).
+def pair_bin_factor(frac: Sequence[float] | np.ndarray, shares: dict) -> float:
+ """Consecutive-sample pairs inside a 2 x 2 sum of registered pixels.
+
+ Relative to four times one pixel's own single-sample variance (equal raw
+ pixels assumed, as :func:`spatial_factor`).
- Per axis with fractional shift ``f`` the sum's raw-pixel weights are
- ``(1 - f, 1, f)``: ``A = (1 - f)^2 + 1 + f^2`` along an axis the pair
- does not step on, ``1`` along one it steps on, against ``Q = (1 - f)^2
- + f^2`` for one pixel. With ``pi_d`` the share of samples whose next
- sample is in direction ``d``: ``sum_d pi_d S_d / (4 Q_r Q_c)``.
+ Per axis with fractional shift f the sum's raw-pixel weights are
+ (1 - f, 1, f): A = (1 - f)^2 + 1 + f^2 along an axis the pair
+ does not step on, 1 along one it steps on, against Q = (1 - f)^2
+ + f^2 for one pixel. With pi_d the share of samples whose next
+ sample is in direction d: sum_d pi_d S_d / (4 Q_r Q_c).
Parameters
----------
frac : (float, float)
The frame's fractional row and column shifts.
shares : dict
- ``{(dr, dc): pi_d}`` (:attr:`FrameGeometry.pair_share`).
+ {(dr, dc): pi_d} (:attr:`FrameGeometry.pair_share`).
+
+ Returns
+ -------
+ float
+ sum_d pi_d S_d / (4 Q_r Q_c): the variance of consecutive-sample pairs inside
+ the 2 x 2 sum relative to four times one pixel's single-sample variance.
"""
q = [(1 - f) ** 2 + f**2 for f in frac]
a = [(1 - f) ** 2 + 1 + f**2 for f in frac]
total = 0.0
for (dr, dc), share in shares.items():
- total += (
- share * (a[0] if dr == 0 else 1.0) * (a[1] if dc == 0 else 1.0)
- )
+ total += share * (a[0] if dr == 0 else 1.0) * (a[1] if dc == 0 else 1.0)
return total / (4 * q[0] * q[1])
-def _pair_products(w_first, w_partner, cmin, lag, n_first):
- """Kernel products of frames ``f`` and ``f + lag`` per line.
+def _pair_products(
+ w_first: np.ndarray, w_partner: np.ndarray, cmin: np.ndarray, lag: int, n_first: int
+) -> np.ndarray:
+ """Kernel products of frames f and f + lag per line.
Parameters
----------
- w_first : ndarray ``(n, P, k)``
+ w_first : ndarray (n, P, k)
Weights of each frame's k-th sample of each line (0 if out of reach
- or not in the displacement group), used for frame ``f``.
- w_partner : ndarray ``(n, P, k)``
- The same weights for frame ``f + lag`` (all samples in reach).
- cmin : ndarray ``(n, P)``
+ or not in the displacement group), used for frame f.
+ w_partner : ndarray (n, P, k)
+ The same weights for frame f + lag (all samples in reach).
+ cmin : ndarray (n, P)
Cycle of each frame's first (k = 0) sample of each line.
lag : int
Frame lag.
n_first : int
- Frames ``f`` (``f + lag`` must be below ``n``).
+ Frames f (f + lag must be below n).
Returns
-------
- ndarray ``(3, n_first, P, k)``
- ``w_f w_g``, ``w_f^2 w_g`` and ``w_f w_g^2`` at frame ``f``'s
- samples (``g = f + lag``).
+ ndarray (3, n_first, P, k)
+ w_f w_g, w_f^2 w_g and w_f w_g^2 at frame f's
+ samples (g = f + lag).
"""
n, _, k = w_first.shape
out = np.zeros((3, n_first) + w_first.shape[1:])
@@ -216,7 +242,7 @@ class FrameGeometry:
ds : array_like of int
One-based line times of the registered frames.
margin : int
- Padding of the registered grid (``maxshift``).
+ Padding of the registered grid (maxshift).
Attributes
----------
@@ -226,8 +252,16 @@ class FrameGeometry:
Registered frame shape.
"""
- def __init__(self, source, ds, margin: int):
- """Pixel tables of the window and the frames' kernel range."""
+ def __init__(
+ self, source: PlainFrames | CompensatedFrames, ds: npt.ArrayLike, margin: int
+ ) -> None:
+ """Pixel tables of the window and the frames' kernel range.
+
+ Raises
+ ------
+ ValueError
+ If the frames share samples over more lags than MAX_LAGS.
+ """
self.source = source
self.former = source.former
self.device = self.former.device
@@ -238,9 +272,7 @@ def __init__(self, source, ds, margin: int):
self.reach = max(3 * self.dt, lay.lines_per_cycle)
spacing = int(np.diff(self.ds).min()) if self.ds.size > 1 else 1
# no partners beyond the trial (a one-frame trial has none)
- self.n_lags = min(
- int((2 * self.reach) // max(1, spacing)), max(0, self.ds.size - 1)
- )
+ self.n_lags = min(int((2 * self.reach) // max(1, spacing)), max(0, self.ds.size - 1))
if self.n_lags > MAX_LAGS:
raise ValueError(
f"frames share samples over {self.n_lags} frames; the "
@@ -251,9 +283,7 @@ def __init__(self, source, ds, margin: int):
h, w = self.window.shape
self.out_shape = (h + 2 * self.margin, w + 2 * self.margin)
self.n_win = int(self.window.rows.numel())
- self.lookup = torch.full(
- (h * w,), self.n_win, dtype=torch.long, device=self.device
- )
+ self.lookup = torch.full((h * w,), self.n_win, dtype=torch.long, device=self.device)
flat = self.window.rows * w + self.window.cols
self.lookup[flat] = torch.arange(self.n_win, device=self.device)
pix = self.former._pix_flat
@@ -269,28 +299,34 @@ def __init__(self, source, ds, margin: int):
self._adjacent = {}
self.slot_dirs = self._slot_directions()
self.pair_share = self._pair_shares()
- self.directions = sorted(
- {tuple(int(v) for v in d) for d in self.slot_dirs[1].tolist()}
- )
+ self.directions = sorted({tuple(int(v) for v in d) for d in self.slot_dirs[1].tolist()})
self.tables = self._precompute()
# ------------------------------------------------------------ raw sums
- def _destinations(self, dr: int, dc: int):
- """Former pixels and their window-list positions at a displacement."""
+ def _destinations(self, dr: int, dc: int) -> tuple[torch.Tensor, torch.Tensor]:
+ """Former pixels and their window-list positions at a displacement.
+
+ Returns
+ -------
+ keep : torch.Tensor
+ The former pixels that land in the window at displacement (dr, dc).
+ dest : torch.Tensor
+ Each kept pixel's position in the window list.
+ """
if self.source.compensation is None:
keep = self.source.pixels
return keep, torch.arange(keep.numel(), device=self.device)
return self.source._destination(dr, dc)
- def _slot_directions(self):
+ def _slot_directions(self) -> tuple[np.ndarray, np.ndarray]:
"""Slots of the plane whose next sample is in a neighbouring pixel.
Returns
-------
slots : ndarray of int
Layout slot indices.
- dirs : ndarray of int ``(n, 2)``
+ dirs : ndarray of int (n, 2)
Row and column from the slot's pixel to the next sample's.
"""
from .gain import next_slots
@@ -300,37 +336,47 @@ def _slot_directions(self):
on_plane = lay.line_fast_z[lay.slot_line - 1] == 1
s = np.flatnonzero((nxt >= 0) & on_plane)
n = nxt[s]
- pr, pc = (lay.slot_pixel - 1) // lay.n_cols, (
- lay.slot_pixel - 1
- ) % lay.n_cols
+ pr, pc = (lay.slot_pixel - 1) // lay.n_cols, (lay.slot_pixel - 1) % lay.n_cols
d = np.stack([pr[n] - pr[s], pc[n] - pc[s]], 1)
near = (np.abs(d) <= 1).all(1) & (d != 0).any(1)
return s[near], d[near]
def _pair_shares(self) -> dict:
- """``{(dr, dc): share}``: the plane's samples whose next sample is
- in the neighbouring pixel ``(dr, dc)``, as a share of all of them."""
+ """{(dr, dc): share}: the plane's samples whose next sample is in pixel (dr, dc).
+
+ The samples whose next sample is in the neighbouring pixel
+ (dr, dc), as a share of all of them.
+
+ Returns
+ -------
+ dict
+ {(dr, dc): share}; empty when the plane has no such samples.
+ """
lay = self.former.layout
n = int((lay.line_fast_z[lay.slot_line - 1] == 1).sum())
dirs = self.slot_dirs[1]
if n == 0 or dirs.size == 0:
return {}
keys, counts = np.unique(dirs, axis=0, return_counts=True)
- return {
- (int(r), int(c)): float(k) / n for (r, c), k in zip(keys, counts)
- }
+ return {(int(r), int(c)): float(k) / n for (r, c), k in zip(keys, counts)}
+
+ def adjacency(self, dr: int, dc: int, delta: Sequence[int]) -> torch.Tensor:
+ """(P, n_win + 1) float32: slots on line l of the window pixel.
- def adjacency(self, dr: int, dc: int, delta) -> torch.Tensor:
- """``(P, n_win + 1)`` float32: slots on line ``l`` of the window
- pixel whose next sample is at ``pixel + delta`` (displacement
- ``(dr, dc)``)."""
+ Those whose next sample is at pixel + delta (displacement
+ (dr, dc)).
+
+ Returns
+ -------
+ torch.Tensor
+ The (P, n_win + 1) float32 count of such slots per line and window pixel
+ (cached per (dr, dc, delta)).
+ """
key = (int(dr), int(dc), tuple(delta))
if key not in self._adjacent:
lay = self.former.layout
p = lay.lines_per_cycle
- m = torch.zeros(
- (p, self.n_win + 1), dtype=torch.float32, device=self.device
- )
+ m = torch.zeros((p, self.n_win + 1), dtype=torch.float32, device=self.device)
slots, dirs = self.slot_dirs
sel = slots[(dirs == np.asarray(delta)).all(1)]
keep, dest = self._destinations(dr, dc)
@@ -352,14 +398,20 @@ def adjacency(self, dr: int, dc: int, delta) -> torch.Tensor:
return self._adjacent[key]
def incidence(self, dr: int, dc: int) -> torch.Tensor:
- """``(P, n_win + 1)`` float32: line ``l`` has a slot of the window
- pixel (the last column, for raw pixels without samples, is 0)."""
+ """(P, n_win + 1) float32: line l has a slot of the window pixel.
+
+ The last column, for raw pixels without samples, is 0.
+
+ Returns
+ -------
+ torch.Tensor
+ The (P, n_win + 1) float32 count of slots per line and window pixel at
+ displacement (dr, dc) (cached per (dr, dc)).
+ """
key = (int(dr), int(dc))
if key not in self._incidence:
p = self.former.layout.lines_per_cycle
- m = torch.zeros(
- (p, self.n_win + 1), dtype=torch.float32, device=self.device
- )
+ m = torch.zeros((p, self.n_win + 1), dtype=torch.float32, device=self.device)
keep, dest = self._destinations(*key)
lines = self.pixel_lines[keep]
for j in range(lines.shape[1]):
@@ -372,17 +424,22 @@ def incidence(self, dr: int, dc: int) -> torch.Tensor:
self._incidence[key] = m
return self._incidence[key]
- def _groups(self, f0: int, f_ext: int, lines, ok):
- """``[((dr, dc), mask)]``: samples of each displacement."""
+ def _groups(
+ self, f0: int, f_ext: int, lines: np.ndarray, ok: np.ndarray
+ ) -> list[tuple[tuple[int, int], np.ndarray]]:
+ """[((dr, dc), mask)]: samples of each displacement.
+
+ Returns
+ -------
+ list[tuple[tuple[int, int], np.ndarray]]
+ Each displacement (dr, dc) present, with the mask of the valid samples at it
+ (a single (0, 0) group of ok without compensation references).
+ """
if self.refs is None:
return [((0, 0), ok)]
- dr, dc = line_shifts(
- self.source.compensation, lines, self.refs[f0:f_ext]
- )
+ dr, dc = line_shifts(self.source.compensation, lines, self.refs[f0:f_ext])
pairs = np.unique(np.stack([dr[ok], dc[ok]], 1), axis=0)
- return [
- ((int(r), int(c)), ok & (dr == r) & (dc == c)) for r, c in pairs
- ]
+ return [((int(r), int(c)), ok & (dr == r) & (dc == c)) for r, c in pairs]
def line_tables(self, f0: int, f1: int, f_ext: int) -> list:
"""Kernel sums per line, by displacement group.
@@ -392,14 +449,14 @@ def line_tables(self, f0: int, f1: int, f_ext: int) -> list:
f0, f1 : int
Frames whose pair sums are wanted.
f_ext : int
- End of the frames read (partners ``f + l`` must be below it).
+ End of the frames read (partners f + l must be below it).
Returns
-------
list of ((dr, dc), single, pair)
- ``single``: ``(4, f_ext - f0, P)`` sample count, ``sum w``,
- ``sum w^2``, ``sum w^3``; ``pair``: ``(3 n_lags, f1 - f0, P)``
- ``H_l``, ``T_l``, ``U_l`` for ``l = 1 .. n_lags`` (lag-major).
+ single: (4, f_ext - f0, P) sample count, sum w,
+ sum w^2, sum w^3; pair: (3 n_lags, f1 - f0, P)
+ H_l, T_l, U_l for l = 1 .. n_lags (lag-major).
"""
local, w, lines, ok = self.former._tables(self.ds[f0:f_ext], self.dt)
cmin = local[:, :, 0]
@@ -407,9 +464,9 @@ def line_tables(self, f0: int, f1: int, f_ext: int) -> list:
out = []
for key, mask in self._groups(f0, f_ext, lines, ok):
wg = np.where(mask, w, 0.0)
- single = np.stack(
- [mask.sum(2), wg.sum(2), (wg**2).sum(2), (wg**3).sum(2)]
- ).astype(np.float64)
+ single = np.stack([mask.sum(2), wg.sum(2), (wg**2).sum(2), (wg**3).sum(2)]).astype(
+ np.float64
+ )
pair = np.zeros((3 * self.n_lags, n_first, w.shape[1]))
for lag in range(1, self.n_lags + 1):
# a shared sample is placed by the earlier frame's group
@@ -424,10 +481,10 @@ def _precompute(self) -> dict:
Returns
-------
dict
- ``(dr, dc) -> (rows, single, pair)``: ``rows`` ``(frames,)``
+ (dr, dc) -> (rows, single, pair): rows (frames,)
int64, each frame's row in the group's tables (-1 if the group
- has no samples of it); ``single`` ``(4, n_g, P)`` and ``pair``
- ``(3 n_lags, n_g, P)`` float32 (see :meth:`line_tables`).
+ has no samples of it); single (4, n_g, P) and pair
+ (3 n_lags, n_g, P) float32 (see :meth:`line_tables`).
"""
n = self.ds.size
parts = {}
@@ -437,30 +494,33 @@ def _precompute(self) -> dict:
for key, single, pair in self.line_tables(a, b, e):
has = single[0, : b - a].sum(1) > 0
frames = a + np.flatnonzero(has)
- parts.setdefault(key, []).append(
- (frames, single[:, : b - a][:, has], pair[:, has])
- )
+ parts.setdefault(key, []).append((frames, single[:, : b - a][:, has], pair[:, has]))
out = {}
for key, chunks in parts.items():
frames = np.concatenate([c[0] for c in chunks])
rows = np.full(n, -1, dtype=np.int64)
rows[frames] = np.arange(frames.size)
tabs = [
- torch.from_numpy(
- np.concatenate([c[i] for c in chunks], 1).astype(
- np.float32
- )
- ).to(self.device)
+ torch.from_numpy(np.concatenate([c[i] for c in chunks], 1).astype(np.float32)).to(
+ self.device
+ )
for i in (1, 2)
]
out[key] = (rows, tabs[0], tabs[1])
return out
def _raw(self, which: int, a: int, b: int) -> torch.Tensor:
- """Line tables of frames ``[a, b)`` summed over each window pixel's
- lines and the displacement groups: ``(quantities, b - a, n_win +
- 1)`` float32 (``which`` 1: single-frame sums, 2: pair sums), 0 in
- the last column."""
+ """Line tables of frames [a, b) summed over window pixels and displacement groups.
+
+ Summed over each window pixel's lines and the displacement groups:
+ (quantities, b - a, n_win + 1) float32 (which 1: single-frame
+ sums, 2: pair sums), 0 in the last column.
+
+ Returns
+ -------
+ torch.Tensor
+ The (quantities, b - a, n_win + 1) float32 sums.
+ """
total = None
for key, (rows, single, pair) in self.tables.items():
r = rows[a:b]
@@ -483,11 +543,19 @@ def _raw(self, which: int, a: int, b: int) -> torch.Tensor:
total = torch.zeros((q, b - a, self.n_win + 1), device=self.device)
return total
- def _images(self, key, t: torch.Tensor, which: int) -> torch.Tensor:
- """Line tables ``t`` ``(q, frames, P)`` on the window pixels; for the
- single sums also, per direction of :attr:`directions`, ``sum w^2``,
- ``sum w^3`` and the sample count over the slots whose next sample is
- in that direction (appended in that order)."""
+ def _images(self, key: tuple[int, int], t: torch.Tensor, which: int) -> torch.Tensor:
+ """Line tables t (q, frames, P) on the window pixels.
+
+ For the single sums also, per direction of :attr:`directions`,
+ sum w^2, sum w^3 and the sample count over the slots whose next
+ sample is in that direction (appended in that order).
+
+ Returns
+ -------
+ torch.Tensor
+ The tables on the window pixels, (q, frames, n_win + 1), with the
+ per-direction sums appended along the first axis for which == 1.
+ """
flat = t.reshape(-1, t.shape[-1])
m = self.incidence(*key)
imgs = [(flat @ m).reshape(t.shape[:2] + (m.shape[1],))]
@@ -495,40 +563,37 @@ def _images(self, key, t: torch.Tensor, which: int) -> torch.Tensor:
sub = t[[2, 3, 0]].reshape(-1, t.shape[-1])
for delta in self.directions:
ma = self.adjacency(key[0], key[1], delta)
- imgs.append(
- (sub @ ma).reshape((3,) + t.shape[1:2] + (m.shape[1],))
- )
+ imgs.append((sub @ ma).reshape((3,) + t.shape[1:2] + (m.shape[1],)))
return torch.cat(imgs) if len(imgs) > 1 else imgs[0]
# ----------------------------------------------------- registered sums
- def corners(self, motion: np.ndarray, present: np.ndarray):
- """Each frame's bilinear offsets, coefficients and fractions
- (:func:`bilinear_corners`, for many frames).
+ def corners(
+ self, motion: np.ndarray, present: np.ndarray
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Each frame's bilinear offsets, coefficients and fractions.
+
+ As :func:`bilinear_corners`, for many frames.
Parameters
----------
- motion : ndarray ``(n, 2)``
+ motion : ndarray (n, 2)
Row and column motion of the frames.
- present : ndarray of bool ``(n,)``
+ present : ndarray of bool (n,)
Frames with samples (others get zero coefficients).
Returns
-------
- off : ndarray of int64 ``(n, 2)``
- coef : ndarray of float64 ``(n, 4)``
- frac : ndarray of float64 ``(n, 2)``
+ off : ndarray of int64 (n, 2)
+ coef : ndarray of float64 (n, 4)
+ frac : ndarray of float64 (n, 2)
"""
present = np.asarray(present, dtype=bool)
- first = (1 - self.margin) + np.where(
- present[:, None], np.asarray(motion, np.float64), 0.0
- )
+ first = (1 - self.margin) + np.where(present[:, None], np.asarray(motion, np.float64), 0.0)
whole = np.floor(first)
frac = first - whole
fr, fc = frac[:, 0], frac[:, 1]
- coef = np.stack(
- [(1 - fc) * (1 - fr), fc * (1 - fr), (1 - fc) * fr, fc * fr], 1
- )
+ coef = np.stack([(1 - fc) * (1 - fr), fc * (1 - fr), (1 - fc) * fr, fc * fr], 1)
coef = coef.astype(np.float32).astype(np.float64)
off = (whole - 1).astype(np.int64)
coef[~present] = 0.0
@@ -536,9 +601,16 @@ def corners(self, motion: np.ndarray, present: np.ndarray):
frac[~present] = 0.0
return off, coef, frac
- def corner_index(self, out_idx: torch.Tensor, off: np.ndarray):
- """``(n, 4, n_idx)`` window-list index of each output pixel's raw
- neighbours (``n_win`` outside the window or where unsampled)."""
+ def corner_index(self, out_idx: torch.Tensor, off: np.ndarray) -> torch.Tensor:
+ """(n, 4, n_idx) window-list index of each output pixel's raw neighbours.
+
+ n_win outside the window or where unsampled.
+
+ Returns
+ -------
+ torch.Tensor
+ The (n, 4, n_idx) window-list indices of the four corners of each output pixel.
+ """
h, w = self.window.shape
big_w = self.out_shape[1]
rr = torch.div(out_idx, big_w, rounding_mode="floor")
@@ -553,15 +625,16 @@ def corner_index(self, out_idx: torch.Tensor, off: np.ndarray):
out.append(torch.where(inside, self.lookup[flat], self.n_win))
return torch.stack(out, 1)
- def pair_coefficients(self, off, coef, n_first) -> np.ndarray:
- """Products of the corner coefficients of frames ``t`` and ``t + l``
- at the raw pixels the two share.
+ def pair_coefficients(self, off: np.ndarray, coef: np.ndarray, n_first: int) -> np.ndarray:
+ """Products of the corner coefficients of frames t and t + l.
+
+ At the raw pixels the two share.
Returns
-------
- ndarray ``(3 n_lags, n_first, 4)``
- Lag-major ``c_t c_u``, ``c_t^2 c_u``, ``c_t c_u^2`` per corner
- of ``t`` (``u = t + l``; 0 past the frames given).
+ ndarray (3 n_lags, n_first, 4)
+ Lag-major c_t c_u, c_t^2 c_u, c_t c_u^2 per corner
+ of t (u = t + l; 0 past the frames given).
"""
n = off.shape[0]
out = np.zeros((3 * self.n_lags, n_first, 4))
@@ -582,15 +655,17 @@ def pair_coefficients(self, off, coef, n_first) -> np.ndarray:
out[q + 2, :m] = ct * cu * cu
return out
- def _norms(self, single, cidx, coef, varfac) -> dict:
+ def _norms(
+ self, single: torch.Tensor, cidx: torch.Tensor, coef: np.ndarray, varfac: torch.Tensor
+ ) -> dict:
"""Per-frame normalisers and single-frame sums at output pixels.
Returns
-------
- dict of torch.Tensor ``(n, n_idx)`` float32
- ``n0``, ``d_g`` (all-valid ``D``), ``q2`` and ``q3`` (the summed
- powers), ``n2 = sqrt(d_g d_a)``, ``n3 = (d_g d_a^2)^(1/3)``
- (``d_a = 1 / varFacDS``) and ``ok``.
+ dict of torch.Tensor (n, n_idx) float32
+ n0, d_g (all-valid D), q2 and q3 (the summed
+ powers), n2 = sqrt(d_g d_a), n3 = (d_g d_a^2)^(1/3)
+ (d_a = 1 / varFacDS) and ok.
"""
c = torch.from_numpy(coef.astype(np.float32)).to(self.device)
acc = [0.0, 0.0, 0.0, 0.0]
@@ -598,9 +673,7 @@ def _norms(self, single, cidx, coef, varfac) -> dict:
for k in range(4):
pairs, rows = self._corner_rows(k)
sub = single.index_select(0, rows)
- g = torch.gather(
- sub, 2, cidx[:, k][None].expand(len(rows), -1, -1)
- )
+ g = torch.gather(sub, 2, cidx[:, k][None].expand(len(rows), -1, -1))
ck = c[:, k : k + 1]
pw = ((ck > 0).float(), ck, ck * ck, ck * ck * ck)
for j in range(4):
@@ -613,19 +686,19 @@ def _norms(self, single, cidx, coef, varfac) -> dict:
n2 = torch.where(ok, torch.sqrt(d_g * d_a), zero)
n3 = torch.where(ok, (d_g * d_a * d_a) ** (1.0 / 3), zero)
qa2, qa3a, qa3b, m0 = (a + zero for a in adj)
- return dict(
- n0=n0, d_g=d_g, q2=q2, q3=q3, n2=n2, n3=n3, ok=ok,
- qa2=qa2, qa3a=qa3a, qa3b=qa3b, m0=m0,
- ) # fmt: skip
+ return {
+ "n0": n0, "d_g": d_g, "q2": q2, "q3": q3, "n2": n2, "n3": n3, "ok": ok,
+ "qa2": qa2, "qa3a": qa3a, "qa3b": qa3b, "m0": m0,
+ } # fmt: skip
- def _corner_rows(self, k: int):
- """Corner ``k``'s partners and the rows of the single sums it needs.
+ def _corner_rows(self, k: int) -> tuple[list[int], torch.Tensor]:
+ """Corner k's partners and the rows of the single sums it needs.
Returns
-------
pairs : list of int
- Partner corner ``k2 = k + delta`` for each direction (of
- :attr:`directions`, in order) in which ``k`` is the first
+ Partner corner k2 = k + delta for each direction (of
+ :attr:`directions`, in order) in which k is the first
sample's corner.
rows : torch.Tensor of int64
The four own sums, then the three pair sums of each of those
@@ -644,11 +717,14 @@ def _corner_rows(self, k: int):
self._rows[k] = (pairs, rows)
return self._rows[k]
- def _adjacent_terms(self, adj: list, g, c, k: int, pairs) -> None:
- """Add corner ``k``'s pairs of consecutive samples to ``adj``
- (``sum c c' w^2``, ``sum c^2 c' w^3``, ``sum c c'^2 w^3``, pair
- counts), from its gathered sums ``g`` (rows of
- :meth:`_corner_rows`)."""
+ def _adjacent_terms(
+ self, adj: list, g: torch.Tensor, c: torch.Tensor, k: int, pairs: list[int]
+ ) -> None:
+ """Add corner k's pairs of consecutive samples to adj.
+
+ sum c c' w^2, sum c^2 c' w^3, sum c c'^2 w^3, pair counts,
+ from its gathered sums g (rows of :meth:`_corner_rows`).
+ """
c1 = c[:, k : k + 1]
for j, k2 in enumerate(pairs):
c2 = c[:, k2 : k2 + 1]
@@ -659,26 +735,35 @@ def _adjacent_terms(self, adj: list, g, c, k: int, pairs) -> None:
both = ((c1 > 0) & (c2 > 0)).float()
adj[3] = adj[3] + both * cnt
- def registered(self, f0, f1, f_ext, out_idx, motion, present, varfac):
- """Photon-noise sums of frames ``[f0, f1)`` at output pixels.
+ def registered(
+ self,
+ f0: int,
+ f1: int,
+ f_ext: int,
+ out_idx: torch.Tensor,
+ motion: np.ndarray,
+ present: np.ndarray,
+ varfac: torch.Tensor,
+ ) -> dict[str, torch.Tensor]:
+ """Photon-noise sums of frames [f0, f1) at output pixels.
Parameters
----------
f0, f1, f_ext : int
Frames wanted, and the end of the frames given (partners).
- out_idx : torch.Tensor of int64 ``(n_idx,)``
+ out_idx : torch.Tensor of int64 (n_idx,)
Flat indices into the registered grid.
- motion : ndarray ``(f_ext - f0, 2)``
- present : ndarray of bool ``(f_ext - f0,)``
- varfac : torch.Tensor ``(f_ext - f0, n_idx)``
- ``varFacDS`` at the output pixels (NaN where undefined).
+ motion : ndarray (f_ext - f0, 2)
+ present : ndarray of bool (f_ext - f0,)
+ varfac : torch.Tensor (f_ext - f0, n_idx)
+ varFacDS at the output pixels (NaN where undefined).
Returns
-------
dict of torch.Tensor (float32)
- ``G`` ``(1 + n_lags, n, n_idx)``, ``R0`` ``(n, n_idx)``, ``R``
- and ``Rp`` ``(n_lags, n, n_idx)``, ``N0``, ``QA2``, ``QA3a``,
- ``QA3b`` and ``M0`` ``(n, n_idx)``, with ``n = f1 - f0``; 0
+ G (1 + n_lags, n, n_idx), R0 (n, n_idx), R
+ and Rp (n_lags, n, n_idx), N0, QA2, QA3a,
+ QA3b and M0 (n, n_idx), with n = f1 - f0; 0
where a frame has no defined value.
"""
n = f1 - f0
@@ -712,10 +797,26 @@ def registered(self, f0, f1, f_ext, out_idx, motion, present, varfac):
out["Rp"] = pairs[2::3]
return out
- def _pair_part(self, f0: int, cidx, cc, nrm, a: int, b: int):
- """``A2``, ``A3(t, t, u)``, ``A3(t, u, u)`` of frames ``[a, b)``
- (relative to the chunk starting at frame ``f0``) with ``u = t + l``:
- ``(3 n_lags, b - a, n_idx)`` lag-major."""
+ def _pair_part(
+ self,
+ f0: int,
+ cidx: torch.Tensor,
+ cc: torch.Tensor,
+ nrm: dict[str, torch.Tensor],
+ a: int,
+ b: int,
+ ) -> torch.Tensor:
+ """A2, A3(t, t, u), A3(t, u, u) of frames [a, b).
+
+ Relative to the chunk starting at frame f0, with u = t + l:
+ (3 n_lags, b - a, n_idx) lag-major.
+
+ Returns
+ -------
+ torch.Tensor
+ The (3 n_lags, b - a, n_idx) lag-major normalised A2, A3(t, t, u) and
+ A3(t, u, u) sums of frames [a, b); 0 where either frame is invalid.
+ """
raw = self._raw(2, f0 + a, f0 + b)
lag3 = raw.shape[0]
acc = None
@@ -731,8 +832,6 @@ def _pair_part(self, f0: int, cidx, cc, nrm, a: int, b: int):
both = ok[a:b][None] & ok[uc] & (u < m)[:, :, None]
n2a, n3a = n2[a:b][None], n3[a:b][None]
n2u, n3u = n2[uc], n3[uc]
- den = torch.stack(
- [n2a * n2u, n3a * n3a * n3u, n3a * n3u * n3u], 1
- ).reshape(acc.shape)
+ den = torch.stack([n2a * n2u, n3a * n3a * n3u, n3a * n3u * n3u], 1).reshape(acc.shape)
mask = both.repeat_interleave(3, 0)
return torch.where(mask, acc / den, torch.zeros_like(acc))
diff --git a/src/giant_python/registration/stats/io.py b/src/giant_python/registration/stats/io.py
index 4770e228..ef458047 100644
--- a/src/giant_python/registration/stats/io.py
+++ b/src/giant_python/registration/stats/io.py
@@ -1,10 +1,10 @@
-"""The statistics file of a registered trial (``_REGSTATS-80Hz.h5``).
+"""The statistics file of a registered trial (_REGSTATS-80Hz.h5).
A sidecar next to the registered movie, so that no reader of the movie or
the alignment file changes. Arrays are stored in GIAnT's MATLAB layout, as
-the movie is: a map that is ``(channels, rows, cols)`` in Python is the
-HDF5 dataset ``(channels, cols, rows)``, which MATLAB's ``h5read`` returns
-as ``rows x cols x channels``. :func:`read_stats` returns Python's
+the movie is: a map that is (channels, rows, cols) in Python is the
+HDF5 dataset (channels, cols, rows), which MATLAB's h5read returns
+as rows x cols x channels. :func:`read_stats` returns Python's
orientation.
"""
@@ -14,10 +14,10 @@
import json
from datetime import datetime
from pathlib import Path
-from typing import Union
import h5py
import numpy as np
+from numpy.typing import ArrayLike
STATS_VERSION = 1
"""Version of the statistics' definitions and file layout."""
@@ -33,12 +33,17 @@
_REGISTERED = "_REGISTERED_DOWNSAMPLED-"
-def stats_path(movie_path: Union[str, Path]) -> Path:
- """The statistics file of a registered movie.
+def stats_path(movie_path: str | Path) -> Path:
+ """Return the statistics file of a registered movie.
- ``_REGISTERED_DOWNSAMPLED-80Hz.h5`` (or ``.tif``) gives
- ``_REGSTATS-80Hz.h5`` in the same folder; any other name
- ``_REGSTATS.h5``.
+ _REGISTERED_DOWNSAMPLED-80Hz.h5 (or .tif) gives
+ _REGSTATS-80Hz.h5 in the same folder; any other name
+ _REGSTATS.h5.
+
+ Returns
+ -------
+ Path
+ The statistics file's path, in the same folder as the movie.
"""
p = Path(movie_path)
if _REGISTERED in p.name:
@@ -48,9 +53,16 @@ def stats_path(movie_path: Union[str, Path]) -> Path:
return p.with_name(f"{p.stem}_REGSTATS.h5")
-def alignment_digest(ds_frames, motion_r, motion_c) -> str:
- """SHA-256 of the frame times and motion (float64), which identify the
- registration the statistics were made from."""
+def alignment_digest(ds_frames: ArrayLike, motion_r: ArrayLike, motion_c: ArrayLike) -> str:
+ """SHA-256 of the frame times and motion (float64).
+
+ These identify the registration the statistics were made from.
+
+ Returns
+ -------
+ str
+ Hex digest of the SHA-256 hash.
+ """
h = hashlib.sha256()
for a in (ds_frames, motion_r, motion_c):
h.update(np.ascontiguousarray(a, dtype=np.float64).ravel().tobytes())
@@ -58,7 +70,13 @@ def alignment_digest(ds_frames, motion_r, motion_c) -> str:
def _to_file(a: np.ndarray) -> np.ndarray:
- """Python ``(..., rows, cols)`` to the file's ``(..., cols, rows)``."""
+ """Python (..., rows, cols) to the file's (..., cols, rows).
+
+ Returns
+ -------
+ np.ndarray
+ a with its last two axes swapped, as a contiguous array.
+ """
return np.ascontiguousarray(np.swapaxes(a, -1, -2))
@@ -67,11 +85,11 @@ def _dataset(grp: h5py.Group, name: str, data: np.ndarray) -> None:
data = np.asarray(data)
opts = {}
if data.size >= 4096:
- opts = dict(compression="gzip", compression_opts=1, shuffle=True)
+ opts = {"compression": "gzip", "compression_opts": 1, "shuffle": True}
grp.create_dataset(name, data=data, **opts)
-def write_stats(path: Union[str, Path], result: dict, attrs: dict) -> None:
+def write_stats(path: str | Path, result: dict, attrs: dict) -> None:
"""Write a trial's statistics.
Parameters
@@ -103,8 +121,15 @@ def write_stats(path: Union[str, Path], result: dict, attrs: dict) -> None:
_dataset(g, k, np.asarray(v))
-def _attr(v):
- """A file attribute as a Python value (JSON decoded where it is)."""
+def _attr(v: object) -> object:
+ """Convert a file attribute to a Python value (JSON decoded where it is).
+
+ Returns
+ -------
+ object
+ The attribute as a Python value: bytes decoded, JSON-encoded lists and dicts parsed,
+ numpy scalars converted.
+ """
if isinstance(v, bytes):
v = v.decode()
if isinstance(v, str) and v[:1] in "[{":
@@ -117,14 +142,14 @@ def _attr(v):
return v
-def read_stats(path: Union[str, Path]) -> dict:
- """A statistics file, with maps as ``(channels, rows, cols)``.
+def read_stats(path: str | Path) -> dict:
+ """Read a statistics file, with maps as (channels, rows, cols).
Returns
-------
dict
- ``attrs``, ``maps``, ``svd`` (weights ``(channels, components,
- rows, cols)``) and ``gain``.
+ attrs, maps, svd (weights (channels, components,
+ rows, cols)) and gain.
"""
out = {"maps": {}, "svd": {}, "gain": {}}
with h5py.File(path, "r") as f:
diff --git a/src/giant_python/registration/stats/maps.py b/src/giant_python/registration/stats/maps.py
index a0b857b8..f49d8740 100644
--- a/src/giant_python/registration/stats/maps.py
+++ b/src/giant_python/registration/stats/maps.py
@@ -1,29 +1,34 @@
"""The statistic maps of a trial, from the accumulated per-pixel sums.
-Every map is per channel, ``(channels, rows, cols)`` float32 on the
+Every map is per channel, (channels, rows, cols) float32 on the
registered grid, NaN where a pixel has too few valid frames. For each
-second moment ``m`` the file holds the moment; ``m_q`` and ``m_qa``, its
-photon-noise expectation per unit of ``g2 mu`` from the samples
-themselves and per unit of ``2 c2 mu`` from pairs of consecutive samples
-(properties of frame formation and registration only); ``m_ph = mu (g2
-m_q + 2 c2 m_qa)``; and a normalised map that is 0 under photon noise. The
-fast third moment likewise has ``fast_q3``, ``fast_q3a`` and ``fast_q3b``
-(per unit of ``g3 mu``, ``3 c3a mu``, ``3 c3b mu``). See
-``docs/source/reg_stats.rst`` for the definitions.
+second moment m the file holds the moment; m_q and m_qa, its
+photon-noise expectation per unit of g2 mu from the samples
+themselves and per unit of 2 c2 mu from pairs of consecutive samples
+(properties of frame formation and registration only); m_ph = mu (g2
+m_q + 2 c2 m_qa); and a normalised map that is 0 under photon noise. The
+fast third moment likewise has fast_q3, fast_q3a and fast_q3b
+(per unit of g3 mu, 3 c3a mu, 3 c3b mu). See
+docs/source/reg_stats.rst for the definitions.
For two frames that share samples, the pair terms are those of the frames'
-own sums scaled by the pixel's ratio ``r = sum_t QA2(t) / sum_t A2(t, t)``
+own sums scaled by the pixel's ratio r = sum_t QA2(t) / sum_t A2(t, t)
(the pairs lie on the same lines as the pixel's samples, so their kernel
overlap between frames is that of the samples).
"""
from __future__ import annotations
+from typing import TYPE_CHECKING
+
import numpy as np
import torch
from .svd import shared_modes
+if TYPE_CHECKING:
+ from .accumulate import TrialStatsAccumulator
+
ZERO_NU = np.geomspace(1e-4, 2.0, 33)
"""Non-zero rates per sample at which the photon-noise share of zeros is
accumulated (interpolated between them at each pixel's rate)."""
@@ -41,30 +46,54 @@
def _np(t: torch.Tensor) -> np.ndarray:
- """A tensor as a float64 NumPy array."""
+ """Convert a tensor to a float64 NumPy array.
+
+ Returns
+ -------
+ np.ndarray
+ The detached CPU values of t as float64.
+ """
return t.detach().double().cpu().numpy()
-def _ratio(num, den, ok):
- """``num / den`` where ``ok`` and ``den > 0``, else NaN."""
+def _ratio(num: np.ndarray, den: np.ndarray, ok: np.ndarray) -> np.ndarray:
+ """``num / den`` where ok and den > 0, else NaN.
+
+ Returns
+ -------
+ np.ndarray
+ The elementwise ratio, NaN where ok is false or den is not positive.
+ """
with np.errstate(invalid="ignore", divide="ignore"):
return np.where(ok & (den > 0), num / den, np.nan)
def _pair_ratio(a: dict) -> np.ndarray:
- """``r``: the pixel's pair sums relative to its own sums."""
+ """r: the pixel's pair sums relative to its own sums.
+
+ Returns
+ -------
+ np.ndarray
+ sq / s0 per pixel, 0 where s0 is not positive.
+ """
with np.errstate(invalid="ignore", divide="ignore"):
return np.where(a["s0"] > 0, a["sq"] / a["s0"], 0.0)
-def single_frame_maps(a: dict, mu, g: dict) -> dict:
+def single_frame_maps(a: dict, mu: np.ndarray, g: dict) -> dict:
"""Mean-related maps: valid frames, variance, share of zeros.
- ``var = mean(x^2) - mean(x)^2`` over a pixel's valid frames, and its
- photon-noise expectation ``var_q = S0 / n - (S0 + 2 S1) / n^2`` with
- ``S0 = sum_t A2(t, t)`` and ``S1 = sum_t sum_l A2(t, t + l)`` over pairs
+ var = mean(x^2) - mean(x)^2 over a pixel's valid frames, and its
+ photon-noise expectation var_q = S0 / n - (S0 + 2 S1) / n^2 with
+ S0 = sum_t A2(t, t) and S1 = sum_t sum_l A2(t, t + l) over pairs
of valid frames (the second term is the variance of the mean);
- ``var_qa`` likewise from ``SQ = sum_t QA2(t)`` and ``r S1``.
+ var_qa likewise from SQ = sum_t QA2(t) and r S1.
+
+ Returns
+ -------
+ dict
+ Maps var, var_q, var_qa, var_ph (photon-noise variance), var_rel
+ (var / var_ph - 1) and zero_share (share of exactly zero frames).
"""
n = a["n"]
ok = n >= MIN_FRAMES
@@ -72,12 +101,8 @@ def single_frame_maps(a: dict, mu, g: dict) -> dict:
r = _pair_ratio(a)
mean = a["sx"] / nn
var = np.where(ok, a["sx2"] / nn - mean**2, np.nan)
- var_q = np.where(
- ok, a["s0"] / nn - (a["s0"] + 2 * a["s1"]) / nn**2, np.nan
- )
- var_qa = np.where(
- ok, a["sq"] / nn - (a["sq"] + 2 * r * a["s1"]) / nn**2, np.nan
- )
+ var_q = np.where(ok, a["s0"] / nn - (a["s0"] + 2 * a["s1"]) / nn**2, np.nan)
+ var_qa = np.where(ok, a["sq"] / nn - (a["sq"] + 2 * r * a["s1"]) / nn**2, np.nan)
var_ph = mu * (g["g2"] * var_q + 2 * g["c2"] * var_qa)
return {
"var": var,
@@ -89,14 +114,20 @@ def single_frame_maps(a: dict, mu, g: dict) -> dict:
}
-def slow_maps(a: dict, mu, g: dict) -> dict:
+def slow_maps(a: dict, mu: np.ndarray, g: dict) -> dict:
"""Variance of 64-frame block means and its photon-noise expectation.
- ``slow_var = sum_j (B_j - mean B)^2 / (J - 1)`` over the pixel's ``J``
- valid blocks; ``slow_q = (sum_j V_j - (sum_j V_j + 2 sum_j C_j) / J) /
- (J - 1)`` with ``V_j`` the photon variance of block mean ``j`` and
- ``C_j`` its covariance with the previous block's mean (kernel overlap);
- ``slow_qa`` likewise with the pair terms.
+ slow_var = sum_j (B_j - mean B)^2 / (J - 1) over the pixel's J
+ valid blocks; slow_q = (sum_j V_j - (sum_j V_j + 2 sum_j C_j) / J) /
+ (J - 1) with V_j the photon variance of block mean j and
+ C_j its covariance with the previous block's mean (kernel overlap);
+ slow_qa likewise with the pair terms.
+
+ Returns
+ -------
+ dict
+ Maps n_blocks, slow_var, slow_q, slow_qa, slow_var_ph (photon-noise
+ variance) and slow_rel (slow_var / slow_var_ph - 1).
"""
nb = a["nb"]
ok = nb >= MIN_BLOCKS
@@ -104,8 +135,14 @@ def slow_maps(a: dict, mu, g: dict) -> dict:
r = _pair_ratio(a)
var = np.where(ok, (a["sb2"] - a["sb"] ** 2 / jj) / (jj - 1), np.nan)
- def expect(vb, cb):
- """Expectation of the block-mean variance from its sums."""
+ def expect(vb: np.ndarray, cb: np.ndarray) -> np.ndarray:
+ """Compute the expectation of the block-mean variance from its sums.
+
+ Returns
+ -------
+ np.ndarray
+ The expectation per pixel, NaN where too few valid blocks.
+ """
return np.where(ok, (vb - (vb + 2 * cb) / jj) / (jj - 1), np.nan)
q = expect(a["vb"], a["cb"])
@@ -121,9 +158,18 @@ def expect(vb, cb):
}
-def fast_maps(a: dict, mu, g: dict) -> dict:
- """Second and third central moments of the fast part and their
- photon-noise expectations (means over the pixel's centres)."""
+def fast_maps(a: dict, mu: np.ndarray, g: dict) -> dict:
+ """Second and third central moments of the fast part and their photon-noise expectations.
+
+ Means over the pixel's centres.
+
+ Returns
+ -------
+ dict
+ Maps n_fast, fast_var, fast_q, fast_qa, fast_var_ph, fast_rel,
+ fast_m3, fast_q3, fast_q3a, fast_q3b, fast_m3_ph and
+ fast_skew_rel (third-moment excess over photon noise, in photon-noise SD units).
+ """
nf = a["nf"]
ok = nf >= MIN_FRAMES
nn = np.maximum(nf, 1)
@@ -132,14 +178,10 @@ def fast_maps(a: dict, mu, g: dict) -> dict:
m2 = a["sz2"] / nn
var = np.where(ok, m2 - m1**2, np.nan)
m3 = np.where(ok, a["sz3"] / nn - 3 * m1 * m2 + 2 * m1**3, np.nan)
- q = {
- k: np.where(ok, a[k] / nn, np.nan) for k in ("q2", "q3", "q3a", "q3b")
- }
+ q = {k: np.where(ok, a[k] / nn, np.nan) for k in ("q2", "q3", "q3a", "q3b")}
qa = np.where(ok, (a["qa"] + r * a["q2l"]) / nn, np.nan)
ph2 = mu * (g["g2"] * q["q2"] + 2 * g["c2"] * qa)
- ph3 = mu * (
- g["g3"] * q["q3"] + 3 * (g["c3a"] * q["q3a"] + g["c3b"] * q["q3b"])
- )
+ ph3 = mu * (g["g3"] * q["q3"] + 3 * (g["c3a"] * q["q3a"] + g["c3b"] * q["q3b"]))
with np.errstate(invalid="ignore", divide="ignore"):
skew = np.where(ok & (ph2 > 0), (m3 - ph3) / ph2**1.5, np.nan)
return {
@@ -158,17 +200,25 @@ def fast_maps(a: dict, mu, g: dict) -> dict:
}
-def zero_maps(grid: np.ndarray, n: np.ndarray, nu: np.ndarray, share):
+def zero_maps(
+ grid: np.ndarray, n: np.ndarray, nu: np.ndarray, share: np.ndarray
+) -> dict[str, np.ndarray]:
"""Photon-noise share of exact zeros.
A frame is exactly 0 when all of its contributing samples are
- (samples are non-negative). With ``N`` such samples, ``M`` of them in
- pairs of consecutive samples, a rate ``nu`` of non-zero events per
- sample and a share ``phi`` of a pair's events in both samples, that has
- probability ``exp(-nu (N - phi M))``; ``grid`` holds the sum of it over
+ (samples are non-negative). With N such samples, M of them in
+ pairs of consecutive samples, a rate nu of non-zero events per
+ sample and a share phi of a pair's events in both samples, that has
+ probability exp(-nu (N - phi M)); grid holds the sum of it over
the pixel's valid frames at the rates :data:`ZERO_NU`, and the
- expectation interpolates ``log(grid / n)`` linearly in ``nu`` (beyond
+ expectation interpolates log(grid / n) linearly in nu (beyond
the grid: the nearest interval's slope).
+
+ Returns
+ -------
+ dict of str to np.ndarray
+ zero_ph (photon-noise expectation of the share of exact zeros) and zero_excess
+ (share minus zero_ph).
"""
with np.errstate(divide="ignore", invalid="ignore"):
lg = np.log(np.maximum(grid, 1e-300) / np.maximum(n, 1)[..., None])
@@ -183,8 +233,14 @@ def zero_maps(grid: np.ndarray, n: np.ndarray, nu: np.ndarray, share):
return {"zero_ph": zph, "zero_excess": share - zph}
-def sigma8_map(a: dict, mu, g: dict) -> np.ndarray:
- """Photon SD of each pixel's 8-frame mean (mean over its valid bins)."""
+def sigma8_map(a: dict, mu: np.ndarray, g: dict) -> np.ndarray:
+ """Photon SD of each pixel's 8-frame mean (mean over its valid bins).
+
+ Returns
+ -------
+ np.ndarray
+ The photon-noise standard deviation per pixel, NaN where it has no valid bins.
+ """
r = _pair_ratio(a)
n8 = np.maximum(a["n8"], 1)
v = g["g2"] * a["v8"] + 2 * g["c2"] * (a["v8q"] + r * a["v8l"])
@@ -192,26 +248,33 @@ def sigma8_map(a: dict, mu, g: dict) -> np.ndarray:
return np.where(a["n8"] > 0, np.sqrt(mu * v / n8), np.nan)
-def bin_var8(a: dict, mu, g: dict, kappa: float, lam: float) -> np.ndarray:
- """Each pixel's share of the photon variance of a 2 x 2 sum of 8-frame
- means: ``mu v8 (g2 kappa + 2 c2 lam) / n8``, with ``kappa`` the
- trial's :func:`.geometry.spatial_factor` and ``lam`` its
+def bin_var8(a: dict, mu: np.ndarray, g: dict, kappa: float, lam: float) -> np.ndarray:
+ """Each pixel's share of the photon variance of a 2 x 2 sum of 8-frame means.
+
+ The share is mu v8 (g2 kappa + 2 c2 lam) / n8, with kappa the
+ trial's :func:`.geometry.spatial_factor` and lam its
:func:`.geometry.pair_bin_factor` (all pairs inside the sum, each
- pixel's own among them)."""
+ pixel's own among them).
+
+ Returns
+ -------
+ np.ndarray
+ The per-pixel variance share, NaN where the pixel has no valid bins.
+ """
n8 = np.maximum(a["n8"], 1)
v = a["v8"] * (g["g2"] * kappa + 2 * g["c2"] * lam)
with np.errstate(invalid="ignore"):
return np.where(a["n8"] > 0, mu * v / n8, np.nan)
-def finish_maps(o) -> dict:
+def finish_maps(o: TrialStatsAccumulator) -> dict:
"""All statistics of a finished accumulator.
Returns
-------
dict
- ``maps`` (name -> ``(channels, rows, cols)`` float32), ``svd``,
- ``gain`` (per channel curves) and ``attrs`` (scalars).
+ maps (name -> (channels, rows, cols) float32), svd,
+ gain (per channel curves) and attrs (scalars).
"""
h, w = o.shape
mean32 = o.sum32 / torch.clamp(o.count32, min=1)
@@ -222,18 +285,12 @@ def finish_maps(o) -> dict:
at = [cv.at(mu[ch]) for ch, cv in enumerate(o.gains)]
g = {k: np.stack([x[k] for x in at]) for k in at[0]}
compact = {"n_valid": a["n"]}
- compact.update(
- {f"gain_{k}": g[k] for k in ("g2", "g3", "c2", "c3a", "c3b")}
- )
+ compact.update({f"gain_{k}": g[k] for k in ("g2", "g3", "c2", "c3a", "c3b")})
compact.update(single_frame_maps(a, mu, g))
compact.update(slow_maps(a, mu, g))
compact.update(fast_maps(a, mu, g))
n_idx = idx.size
- grid = (
- _np(o.hist[:, :n_idx])
- if o.hist is not None
- else np.ones(mu.shape + (ZERO_NU.size,))
- )
+ grid = _np(o.hist[:, :n_idx]) if o.hist is not None else np.ones(mu.shape + (ZERO_NU.size,))
compact.update(zero_maps(grid, a["n"], g["nu"], compact["zero_share"]))
compact["sigma8_ph"] = sigma8_map(a, mu, g)
kappa = o.kappa[0] / o.kappa[1] if o.kappa[1] else float("nan")
@@ -241,8 +298,14 @@ def finish_maps(o) -> dict:
var8 = bin_var8(a, mu, g, kappa, lam)
svd = shared_modes(o.bins, idx, (h, w), compact["sigma8_ph"], var8)
- def dense(v):
- """Compact ``(channels, n_idx)`` values on the registered grid."""
+ def dense(v: np.ndarray) -> np.ndarray:
+ """Compact (channels, n_idx) values on the registered grid.
+
+ Returns
+ -------
+ np.ndarray
+ Float32 (channels, rows, cols) array, NaN outside the indexed pixels.
+ """
out = np.full((o.c, h * w), np.nan, dtype=np.float32)
out[:, idx] = v
return out.reshape(o.c, h, w)
@@ -250,9 +313,7 @@ def dense(v):
maps = {"mean": mean32.cpu().numpy().astype(np.float32)}
maps.update({k: dense(v) for k, v in compact.items()})
for key in ("weight", "weight_ph"):
- svd[key] = np.stack(
- [dense(svd[key][:, :, j]) for j in range(svd[key].shape[2])], 1
- )
+ svd[key] = np.stack([dense(svd[key][:, :, j]) for j in range(svd[key].shape[2])], 1)
attrs = {
"n_frames": o.n_frames,
"n_lags": o.n_lags,
@@ -268,7 +329,13 @@ def dense(v):
def _stack_curves(curves: list) -> np.ndarray:
- """Per-channel curves of possibly different lengths, NaN-padded."""
+ """Per-channel curves of possibly different lengths, NaN-padded.
+
+ Returns
+ -------
+ np.ndarray
+ (channels, longest curve length) array, one NaN-padded curve per row.
+ """
k = max((c.size for c in curves), default=0)
out = np.full((len(curves), k), np.nan)
for i, c in enumerate(curves):
diff --git a/src/giant_python/registration/stats/session.py b/src/giant_python/registration/stats/session.py
index 2d932688..87b1a3d0 100644
--- a/src/giant_python/registration/stats/session.py
+++ b/src/giant_python/registration/stats/session.py
@@ -4,27 +4,32 @@
template made from its own frames, so the same tissue lies at different
(sub-pixel) positions in different trials. Registration therefore writes
per-trial maps only. SILo's plan stage measures each trial's map from a
-consensus frame to its registered frame (``extraction.raster.alignment.
-TrialWarp``, a rigid shift by default); given it, :func:`combine_trials`
+consensus frame to its registered frame (extraction.raster.alignment.
+TrialWarp, a rigid shift by default); given it, :func:`combine_trials`
resamples every trial's maps into the consensus frame (bilinear, NaN next to
-NaN, as ``warp_trial_image``) and averages them, each map weighted by the
+NaN, as warp_trial_image) and averages them, each map weighted by the
frames behind it at the pixel:
-* single-frame maps and the share of zeros by ``n_valid``;
-* slow maps by ``n_blocks``; fast maps by ``n_fast``;
-* the gains and ``sigma8_ph`` by ``n_valid``.
+* single-frame maps and the share of zeros by n_valid;
+* slow maps by n_blocks; fast maps by n_fast;
+* the gains and sigma8_ph by n_valid.
Raw moments and their photon-noise expectations are averaged; the
-normalised maps are then formed from the averages (``var_rel = var /
-var_ph - 1`` and so on), not averaged themselves. Variances stay about each
+normalised maps are then formed from the averages (var_rel = var /
+var_ph - 1 and so on), not averaged themselves. Variances stay about each
trial's own mean (differences between trials' means do not enter). The
shared modes (SVD) are per trial and are not combined.
"""
from __future__ import annotations
+from typing import TYPE_CHECKING
+
import numpy as np
+if TYPE_CHECKING:
+ from ...extraction.raster.alignment import TrialWarp
+
WEIGHTS = {
"n_valid": (
"mean", "var", "var_q", "var_qa", "var_ph", "zero_share", "zero_ph",
@@ -51,8 +56,15 @@
def _normalised(m: dict) -> dict:
- """The normalised maps from averaged moments and expectations (those
- whose inputs are there)."""
+ """Form the normalised maps from averaged moments and expectations.
+
+ Only those whose inputs are there.
+
+ Returns
+ -------
+ dict
+ The normalised maps (see NORMALISED) whose inputs are all in m, by name.
+ """
out = {}
with np.errstate(invalid="ignore", divide="ignore"):
for name, (inputs, fn) in NORMALISED.items():
@@ -62,28 +74,39 @@ def _normalised(m: dict) -> dict:
def _resample(
- img: np.ndarray, warp, trial: int, shape, coords=None
+ img: np.ndarray,
+ warp: TrialWarp,
+ trial: int,
+ shape: tuple[int, int],
+ coords: tuple[np.ndarray, np.ndarray] | None = None,
) -> np.ndarray:
- """A trial's ``(channels, rows, cols)`` map in the consensus frame,
- placed at the top left of the ``shape`` canvas first (NaN elsewhere),
- as SILo places trials of different sizes. ``coords``: the map's
- positions of the canvas (``warp.grid_coords(trial, shape)``), computed
- once per trial by the caller (a patchwise field costs a blend over the
- patch centres per pixel)."""
+ """Resample a trial's (channels, rows, cols) map in the consensus frame.
+
+ The map is placed at the top left of the shape canvas first (NaN
+ elsewhere), as SILo places trials of different sizes. coords: the
+ map's positions of the canvas (warp.grid_coords(trial, shape)),
+ computed once per trial by the caller (a patchwise field costs a blend
+ over the patch centres per pixel).
+
+ Returns
+ -------
+ np.ndarray
+ The resampled map, (channels, rows, cols), in the consensus frame.
+ """
from ...extraction.raster.alignment import warp_trial_image
canvas = np.full((img.shape[0],) + tuple(shape), np.nan)
canvas[:, : img.shape[1], : img.shape[2]] = img
return np.moveaxis(
- warp_trial_image(
- np.moveaxis(canvas, 0, -1), warp, trial, coords=coords
- ),
+ warp_trial_image(np.moveaxis(canvas, 0, -1), warp, trial, coords=coords),
-1,
0,
)
-def combine_trials(stats: list, warp=None, shifts=None) -> dict:
+def combine_trials(
+ stats: list, warp: TrialWarp | None = None, shifts: np.ndarray | None = None
+) -> dict:
"""Session maps of one imaging path.
Parameters
@@ -93,40 +116,35 @@ def combine_trials(stats: list, warp=None, shifts=None) -> dict:
trial order; None for a trial without statistics.
warp : TrialWarp, optional
SILo's map from the consensus frame to each trial's registered
- frame (``ExtractionPlan.warp``). Trials it did not align are left
+ frame (ExtractionPlan.warp). Trials it did not align are left
out.
- shifts : array_like ``(trials, 2)``, optional
- Instead of ``warp``: rigid shifts (consensus pixel ``(r, c)`` is at
- ``(r + dr, c + dc)`` in the trial), NaN for trials left out.
-
- Raises
- ------
- ValueError
- If the trials' statistics differ in their number of channels.
+ shifts : array_like (trials, 2), optional
+ Instead of warp: rigid shifts (consensus pixel (r, c) is at
+ (r + dr, c + dc) in the trial), NaN for trials left out.
Returns
-------
dict
- Maps ``(channels, rows, cols)`` in the consensus frame (trials of
+ Maps (channels, rows, cols) in the consensus frame (trials of
different sizes are placed at the top left of the largest, as SILo
places them): the frame
counts summed, the moments and expectations averaged, the
- normalised maps formed from them, and ``n_trials`` (trials with data
+ normalised maps formed from them, and n_trials (trials with data
at each pixel).
+
+ Raises
+ ------
+ ValueError
+ If the trials' statistics differ in their number of channels.
"""
from ...extraction.raster.alignment import TrialWarp
if warp is None:
warp = TrialWarp.from_shifts(shifts)
- used = [
- t for t, st in enumerate(stats) if st is not None and warp.aligned[t]
- ]
+ used = [t for t, st in enumerate(stats) if st is not None and warp.aligned[t]]
shape = (0, 0)
if used:
- shape = tuple(
- max(stats[t]["maps"]["mean"].shape[d] for t in used)
- for d in (1, 2)
- )
+ shape = tuple(max(stats[t]["maps"]["mean"].shape[d] for t in used) for d in (1, 2))
if len({stats[t]["maps"]["mean"].shape[0] for t in used}) > 1:
raise ValueError("the trials' statistics differ in channels")
sums, wsum, out = {}, {}, {}
@@ -153,9 +171,7 @@ def combine_trials(stats: list, warp=None, shifts=None) -> dict:
out["n_trials"] = out.get("n_trials", 0) + full
with np.errstate(invalid="ignore", divide="ignore"):
for name in sums:
- out[name] = np.where(
- wsum[name] > 0, sums[name] / wsum[name], np.nan
- )
+ out[name] = np.where(wsum[name] > 0, sums[name] / wsum[name], np.nan)
if sums:
out.update(_normalised(out))
return out
diff --git a/src/giant_python/registration/stats/svd.py b/src/giant_python/registration/stats/svd.py
index 9128aa53..f1707399 100644
--- a/src/giant_python/registration/stats/svd.py
+++ b/src/giant_python/registration/stats/svd.py
@@ -9,23 +9,24 @@
sigma_bin^2 = kappa * sum_p sigma8(p)^2 / 16,
-where ``sigma8(p)`` is pixel ``p``'s photon SD of an 8-frame mean and
-``kappa`` the trial's mean factor by which bilinear interpolation's shared
+where sigma8(p) is pixel p's photon SD of an 8-frame mean and
+kappa the trial's mean factor by which bilinear interpolation's shared
raw pixels raise the variance of a 2 x 2 sum (see
-``geometry.spatial_factor``), so that photon noise has unit variance.
+geometry.spatial_factor), so that photon noise has unit variance.
-The top :data:`N_COMPONENTS` components of ``Y = U S V^T`` are kept, each
+The top :data:`N_COMPONENTS` components of Y = U S V^T are kept, each
signed so that its spatial vector sums to a non-negative value (a mode that
brightens the trial on balance has a time course that rises). Every pixel's
-weight on component ``j`` is the coefficient of ``u_j`` in a least-squares
+weight on component j is the coefficient of u_j in a least-squares
fit of its own 8-frame bin means (movie units, its valid bins, with an
-intercept) on the time courses: ``weight`` in movie units per unit of the
-unit-norm time course, ``weight_ph`` divided by ``sigma8``.
+intercept) on the time courses: weight in movie units per unit of the
+unit-norm time course, weight_ph divided by sigma8.
"""
from __future__ import annotations
import numpy as np
+import torch
N_COMPONENTS = 3
"""Components kept."""
@@ -41,7 +42,14 @@
def _stack_bins(bins: list, n_idx: int) -> np.ndarray:
- """``(channels, n_bins, n_idx)`` float64, NaN-padded per block."""
+ """(channels, n_bins, n_idx) float64, NaN-padded per block.
+
+ Returns
+ -------
+ np.ndarray
+ The blocks' bin means concatenated along the bin axis, each padded with NaN to
+ n_idx pixels; (0, 0, n_idx) zeros without blocks.
+ """
parts = []
for b in bins:
b = b.numpy().astype(np.float64)
@@ -52,9 +60,11 @@ def _stack_bins(bins: list, n_idx: int) -> np.ndarray:
return np.concatenate(parts, 1)
-def bin_members(idx, shape) -> np.ndarray:
- """``(n_space, 4)`` compact positions of the four pixels of every
- 2 x 2 bin whose pixels are all in the index (bins in raster order).
+def bin_members(idx: np.ndarray, shape: tuple[int, int]) -> np.ndarray:
+ """(n_space, 4) compact positions of the four pixels of every 2 x 2 bin.
+
+ Only bins whose pixels are all in the index are included (bins in raster
+ order).
Parameters
----------
@@ -62,6 +72,12 @@ def bin_members(idx, shape) -> np.ndarray:
Flat registered-grid index of the compact pixels.
shape : (int, int)
Registered grid.
+
+ Returns
+ -------
+ np.ndarray
+ (n_space, 4) positions in idx of each bin's four pixels, bins in raster
+ order.
"""
h, w = shape
h2, w2 = h // 2, w // 2
@@ -73,33 +89,47 @@ def bin_members(idx, shape) -> np.ndarray:
def _binned(full: np.ndarray, members: np.ndarray) -> np.ndarray:
- """2 x 2 bin means ``(n_bins, n_space)`` of compact time bins
- ``(n_bins, n_idx)`` (NaN unless all four pixels are present)."""
+ """2 x 2 bin means (n_bins, n_space) of compact time bins (n_bins, n_idx).
+
+ NaN unless all four pixels are present.
+
+ Returns
+ -------
+ np.ndarray
+ The mean of each bin's four pixels, shape (n_bins, n_space).
+ """
return full[:, members].mean(-1)
-def _bin_sigma(bin_var: np.ndarray, members: np.ndarray):
- """Photon-noise SD of each 2 x 2 bin's mean ``(n_space,)`` from its
- pixels' shares (:func:`.maps.bin_var8`)."""
+def _bin_sigma(bin_var: np.ndarray, members: np.ndarray) -> np.ndarray:
+ """Photon-noise SD of each 2 x 2 bin's mean (n_space,).
+
+ From its pixels' shares (:func:`.maps.bin_var8`).
+
+ Returns
+ -------
+ np.ndarray
+ The photon-noise SD of each bin's mean, shape (n_space,).
+ """
return np.sqrt(bin_var[members].sum(-1) / 16)
-def _components(y: np.ndarray, k: int):
- """Top ``k`` signed components of ``y`` ``(n_bins, n_space)``.
+def _components(y: np.ndarray, k: int) -> tuple[np.ndarray, np.ndarray, float]:
+ """Top k signed components of y (n_bins, n_space).
- From the eigenvectors of the smaller Gram matrix: ``y y^T`` (time bins
+ From the eigenvectors of the smaller Gram matrix: y y^T (time bins
x time bins; its eigenvectors are the left singular vectors) or, for a
- trial with more time bins than spatial bins, ``y^T y`` (then ``u = y v
- / s``). Memory and time go with the smaller side squared and cubed.
+ trial with more time bins than spatial bins, y^T y (then u = y v
+ / s). Memory and time go with the smaller side squared and cubed.
Returns
-------
- u : ndarray ``(n_bins, n)``
- s : ndarray ``(n,)``
- The ``n <= k`` components whose singular value is above
+ u : ndarray (n_bins, n)
+ s : ndarray (n,)
+ The n <= k components whose singular value is above
:data:`RANK_TOL` of the largest.
total : float
- ``sum(y^2)`` (the sum of all squared singular values).
+ sum(y^2) (the sum of all squared singular values).
"""
tall = y.shape[0] > y.shape[1]
gram = y.T @ y if tall else y @ y.T
@@ -116,8 +146,16 @@ def _components(y: np.ndarray, k: int):
return u * sign, s, float(np.trace(gram))
-def _descriptors(u: np.ndarray):
- """Skewness and lag-1 autocorrelation of each time course."""
+def _descriptors(u: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Skewness and lag-1 autocorrelation of each time course.
+
+ Returns
+ -------
+ skew : np.ndarray
+ Skewness of each time course (column of u).
+ lag1 : np.ndarray
+ Lag-1 autocorrelation of each time course.
+ """
c = u - u.mean(0)
m2 = (c**2).mean(0)
with np.errstate(invalid="ignore", divide="ignore"):
@@ -127,18 +165,18 @@ def _descriptors(u: np.ndarray):
def regression_weights(y: np.ndarray, u: np.ndarray) -> np.ndarray:
- """Least-squares coefficients of ``u`` for every pixel.
+ """Least-squares coefficients of u for every pixel.
Parameters
----------
- y : ndarray ``(n_bins, n_px)``
+ y : ndarray (n_bins, n_px)
Pixels' bin means, NaN where missing.
- u : ndarray ``(n_bins, k)``
+ u : ndarray (n_bins, k)
Time courses.
Returns
-------
- ndarray ``(n_px, k)``
+ ndarray (n_px, k)
Coefficients (with an intercept in the fit); NaN for pixels with
fewer than :data:`MIN_BINS` bins, or whose bins do not determine
the fit (a time course that is flat over them: condition number of
@@ -164,7 +202,14 @@ def regression_weights(y: np.ndarray, u: np.ndarray) -> np.ndarray:
def _empty(c: int, nb: int, n_idx: int, k: int) -> dict:
- """Outputs of a trial without enough data (NaN)."""
+ """Build the outputs of a trial without enough data (NaN).
+
+ Returns
+ -------
+ dict
+ The outputs of :func:`shared_modes` for c channels, filled with NaN (n_space
+ zero).
+ """
nan = np.full((c, k), np.nan)
return {
"time_courses": np.full((c, k, nb), np.nan),
@@ -179,8 +224,17 @@ def _empty(c: int, nb: int, n_idx: int, k: int) -> dict:
}
-def _channel(out, ch, full, idx, shape, sigma8, bin_var, k) -> None:
- """Fill channel ``ch`` of ``out``."""
+def _channel(
+ out: dict,
+ ch: int,
+ full: np.ndarray,
+ idx: np.ndarray,
+ shape: tuple[int, int],
+ sigma8: np.ndarray,
+ bin_var: np.ndarray,
+ k: int,
+) -> None:
+ """Fill channel ch of out."""
members = bin_members(idx, shape)
b = _binned(full, members)
sd = _bin_sigma(bin_var, members)
@@ -204,20 +258,27 @@ def _channel(out, ch, full, idx, shape, sigma8, bin_var, k) -> None:
out["weight_ph"][ch, :, :n] = wts / sigma8[:, None]
-def shared_modes(bins, idx, shape, sigma8, bin_var, k=N_COMPONENTS) -> dict:
- """The trial's top shared modes per channel.
+def shared_modes(
+ bins: list[torch.Tensor],
+ idx: np.ndarray,
+ shape: tuple[int, int],
+ sigma8: np.ndarray,
+ bin_var: np.ndarray,
+ k: int = N_COMPONENTS,
+) -> dict:
+ """Compute the trial's top shared modes per channel.
Parameters
----------
bins : list of torch.Tensor
- Per block ``(channels, n_bins, n_idx_then)`` 8-frame bin means.
+ Per block (channels, n_bins, n_idx_then) 8-frame bin means.
idx : ndarray of int
Flat registered-grid index of the compact pixels.
shape : (int, int)
Registered grid.
- sigma8 : ndarray ``(channels, n_idx)``
- Photon SD of each pixel's 8-frame mean (for ``weight_ph``).
- bin_var : ndarray ``(channels, n_idx)``
+ sigma8 : ndarray (channels, n_idx)
+ Photon SD of each pixel's 8-frame mean (for weight_ph).
+ bin_var : ndarray (channels, n_idx)
Each pixel's share of the photon variance of a 2 x 2 sum of
8-frame means (:func:`.maps.bin_var8`).
k : int
@@ -226,10 +287,10 @@ def shared_modes(bins, idx, shape, sigma8, bin_var, k=N_COMPONENTS) -> dict:
Returns
-------
dict
- ``time_courses`` ``(channels, k, n_bins)``, ``singular_values``,
- ``var_share``, ``skew``, ``lag1`` ``(channels, k)``, ``total_var``,
- ``n_space`` ``(channels,)``, ``weight`` and ``weight_ph``
- ``(channels, n_idx, k)``.
+ time_courses (channels, k, n_bins), singular_values,
+ var_share, skew, lag1 (channels, k), total_var,
+ n_space (channels,), weight and weight_ph
+ (channels, n_idx, k).
"""
full = _stack_bins(bins, idx.size)
c = sigma8.shape[0]
diff --git a/src/giant_python/registration/stats/worker.py b/src/giant_python/registration/stats/worker.py
index d9ac4c5e..5a11ac3c 100644
--- a/src/giant_python/registration/stats/worker.py
+++ b/src/giant_python/registration/stats/worker.py
@@ -13,10 +13,15 @@
import logging
import threading
import time
+from collections.abc import Callable, Iterable
from concurrent.futures import Future, ThreadPoolExecutor
+from typing import TYPE_CHECKING
import torch
+if TYPE_CHECKING:
+ from .accumulate import TrialStatsAccumulator
+
log = logging.getLogger(__name__)
BACKLOG = 32
@@ -32,8 +37,10 @@
class StatsWorker:
- """Set up and accumulate a trial's statistics, on a thread (and, on a
- GPU, a CUDA stream) of their own where :data:`THREADED` says so.
+ """Set up and accumulate a trial's statistics, on a thread of their own.
+
+ They get a thread (and, on a GPU, a CUDA stream) of their own where
+ :data:`THREADED` says so.
A step that fails is logged and stops the statistics; registration goes
on without them (:attr:`failed`, and :meth:`finish` gives
@@ -49,8 +56,12 @@ class StatsWorker:
a thread.
"""
- def __init__(self, setup, device="cpu"):
- """Start the worker with ``setup``."""
+ def __init__(
+ self,
+ setup: Callable[[], "TrialStatsAccumulator"],
+ device: torch.device | str = "cpu",
+ ) -> None:
+ """Start the worker with setup."""
self.seconds = 0.0
self.failed = False
self._acc = None
@@ -65,18 +76,37 @@ def __init__(self, setup, device="cpu"):
self._stream = torch.cuda.Stream(device)
self._submit(self._setup, None, setup)
- def _setup(self, setup) -> None:
+ def _setup(self, setup: Callable[[], "TrialStatsAccumulator"]) -> None:
"""Make the accumulator."""
self._acc = setup()
- def _call(self, name: str, *args):
- """Call the accumulator's method ``name``."""
+ def _call(self, name: str, *args: object) -> object:
+ """Call the accumulator's method name.
+
+ Returns
+ -------
+ object
+ Whatever the accumulator's method returns for args.
+ """
return getattr(self._acc, name)(*args)
- def _submit(self, fn, tensors, *args) -> Future:
- """Queue a step (waits while :data:`BACKLOG` steps are queued), or
- run it now without a thread. ``tensors`` (made on the caller's
- stream) are what the step reads."""
+ def _submit(
+ self,
+ fn: Callable[..., object],
+ tensors: Iterable[torch.Tensor] | None,
+ *args: object,
+ ) -> Future:
+ """Queue a step (waits while :data:`BACKLOG` steps are queued).
+
+ Without a thread, run it now. tensors (made on the caller's stream)
+ are what the step reads.
+
+ Returns
+ -------
+ Future
+ The step's future: already resolved when there is no thread, otherwise the
+ pool's future for the queued step.
+ """
if self._pool is None:
done = Future()
done.set_result(self._step(fn, None, None, *args))
@@ -94,8 +124,20 @@ def _submit(self, fn, tensors, *args) -> Future:
self._slots.release()
raise
- def _step(self, fn, ready, tensors, *args):
- """Run a step unless an earlier one failed; time it."""
+ def _step(
+ self,
+ fn: Callable[..., object],
+ ready: torch.cuda.Event | None,
+ tensors: Iterable[torch.Tensor] | None,
+ *args: object,
+ ) -> object:
+ """Run a step unless an earlier one failed; time it.
+
+ Returns
+ -------
+ object
+ The step's result, or :data:`FAILED` if an earlier step or this one failed.
+ """
try:
if self.failed:
return FAILED
@@ -118,21 +160,34 @@ def _step(self, fn, ready, tensors, *args):
if self._pool is not None:
self._slots.release()
- def add(self, k: int, regs, var_factor, motion) -> None:
- """Queue registered frame ``k`` (see
- :meth:`~.accumulate.TrialStatsAccumulator.add`). The tensors must
- not be changed afterwards."""
+ def add(
+ self,
+ k: int,
+ regs: Iterable[torch.Tensor],
+ var_factor: torch.Tensor,
+ motion: tuple[float, float],
+ ) -> None:
+ """Queue registered frame k.
+
+ See :meth:`~.accumulate.TrialStatsAccumulator.add`. The tensors must
+ not be changed afterwards.
+ """
if not self.failed:
regs = list(regs)
tensors = [t for t in regs + [var_factor] if t.is_cuda]
- self._submit(
- self._call, tensors, "add", k, regs, var_factor, motion
- )
+ self._submit(self._call, tensors, "add", k, regs, var_factor, motion)
def finish(self) -> Future:
- """Queue the maps after the last frame; the future's result is
- :meth:`~.accumulate.TrialStatsAccumulator.finish`'s, or
- :data:`FAILED`. Later calls return the same future."""
+ """Queue the maps after the last frame.
+
+ The future's result is :meth:`~.accumulate.TrialStatsAccumulator.finish`'s,
+ or :data:`FAILED`. Later calls return the same future.
+
+ Returns
+ -------
+ Future
+ The future of the maps (or of :data:`FAILED`); the same one on every call.
+ """
if self._done is None and self.failed:
self._done = Future()
self._done.set_result(FAILED)
@@ -143,8 +198,10 @@ def finish(self) -> Future:
return self._done
def cancel(self) -> None:
- """Give up: queued steps are dropped (a running one completes on
- its own)."""
+ """Give up: queued steps are dropped.
+
+ A running one completes on its own.
+ """
self.failed = True
if self._pool is not None:
self._pool.shutdown(wait=False, cancel_futures=True)
diff --git a/src/giant_python/registration/template.py b/src/giant_python/registration/template.py
index 0cbecbc1..12c5e3dd 100644
--- a/src/giant_python/registration/template.py
+++ b/src/giant_python/registration/template.py
@@ -1,11 +1,11 @@
"""Registration templates: the initial consensus template and its growth.
-The initial template follows GIAnT-MATLAB ``MultiRoiRegistration``: frames
+The initial template follows GIAnT-MATLAB MultiRoiRegistration: frames
spread over the trial are matched pairwise; the frame with the highest median
correlation is the reference, and the frames correlating with it at least as
well as that median are shifted onto it and averaged. The running template is
the square root of the mean of all registered frames added so far (pixels
-with fewer than ``min_samples`` contributions are NaN); frames are matched to
+with fewer than min_samples contributions are NaN); frames are matched to
the average of the initial and the running template.
Initial frames without valid samples are left out of the consensus (in
@@ -13,6 +13,7 @@
is averaged and the template is empty).
"""
+from collections.abc import Sequence
from dataclasses import dataclass
import numpy as np
@@ -29,10 +30,10 @@ class ConsensusResult:
Attributes
----------
correlation : ndarray
- ``(n, n)`` peak correlations between frames (1 on the diagonal).
+ (n, n) peak correlations between frames (1 on the diagonal).
motion : ndarray
- ``(2, n, n)`` [row, col] motion; ``motion[:, i, j]`` matches frame
- ``j`` to frame ``i`` as template.
+ (2, n, n) [row, col] motion; motion[:, i, j] matches frame
+ j to frame i as template.
reference : int
Zero-based index of the reference frame (-1 if no frame has
samples).
@@ -46,8 +47,16 @@ class ConsensusResult:
members: np.ndarray
-def window_image(values: torch.Tensor, index: torch.Tensor, shape, fill):
- """Place per-pixel values into ``(..., H, W)`` images."""
+def window_image(
+ values: torch.Tensor, index: torch.Tensor, shape: Sequence[int], fill: float
+) -> torch.Tensor:
+ """Place per-pixel values into (..., H, W) images.
+
+ Returns
+ -------
+ torch.Tensor
+ The images of shape, holding values at the pixels index and fill elsewhere.
+ """
lead = values.shape[:-1]
out = torch.full(
lead + (shape[0] * shape[1],),
@@ -66,17 +75,17 @@ def consensus(
rows: torch.Tensor,
cols: torch.Tensor,
search: int,
- dtype=torch.float32,
- keep=None,
+ dtype: torch.dtype = torch.float32,
+ keep: np.ndarray | None = None,
) -> ConsensusResult:
"""Match every pair of initial frames and choose the consensus set.
Parameters
----------
frames, freshness : torch.Tensor
- ``(n, pixels)`` frame values (NaN where invalid) and freshness.
+ (n, pixels) frame values (NaN where invalid) and freshness.
images : torch.Tensor
- ``(n, H, W)`` the same frames as window images.
+ (n, H, W) the same frames as window images.
rows, cols : torch.Tensor of int
Zero-based pixel positions in the window.
search : int
@@ -101,14 +110,10 @@ def consensus(
if idx.size == 0:
return ConsensusResult(corr, mot, -1, idx)
sel = torch.as_tensor(idx, device=frames.device)
- sub = consensus(
- frames[sel], freshness[sel], images[sel], rows, cols, search, dtype
- )
+ sub = consensus(frames[sel], freshness[sel], images[sel], rows, cols, search, dtype)
corr[np.ix_(idx, idx)] = sub.correlation
mot[:, idx[:, None], idx[None, :]] = sub.motion
- return ConsensusResult(
- corr, mot, int(idx[sub.reference]), idx[sub.members]
- )
+ return ConsensusResult(corr, mot, int(idx[sub.reference]), idx[sub.members])
corr = np.ones((n, n))
mot = np.zeros((2, n, n))
weights = torch.where(torch.isnan(frames), 0.0, freshness)
@@ -140,16 +145,22 @@ class TemplateState:
Parameters
----------
total : torch.Tensor
- ``(H + 2m, W + 2m)`` float64 sum of registered frames (NaN skipped).
+ (H + 2m, W + 2m) float64 sum of registered frames (NaN skipped).
count : torch.Tensor
Same shape: number of frames contributing to each pixel.
initial : torch.Tensor
- The initial template ``T0``.
+ The initial template T0.
min_samples : int
Pixels with fewer contributions are NaN in the template.
"""
- def __init__(self, total, count, initial, min_samples: int):
+ def __init__(
+ self,
+ total: torch.Tensor,
+ count: torch.Tensor,
+ initial: torch.Tensor | None,
+ min_samples: int,
+ ) -> None:
"""Store the sums and compute the template."""
self.total = total
self.count = count
@@ -158,21 +169,26 @@ def __init__(self, total, count, initial, min_samples: int):
self.template = self._template()
def _template(self) -> torch.Tensor:
- """``sqrt(total / count)``, NaN below ``min_samples``."""
+ """sqrt(total / count), NaN below min_samples.
+
+ Returns
+ -------
+ torch.Tensor
+ The template: the root of the mean of the frames' sums, NaN where fewer than
+ min_samples frames contribute.
+ """
t = torch.sqrt(self.total / self.count)
return t.masked_fill(self.count < self.min_samples, float("nan"))
def add(self, image: torch.Tensor) -> None:
"""Add one registered frame (NaN pixels are skipped)."""
sel = ~torch.isnan(image)
- self.total = self.total + torch.where(sel, image, 0.0).to(
- self.total.dtype
- )
+ self.total = self.total + torch.where(sel, image, 0.0).to(self.total.dtype)
self.count = self.count + sel
self.template = self._template()
def update(self, images: torch.Tensor, sign: int = 1) -> None:
- """Add (``sign=1``) or remove (``-1``) a stack of registered frames.
+ """Add (sign=1) or remove (-1) a stack of registered frames.
The template is recomputed once, after all frames.
"""
@@ -185,7 +201,13 @@ def update(self, images: torch.Tensor, sign: int = 1) -> None:
self.template = self._template()
def matching_template(self) -> torch.Tensor:
- """Mean of the initial and running templates, ignoring NaNs."""
+ """Mean of the initial and running templates, ignoring NaNs.
+
+ Returns
+ -------
+ torch.Tensor
+ The mean of the two templates; where one is NaN, the other.
+ """
a, b = self.initial, self.template
both = (a + b) / 2
out = torch.where(torch.isnan(a), b, both)
@@ -204,19 +226,19 @@ def initial_template(
Parameters
----------
images, fresh_images : torch.Tensor
- ``(n, H, W)`` initial frames (NaN where unsampled) and freshness
+ (n, H, W) initial frames (NaN where unsampled) and freshness
(0 where unsampled).
result : ConsensusResult
Output of :func:`consensus`.
margin : int
- Padding of the output grid (``maxshift``).
+ Padding of the output grid (maxshift).
min_samples : int
Minimum contributions for a template pixel.
Returns
-------
TemplateState
- Sums of the shifted consensus frames, with ``T0`` as both initial
+ Sums of the shifted consensus frames, with T0 as both initial
and running template (empty, all NaN, without members).
"""
ref = result.reference
diff --git a/src/giant_python/simulation/injection.py b/src/giant_python/simulation/injection.py
index 7ce43b42..7c6aa533 100644
--- a/src/giant_python/simulation/injection.py
+++ b/src/giant_python/simulation/injection.py
@@ -1,6 +1,6 @@
"""Synthetic events injected into the raw samples of a SLAP2 recording.
-A copy of a session's raw ``.dat`` files is made in which the raster samples
+A copy of a session's raw .dat files is made in which the raster samples
of one channel hold extra photons from synthetic sources whose positions,
footprints, event times, sizes and time course are known; a truth file
records them. Everything else in the copy (file and line headers, line
@@ -10,57 +10,57 @@
**Where the sources are.** Sources are fixed in the tissue as the session's
own registration sees it. Each path has a *path frame*: the registered frame
of its reference trial (by default the first injected trial), with zero-based
-``(row, col)`` coordinates of the registered movie (as
+(row, col) coordinates of the registered movie (as
:func:`~giant_python.extraction.raster.trial.load_registered_trial` returns
-it, MATLAB orientation; pixel centres at integers). Trial ``t``'s registered
-frame is the path frame shifted by ``trial_shift[t]`` (a position ``p`` in
-the path frame is ``p + trial_shift[t]`` in the trial's frame), estimated by
+it, MATLAB orientation; pixel centres at integers). Trial t's registered
+frame is the path frame shifted by trial_shift[t] (a position p in
+the path frame is p + trial_shift[t] in the trial's frame), estimated by
aligning the trials' mean images (:func:`align_images`) unless given, for
example as SILo's across-trial alignment.
-A sample of DMD pixel ``(r, c)`` (zero-based) on line ``l`` lies at
-``(r, c) + shift(l)`` in the trial's registered frame (:func:`trial_geometry`)
-with, as SILo's ``loadTrial`` combines them::
+A sample of DMD pixel (r, c) (zero-based) on line l lies at
+(r, c) + shift(l) in the trial's registered frame (:func:`trial_geometry`)
+with, as SILo's loadTrial combines them::
shift(l) = o(l) - (trim - 1) + maxshift - M(l)
-where ``trim`` is the first DMD row and column of the registration window
-(one-based ``trimRows(1)``, ``trimCols(1)``), ``M(l)`` the registration's
-motion interpolated to the line (``pchip``, extrapolated), and, when the
-registration undid the online motion correction (``compensateOnline``),
-``o(l) = mapping @ ([x(l), y_eff(l)] - refOffset)`` with the line's online
-offsets and ``M`` the continuous motion ``motionDS + mapping @ (frameRef -
-refOffset)``; without compensation ``o = 0`` and ``M = motionDS`` (the
+where trim is the first DMD row and column of the registration window
+(one-based trimRows(1), trimCols(1)), M(l) the registration's
+motion interpolated to the line (pchip, extrapolated), and, when the
+registration undid the online motion correction (compensateOnline),
+o(l) = mapping @ ([x(l), y_eff(l)] - refOffset) with the line's online
+offsets and M the continuous motion motionDS + mapping @ (frameRef -
+refOffset); without compensation o = 0 and M = motionDS (the
registration's motion then includes the online offsets). A source therefore
stays still in the registered movie of the original data; in the tissue it
moves with the registration's error.
**What is added.** The expected extra raw counts of a sample of the injected
-channel are ``photon_scale * sum_j f_j(p - p_j) * a_j(t)`` over sources
-``j``: ``f_j`` is the footprint (peak 1), ``p`` the sample's registered
-position, ``p_j`` the source's, and ``a_j`` the source's events convolved
-with the indicator's time course at the line's time ``(l - 1) *
-line_period``. Event sizes are in the units of GIAnT's ground-truth refit
-test: frame counts / ``photon_scale`` at the source's peak pixel at the
+channel are photon_scale * sum_j f_j(p - p_j) * a_j(t) over sources
+j: f_j is the footprint (peak 1), p the sample's registered
+position, p_j the source's, and a_j the source's events convolved
+with the indicator's time course at the line's time (l - 1) *
+line_period. Event sizes are in the units of GIAnT's ground-truth refit
+test: frame counts / photon_scale at the source's peak pixel at the
event's peak, in SILo's 200 Hz frames. Frames formed from raw samples keep
only part of an instantaneous peak (their kernel averages over several
milliseconds and the pixel's few samples per cycle, resampling blurs it), so
each source's tissue amplitude is its event size divided by the share its
frames keep, measured on noiseless frames of unit events
(:func:`calibrate_frame_peaks`). The
-expectation is divided by the raw units per photon ``g``; a Poisson draw
-``N`` of it adds ``floor(N * g + U)`` raw counts (``U`` uniform on [0, 1), so
-the mean is exactly ``N * g``), saturating at 32767. Invalid samples
+expectation is divided by the raw units per photon g; a Poisson draw
+N of it adds floor(N * g + U) raw counts (U uniform on [0, 1), so
+the mean is exactly N * g), saturating at 32767. Invalid samples
(-32768) are left as they are.
-``g`` is measured on the original recording (:func:`measure_raw_per_photon`)
+g is measured on the original recording (:func:`measure_raw_per_photon`)
as the variance-to-mean ratio of its raw samples, so injected photons carry
the shot noise of real ones; it is larger than the mean single-photon pulse
height, which is also recorded.
-Run as ``python -m giant_python.simulation.injection inject TRIAL_TABLE
-OUT_DIR`` (or call :func:`inject_session`); after registering the copy
-(``giant register OUT_DIR/trial_table.h5``), ``... compare OUT_DIR`` (or
+Run as python -m giant_python.simulation.injection inject TRIAL_TABLE
+OUT_DIR (or call :func:`inject_session`); after registering the copy
+(giant register OUT_DIR/trial_table.h5), ... compare OUT_DIR (or
:func:`record_copy_registration`) records where the copy's registered frames
put the sources.
"""
@@ -76,13 +76,14 @@
import sys
import time
import warnings
+from collections.abc import Callable, Iterator, Sequence
from dataclasses import asdict, dataclass, replace
from datetime import datetime
from pathlib import Path
-from typing import Dict, List, Optional, Sequence, Tuple, Union
import h5py
import numpy as np
+from numpy.typing import ArrayLike
from scipy import ndimage
from scipy.interpolate import PchipInterpolator
from scipy.spatial import cKDTree
@@ -99,7 +100,7 @@
log = logging.getLogger(__name__)
PHOTON_SCALE = 25.0
-"""Raw counts of one size unit (GIAnT's ``photonScale`` for SLAP2)."""
+"""Raw counts of one size unit (GIAnT's photonScale for SLAP2)."""
SIZE_CLASSES = (0.25, 0.5, 1.0, 2.0, 4.0, 8.0)
"""Event sizes of GIAnT's ground-truth refit test."""
@@ -108,7 +109,7 @@
"""Largest raw sample (int16)."""
TRUTH_FORMAT = "giant_python.simulation.injection/1"
-"""``format`` attribute of truth files."""
+"""format attribute of truth files."""
TRUTH_NAME = "injection_truth.h5"
"""Name of the truth file in the output folder."""
@@ -121,10 +122,14 @@
def _rng(seed: int, *key: int) -> np.random.Generator:
- """An independent generator for one purpose (``key``) of a seed."""
- ss = np.random.SeedSequence(
- int(seed), spawn_key=tuple(int(k) for k in key)
- )
+ """Make an independent generator for one purpose (key) of a seed.
+
+ Returns
+ -------
+ np.random.Generator
+ A generator seeded from seed and spawn key key.
+ """
+ ss = np.random.SeedSequence(int(seed), spawn_key=tuple(int(k) for k in key))
return np.random.default_rng(ss)
@@ -138,20 +143,20 @@ class InjectionSettings:
Attributes
----------
size_classes : tuple of float
- Event sizes in units of ``photon_scale`` raw counts (see
- ``size_reference``).
+ Event sizes in units of photon_scale raw counts (see
+ size_reference).
class_weights : tuple of float, optional
Relative frequency of each size class (default: equal).
rate_hz : float
Rate of each source's events outside their dead time: the interval
- between events is ``min_interval_s`` plus an exponential with mean
- ``1 / rate_hz`` (so the mean rate is ``1 / (min_interval_s + 1 /
- rate_hz)``). 0 injects nothing.
+ between events is min_interval_s plus an exponential with mean
+ 1 / rate_hz (so the mean rate is 1 / (min_interval_s + 1 /
+ rate_hz)). 0 injects nothing.
min_interval_s : float
Dead time after each event of a source.
sync_share : float
Share (0 to 1) of the events that come at onsets common to all
- sources of a path and trial: one train with ``sync_share`` of the
+ sources of a path and trial: one train with sync_share of the
rate is given to every source, and each source's own train has the
rest. Sizes stay independent. A source's own event within the dead
time of a common one is dropped, and the dead time weighs more on
@@ -164,12 +169,12 @@ class InjectionSettings:
Event onsets keep at least this distance from the trial's first and
last line.
tau_s : float
- Decay time constant of the indicator (SILo's ``tau_s``).
+ Decay time constant of the indicator (SILo's tau_s).
rise_s : float
Rise time constant; 0 for an instant rise. Otherwise the time course
- is ``exp(-t / tau_s) - exp(-t / rise_s)`` scaled to a peak of 1.
+ is exp(-t / tau_s) - exp(-t / rise_s) scaled to a peak of 1.
sigma_px : float
- Width of the default Gaussian footprint (SILo's ``sigma_px``), in
+ Width of the default Gaussian footprint (SILo's sigma_px), in
registered pixels.
radius_sigmas : float
The Gaussian footprint is zero beyond this many sigmas.
@@ -181,31 +186,31 @@ class InjectionSettings:
Raw units per photon; by default measured on each path's reference
trial (:func:`measure_raw_per_photon`).
analyze_hz : float
- Rate of the frames (SILo's ``analyzeHz``) at which sizes are
+ Rate of the frames (SILo's analyzeHz) at which sizes are
calibrated and the truth gives each source's traces.
seed : int
Seeds placement, events, calibration and photon draws.
size_reference : str
- ``'frames'`` (default): a size is the event's expected peak in
- SILo's ``analyze_hz`` frames at the source's peak pixel, in frame
- counts / ``photon_scale`` (the units of GIAnT's ground-truth refit
+ 'frames' (default): a size is the event's expected peak in
+ SILo's analyze_hz frames at the source's peak pixel, in frame
+ counts / photon_scale (the units of GIAnT's ground-truth refit
test); each source's injected amplitude is scaled by what its frames
keep of an event's peak (:func:`calibrate_frame_peaks`).
- ``'tissue'``: a size is the instantaneous peak at the footprint's
+ 'tissue': a size is the instantaneous peak at the footprint's
centre, before frames are formed.
calibration_s : float
Length of the trial stretch used to calibrate frame peaks.
frame_traces : bool
- Also give each source's noiseless trace in ``analyze_hz`` frames at
+ Also give each source's noiseless trace in analyze_hz frames at
its peak pixel (formed as SILo forms frames; a render of every
trial).
device : str
Where frames are formed for calibration and frame traces
- (``'auto'``: CUDA when available).
+ ('auto': CUDA when available).
"""
- size_classes: Tuple[float, ...] = SIZE_CLASSES
- class_weights: Optional[Tuple[float, ...]] = None
+ size_classes: tuple[float, ...] = SIZE_CLASSES
+ class_weights: tuple[float, ...] | None = None
rate_hz: float = 1.0
min_interval_s: float = 0.1
sync_share: float = 0.0
@@ -216,7 +221,7 @@ class InjectionSettings:
radius_sigmas: float = 4.0
photon_scale: float = PHOTON_SCALE
channel: int = 0
- raw_per_photon: Optional[float] = None
+ raw_per_photon: float | None = None
analyze_hz: float = 200.0
seed: int = 0
size_reference: str = "frames"
@@ -224,8 +229,16 @@ class InjectionSettings:
frame_traces: bool = True
device: str = "auto"
- def __post_init__(self):
- """Reject settings that cannot describe events."""
+ def __post_init__(self) -> None:
+ """Reject settings that cannot describe events.
+
+ Raises
+ ------
+ ValueError
+ If a size class, class weight, rate, interval, edge, sync share, time constant, width,
+ radius, photon scale, analysis rate, calibration time, raw units per photon, channel
+ or size reference is out of its valid range.
+ """
w = self.class_weights
rules = [
(
@@ -233,12 +246,7 @@ def __post_init__(self):
"size_classes must be non-negative sizes",
),
(
- w is not None
- and (
- len(w) != len(self.size_classes)
- or min(w) < 0
- or sum(w) <= 0
- ),
+ w is not None and (len(w) != len(self.size_classes) or min(w) < 0 or sum(w) <= 0),
"class_weights must match size_classes",
),
(
@@ -262,15 +270,14 @@ def __post_init__(self):
self.calibration_s,
)
<= 0,
- "sigma_px, radius_sigmas, photon_scale, analyze_hz and "
- "calibration_s must be positive",
+ (
+ "sigma_px, radius_sigmas, photon_scale, analyze_hz and "
+ "calibration_s must be positive"
+ ),
),
(
self.raw_per_photon is not None
- and not (
- math.isfinite(self.raw_per_photon)
- and self.raw_per_photon > 0
- ),
+ and not (math.isfinite(self.raw_per_photon) and self.raw_per_photon > 0),
"raw_per_photon must be positive and finite",
),
(self.channel < 0, "channel must be a zero-based channel index"),
@@ -308,7 +315,7 @@ class PlacementSettings:
a sensor session).
label_factor : float
Labeled pixels: the 3 x 3 median of the mean image above this
- factor times its 25th percentile (SILo's ``loadTrial`` uses 3).
+ factor times its 25th percentile (SILo's loadTrial uses 3).
"""
min_separation_px: float = 6.0
@@ -321,26 +328,32 @@ class PlacementSettings:
def peak_delay_s(tau_s: float, rise_s: float = 0.0) -> float:
- """Time from onset to the peak of the time course."""
+ """Time from onset to the peak of the time course.
+
+ Returns
+ -------
+ float
+ The delay in seconds; 0 for an instant rise.
+ """
if rise_s <= 0:
return 0.0
return tau_s * rise_s / (tau_s - rise_s) * math.log(tau_s / rise_s)
-def time_course(t_s, tau_s: float, rise_s: float = 0.0) -> np.ndarray:
- """The indicator's response to an event at time 0, with a peak of 1.
+def time_course(t_s: ArrayLike, tau_s: float, rise_s: float = 0.0) -> np.ndarray:
+ """Compute the indicator's response to an event at time 0, with a peak of 1.
Parameters
----------
t_s : array_like
Times after onset (negative: before the event).
tau_s, rise_s : float
- Decay and rise time constants (``rise_s`` 0: instant rise).
+ Decay and rise time constants (rise_s 0: instant rise).
Returns
-------
ndarray
- 0 before onset; ``exp(-t / tau_s)``, or the difference of
+ 0 before onset; exp(-t / tau_s), or the difference of
exponentials scaled to a peak of 1.
"""
t = np.asarray(t_s, dtype=np.float64)
@@ -356,10 +369,14 @@ def time_course(t_s, tau_s: float, rise_s: float = 0.0) -> np.ndarray:
def kernel_extent_s(settings: InjectionSettings) -> float:
- """Time after onset beyond which the time course is below 1e-6."""
- return peak_delay_s(settings.tau_s, settings.rise_s) + settings.tau_s * (
- 6 * math.log(10)
- )
+ """Time after onset beyond which the time course is below 1e-6.
+
+ Returns
+ -------
+ float
+ The time in seconds.
+ """
+ return peak_delay_s(settings.tau_s, settings.rise_s) + settings.tau_s * (6 * math.log(10))
@dataclass
@@ -373,10 +390,10 @@ class Events:
trial : ndarray of int
One-based trial (column of the original trial table).
onset_line : ndarray of float
- Onset as a one-based line coordinate (line ``l`` is acquired at
- ``(l - 1) * line_period_s`` after the recording's first line).
+ Onset as a one-based line coordinate (line l is acquired at
+ (l - 1) * line_period_s after the recording's first line).
size_class : ndarray of int
- Index into ``size_classes``.
+ Index into size_classes.
size : ndarray of float
Size (see :class:`InjectionSettings`).
"""
@@ -388,37 +405,57 @@ class Events:
size: np.ndarray
@classmethod
- def empty(cls) -> "Events":
- """No events."""
+ def empty(cls) -> Events:
+ """No events.
+
+ Returns
+ -------
+ Events
+ An instance without events.
+ """
z = np.zeros(0)
- return cls(
- z.astype(np.int64), z.astype(np.int64), z, z.astype(np.int64), z
- )
+ return cls(z.astype(np.int64), z.astype(np.int64), z, z.astype(np.int64), z)
@classmethod
- def concat(cls, parts: Sequence["Events"]) -> "Events":
- """Events of several parts, in order."""
+ def concat(cls, parts: Sequence[Events]) -> Events:
+ """Events of several parts, in order.
+
+ Returns
+ -------
+ Events
+ The parts' events concatenated; none if parts is empty.
+ """
if not parts:
return cls.empty()
- return cls(
- *[
- np.concatenate([getattr(p, k) for p in parts])
- for k in (
- "source",
- "trial",
- "onset_line",
- "size_class",
- "size",
- )
- ]
- )
+ return cls(*[
+ np.concatenate([getattr(p, k) for p in parts])
+ for k in (
+ "source",
+ "trial",
+ "onset_line",
+ "size_class",
+ "size",
+ )
+ ])
def __len__(self) -> int:
- """Number of events."""
+ """Return the number of events.
+
+ Returns
+ -------
+ int
+ The number of events.
+ """
return int(self.source.size)
- def select(self, mask) -> "Events":
- """The events where ``mask`` is true."""
+ def select(self, mask: np.ndarray) -> Events:
+ """Select the events where mask is true.
+
+ Returns
+ -------
+ Events
+ The selected events.
+ """
return Events(
self.source[mask],
self.trial[mask],
@@ -440,13 +477,13 @@ def draw_events(
"""Random events of each source in one trial.
Each source's onsets form a renewal process: the first falls an
- exponential interval (mean ``1 / rate_hz``) after the trial's first line
- plus ``edge_s``, each next one ``min_interval_s`` plus an exponential
+ exponential interval (mean 1 / rate_hz) after the trial's first line
+ plus edge_s, each next one min_interval_s plus an exponential
interval after the previous; onsets later than the last line minus
- ``edge_s`` are dropped. Sizes are drawn independently from the size
+ edge_s are dropped. Sizes are drawn independently from the size
classes.
- With ``sync_share`` above 0 one such train, at that share of the rate,
+ With sync_share above 0 one such train, at that share of the rate,
is drawn first and given to every source (the same onsets, each
source's sizes its own); the sources' own trains have the rest of the
rate, and an own onset within the dead time of a common one is dropped.
@@ -481,8 +518,16 @@ def draw_events(
span = hi - lo
n_draw = int(span / (mean_gap + dead) * 1.5) + 20
- def train(mean, n):
- """Onsets of one renewal train and the draw size it needed."""
+ def train(mean: float, n: int) -> tuple[np.ndarray, int]:
+ """Onsets of one renewal train and the draw size it needed.
+
+ Returns
+ -------
+ onsets : np.ndarray
+ Onset lines of the train, within the trial's usable range.
+ n : int
+ The number of gaps that had to be drawn to cover the range.
+ """
while True:
gaps = rng.exponential(mean, n) + dead
gaps[0] -= dead
@@ -508,9 +553,7 @@ def train(mean, n):
before = np.abs(t - common[np.maximum(k - 1, 0)])
t = t[np.minimum(after, before) >= dead]
t = np.sort(np.concatenate([t, common]))
- cls = rng.choice(
- len(settings.size_classes), t.size, p=settings.weights
- )
+ cls = rng.choice(len(settings.size_classes), t.size, p=settings.weights)
parts.append(
Events(
np.full(t.size, j, dtype=np.int64),
@@ -526,7 +569,7 @@ def train(mean, n):
def event_traces(
events: Events,
n_sources: int,
- lines: Tuple[int, int],
+ lines: tuple[int, int],
line_period_s: float,
settings: InjectionSettings,
) -> np.ndarray:
@@ -548,21 +591,19 @@ def event_traces(
Returns
-------
ndarray of float64
- ``(sources, lines)``: sum of size times time course of each
+ (sources, lines): sum of size times time course of each
source's events, in size units.
"""
lo, hi = int(lines[0]), int(lines[1])
out = np.zeros((n_sources, hi - lo + 1))
extent = kernel_extent_s(settings) / line_period_s
for j, t0, a in zip(events.source, events.onset_line, events.size):
- l0 = max(lo, int(math.ceil(t0)))
- l1 = min(hi, int(math.floor(t0 + extent)))
+ l0 = max(lo, math.ceil(t0))
+ l1 = min(hi, math.floor(t0 + extent))
if l1 < l0:
continue
u = (np.arange(l0, l1 + 1) - t0) * line_period_s
- out[j, l0 - lo : l1 - lo + 1] += a * time_course(
- u, settings.tau_s, settings.rise_s
- )
+ out[j, l0 - lo : l1 - lo + 1] += a * time_course(u, settings.tau_s, settings.rise_s)
return out
@@ -573,7 +614,7 @@ class GaussianFootprint:
"""A Gaussian footprint with a peak of 1 at the source position.
Footprints are callables of row and column offsets from the source with
- a ``radius`` (zero beyond it) and a ``peak_offset`` (where their maximum
+ a radius (zero beyond it) and a peak_offset (where their maximum
is, relative to the source).
Parameters
@@ -592,23 +633,35 @@ def __init__(
self,
sigma_px: float = 1.33,
radius_sigmas: float = 4.0,
- sigma_c_px: Optional[float] = None,
- ):
+ sigma_c_px: float | None = None,
+ ) -> None:
"""Store the widths and the support radius."""
sc = sigma_px if sigma_c_px is None else sigma_c_px
self.sigma = (float(sigma_px), float(sc))
self.radius = float(radius_sigmas) * max(self.sigma)
self.peak_offset = (0.0, 0.0)
- def __call__(self, dr, dc) -> np.ndarray:
- """Value at row and column offsets from the source."""
+ def __call__(self, dr: ArrayLike, dc: ArrayLike) -> np.ndarray:
+ """Value at row and column offsets from the source.
+
+ Returns
+ -------
+ np.ndarray
+ The footprint values, 0 beyond radius.
+ """
dr = np.asarray(dr, dtype=np.float64)
dc = np.asarray(dc, dtype=np.float64)
q = (dr / self.sigma[0]) ** 2 + (dc / self.sigma[1]) ** 2
return np.where(dr**2 + dc**2 > self.radius**2, 0.0, np.exp(-0.5 * q))
def describe(self) -> dict:
- """Parameters, as stored in the truth file."""
+ """Parameters, as stored in the truth file.
+
+ Returns
+ -------
+ dict
+ kind, sigma_rc and radius_px.
+ """
return {
"kind": self.kind,
"sigma_rc": list(self.sigma),
@@ -624,14 +677,20 @@ class ImageFootprint:
image : array_like
Non-negative weights on a pixel grid; scaled to a maximum of 1.
center : (float, float), optional
- Zero-based ``(row, col)`` of the image that sits on the source
+ Zero-based (row, col) of the image that sits on the source
position (default: the image's centre).
"""
kind = "image"
- def __init__(self, image, center: Optional[Sequence[float]] = None):
- """Normalize the image and find its support radius."""
+ def __init__(self, image: ArrayLike, center: Sequence[float] | None = None) -> None:
+ """Normalize the image and find its support radius.
+
+ Raises
+ ------
+ ValueError
+ If the image is not 2-D, has negative values, or is all 0.
+ """
img = np.asarray(image, dtype=np.float64)
if img.ndim != 2 or np.nanmin(img) < 0 or np.nanmax(img) <= 0:
raise ValueError("a footprint image must be 2-D, >= 0, not all 0")
@@ -641,27 +700,35 @@ def __init__(self, image, center: Optional[Sequence[float]] = None):
center = ((h - 1) / 2.0, (w - 1) / 2.0)
self.center = (float(center[0]), float(center[1]))
corners = np.array([[0, 0], [0, w - 1], [h - 1, 0], [h - 1, w - 1]])
- self.radius = float(
- np.max(np.hypot(*(corners - np.array(self.center)).T))
- )
+ self.radius = float(np.max(np.hypot(*(corners - np.array(self.center)).T)))
top = np.unravel_index(np.argmax(self.image), self.image.shape)
self.peak_offset = (
float(top[0] - self.center[0]),
float(top[1] - self.center[1]),
)
- def __call__(self, dr, dc) -> np.ndarray:
- """Value at row and column offsets from the source (0 outside)."""
+ def __call__(self, dr: ArrayLike, dc: ArrayLike) -> np.ndarray:
+ """Value at row and column offsets from the source (0 outside).
+
+ Returns
+ -------
+ np.ndarray
+ The interpolated footprint values, in the shape of the offsets.
+ """
dr = np.asarray(dr, dtype=np.float64)
dc = np.asarray(dc, dtype=np.float64)
coords = [self.center[0] + dr.ravel(), self.center[1] + dc.ravel()]
- out = ndimage.map_coordinates(
- self.image, coords, order=1, mode="constant", cval=0.0
- )
+ out = ndimage.map_coordinates(self.image, coords, order=1, mode="constant", cval=0.0)
return out.reshape(dr.shape)
def describe(self) -> dict:
- """Parameters, as stored in the truth file."""
+ """Parameters, as stored in the truth file.
+
+ Returns
+ -------
+ dict
+ kind, center_rc and radius_px.
+ """
return {
"kind": self.kind,
"center_rc": list(self.center),
@@ -675,7 +742,7 @@ def peak_pixels(positions: np.ndarray, footprints: Sequence) -> np.ndarray:
Returns
-------
ndarray of int
- ``(sources, 2)`` zero-based ``(row, col)``.
+ (sources, 2) zero-based (row, col).
"""
pos = np.asarray(positions, dtype=np.float64).reshape(-1, 2)
off = np.array(
@@ -685,15 +752,19 @@ def peak_pixels(positions: np.ndarray, footprints: Sequence) -> np.ndarray:
return np.rint(pos + off).astype(np.int64)
-def footprint_patch(footprint, position, half: int) -> Tuple[np.ndarray, list]:
- """A footprint on the integer pixels around a position.
+def footprint_patch(
+ footprint: Callable[[ArrayLike, ArrayLike], np.ndarray],
+ position: Sequence[float] | np.ndarray,
+ half: int,
+) -> tuple[np.ndarray, list]:
+ """Sample a footprint on the integer pixels around a position.
Returns
-------
patch : ndarray
- ``(2 half + 1, 2 half + 1)`` values at pixels ``origin + (i, j)``.
+ (2 half + 1, 2 half + 1) values at pixels origin + (i, j).
origin : list of int
- Zero-based ``(row, col)`` of the patch's first pixel.
+ Zero-based (row, col) of the patch's first pixel.
"""
r0 = int(round(position[0])) - half
c0 = int(round(position[1])) - half
@@ -720,7 +791,7 @@ class PhotonGain:
quarter of slots over their photons, counted from each slot's share
of empty samples (Poisson).
n_slots : int
- Slots pooled for ``raw_per_photon``.
+ Slots pooled for raw_per_photon.
cycles : (int, int)
Zero-based cycle range used.
channel : int
@@ -730,11 +801,17 @@ class PhotonGain:
raw_per_photon: float
mean_pulse: float
n_slots: int
- cycles: Tuple[int, int]
+ cycles: tuple[int, int]
channel: int
def describe(self) -> dict:
- """Fields, as stored in the truth file."""
+ """Fields, as stored in the truth file.
+
+ Returns
+ -------
+ dict
+ The dataclass fields, with cycles as a list, plus a method description.
+ """
out = asdict(self)
out["cycles"] = list(self.cycles)
out["method"] = (
@@ -747,7 +824,7 @@ def describe(self) -> dict:
def measure_raw_per_photon(
layout: RasterLayout,
channel: int = 0,
- cycles: Optional[Tuple[int, int]] = None,
+ cycles: tuple[int, int] | None = None,
max_cycles: int = 1000,
slots_per_read: int = 8192,
) -> PhotonGain:
@@ -760,7 +837,7 @@ def measure_raw_per_photon(
channel : int
Zero-based channel.
cycles : (int, int), optional
- Zero-based cycle range (default: the first ``max_cycles``).
+ Zero-based cycle range (default: the first max_cycles).
max_cycles : int
Cycles used by default.
slots_per_read : int
@@ -769,6 +846,11 @@ def measure_raw_per_photon(
Returns
-------
PhotonGain
+
+ Raises
+ ------
+ ValueError
+ If the cycle range holds fewer than 3 cycles, or if no slot has photons.
"""
if cycles is None:
cycles = (0, min(layout.num_cycles, max_cycles))
@@ -823,10 +905,15 @@ def measure_raw_per_photon(
def labeled_pixels(mean_im: np.ndarray, factor: float = 3.0) -> np.ndarray:
- """Labeled (dendrite) pixels of a mean image, as SILo's ``loadTrial``.
+ """Labeled (dendrite) pixels of a mean image, as SILo's loadTrial.
The 3 x 3 median of the image (pixels without data read as 0) above
- ``factor`` times its 25th percentile over pixels with data.
+ factor times its 25th percentile over pixels with data.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean array of the image's shape, true at the labeled pixels.
"""
m = np.asarray(mean_im, dtype=np.float64)
data = np.isfinite(m)
@@ -841,16 +928,16 @@ def place_sources(
n_sources: int,
rng: np.random.Generator,
settings: PlacementSettings = PlacementSettings(),
- valid: Optional[np.ndarray] = None,
- exclude_rc: Optional[np.ndarray] = None,
- keep_apart_rc: Optional[np.ndarray] = None,
-) -> Tuple[np.ndarray, int]:
+ valid: np.ndarray | None = None,
+ exclude_rc: np.ndarray | None = None,
+ keep_apart_rc: np.ndarray | None = None,
+) -> tuple[np.ndarray, int]:
"""Random source positions on labeled pixels, apart from each other.
Parameters
----------
mean_im : ndarray
- ``(rows, cols)`` mean image of the injected channel in the path
+ (rows, cols) mean image of the injected channel in the path
frame (NaN without data).
n_sources : int
Sources wanted; fewer are returned if the candidates run out.
@@ -859,20 +946,20 @@ def place_sources(
settings : PlacementSettings
Distances and labeling.
valid : ndarray of bool, optional
- Pixels with data in every trial (default: finite ``mean_im``).
+ Pixels with data in every trial (default: finite mean_im).
exclude_rc : ndarray, optional
- ``(n, 2)`` existing source positions to keep away from
- (``exclude_px``).
+ (n, 2) existing source positions to keep away from
+ (exclude_px).
keep_apart_rc : ndarray, optional
- ``(n, 2)`` positions of sources of this placement that are placed
- already: the new ones keep ``min_separation_px`` from them, as they
+ (n, 2) positions of sources of this placement that are placed
+ already: the new ones keep min_separation_px from them, as they
do from each other. Candidates too near are dropped before any is
chosen, so they cannot stand in a free candidate's way.
Returns
-------
positions : ndarray of float
- ``(k, 2)`` zero-based ``(row, col)``, integers, ``k <= n_sources``.
+ (k, 2) zero-based (row, col), integers, k <= n_sources.
n_candidates : int
Pixels that met the labeling, edge and exclusion rules.
"""
@@ -891,35 +978,48 @@ def place_sources(
d, _ = cKDTree(np.asarray(keep_apart_rc, np.float64)).query(rc)
rc = rc[d >= settings.min_separation_px]
n_cand = int(rc.shape[0])
- chosen: List[np.ndarray] = []
+ chosen: list[np.ndarray] = []
tree_pts = np.zeros((0, 2))
for i in rng.permutation(n_cand):
if len(chosen) >= n_sources:
break
p = rc[i]
- if (
- tree_pts.size
- and np.min(np.hypot(*(tree_pts - p).T))
- < settings.min_separation_px
- ):
+ if tree_pts.size and np.min(np.hypot(*(tree_pts - p).T)) < settings.min_separation_px:
continue
chosen.append(p)
tree_pts = np.vstack([tree_pts, p])
return np.array(chosen).reshape(-1, 2), n_cand
-def _highpass(x: np.ndarray, sigma: float) -> Tuple[np.ndarray, np.ndarray]:
- """An image minus its Gaussian background (0 without data), and its
- data mask."""
+def _highpass(x: np.ndarray, sigma: float) -> tuple[np.ndarray, np.ndarray]:
+ """Subtract an image's Gaussian background (0 without data).
+
+ Also returns its data mask.
+
+ Returns
+ -------
+ filtered : np.ndarray
+ The image minus its Gaussian background, 0 where it has no data.
+ ok : np.ndarray
+ Boolean mask of the pixels with data.
+ """
x = np.asarray(x, dtype=np.float64)
ok = np.isfinite(x)
fill = np.where(ok, x, np.nanmean(x) if ok.any() else 0.0)
return np.where(ok, fill - ndimage.gaussian_filter(fill, sigma), 0.0), ok
-def _ncc(a, va, b, vb, dr: int, dc: int) -> float:
- """Normalized correlation of ``a(p)`` and ``b(p + (dr, dc))`` where both
- have data (-inf if they share fewer than 100 pixels)."""
+def _ncc(a: np.ndarray, va: np.ndarray, b: np.ndarray, vb: np.ndarray, dr: int, dc: int) -> float:
+ """Compute the normalized correlation of a(p) and b(p + (dr, dc)).
+
+ Only where both have data (-inf if they share fewer than 100 pixels).
+
+ Returns
+ -------
+ float
+ The correlation, or -inf if the images share fewer than 100 pixels with data or have
+ no variance there.
+ """
h, w = a.shape
ra = slice(max(0, -dr), min(h, h - dr))
ca = slice(max(0, -dc), min(w, w - dc))
@@ -935,16 +1035,30 @@ def _ncc(a, va, b, vb, dr: int, dc: int) -> float:
def _vertex(c_m: float, c_0: float, c_p: float) -> float:
- """Offset of a parabola's vertex through three equally spaced values."""
+ """Offset of a parabola's vertex through three equally spaced values.
+
+ Returns
+ -------
+ float
+ The vertex offset from the middle point, clipped to -0.5 to 0.5; 0 if the parabola
+ has no maximum.
+ """
den = c_m - 2 * c_0 + c_p
if not np.isfinite(den) or den >= 0:
return 0.0
return float(np.clip(0.5 * (c_m - c_p) / den, -0.5, 0.5))
-def fit_shape(image: np.ndarray, shape) -> np.ndarray:
- """An image cropped or NaN-padded at its bottom and right to ``shape``
- (registered grids share their top-left corner, as in SILo)."""
+def fit_shape(image: np.ndarray, shape: Sequence[int]) -> np.ndarray:
+ """Crop or NaN-pad an image at its bottom and right to shape.
+
+ Registered grids share their top-left corner, as in SILo.
+
+ Returns
+ -------
+ np.ndarray
+ The image cropped or NaN-padded to shape.
+ """
out = np.full(shape, np.nan)
h, w = min(shape[0], image.shape[0]), min(shape[1], image.shape[1])
out[:h, :w] = image[:h, :w]
@@ -962,7 +1076,7 @@ def align_images(
Parameters
----------
reference, image : ndarray
- ``(rows, cols)``, NaN without data; ``image`` is cropped or padded to
+ (rows, cols), NaN without data; image is cropped or padded to
the reference's shape.
max_shift : int
Largest integer shift searched.
@@ -972,9 +1086,14 @@ def align_images(
Returns
-------
ndarray of float
- ``s = (dr, dc)`` such that ``image(p + s)`` matches
- ``reference(p)``, refined to subpixel by parabolas through the
+ s = (dr, dc) such that image(p + s) matches
+ reference(p), refined to subpixel by parabolas through the
correlation peak.
+
+ Raises
+ ------
+ ValueError
+ If the images do not overlap.
"""
a, va = _highpass(reference, highpass_px)
b, vb = _highpass(fit_shape(image, a.shape), highpass_px)
@@ -989,20 +1108,27 @@ def align_images(
return np.array([i - max_shift + di, j - max_shift + dj])
-def shift_image(image: np.ndarray, shift, shape=None) -> np.ndarray:
- """``out(p) = image(p + shift)`` (bilinear; NaN where undefined).
+def shift_image(
+ image: np.ndarray,
+ shift: Sequence[float] | np.ndarray,
+ shape: Sequence[int] | None = None,
+) -> np.ndarray:
+ """out(p) = image(p + shift) (bilinear; NaN where undefined).
- ``shape`` sets the output grid (default: the image's); the whole image
+ shape sets the output grid (default: the image's); the whole image
is sampled, whatever its size.
+
+ Returns
+ -------
+ np.ndarray
+ The shifted image on the output grid, NaN where undefined.
"""
img = np.asarray(image, dtype=np.float64)
ok = np.isfinite(img).astype(np.float64)
shape = img.shape if shape is None else tuple(shape)
rr, cc = np.mgrid[0 : shape[0], 0 : shape[1]].astype(np.float64)
coords = [rr + shift[0], cc + shift[1]]
- val = ndimage.map_coordinates(
- np.where(ok > 0, img, 0.0), coords, order=1, cval=0.0
- )
+ val = ndimage.map_coordinates(np.where(ok > 0, img, 0.0), coords, order=1, cval=0.0)
wt = ndimage.map_coordinates(ok, coords, order=1, cval=0.0)
out = np.full(shape, np.nan)
good = wt > 0.999
@@ -1024,16 +1150,16 @@ class Alignment:
ds_frames : ndarray of float
Line times of the registered (DS) frames.
motion_r, motion_c : ndarray of float
- ``motionDSr``, ``motionDSc`` (NaN for missing frames).
+ motionDSr, motionDSc (NaN for missing frames).
trim_r0, trim_c0 : int
One-based first DMD row and column of the registration window.
margin : int
- ``maxshift``: padding of the registered grid.
+ maxshift: padding of the registered grid.
compensation : dict or None
- ``refOffset``, ``frameRefX``, ``frameRefY``, ``mapping`` and
- ``yLead`` when the registration undid the online correction.
+ refOffset, frameRefX, frameRefY, mapping and
+ yLead when the registration undid the online correction.
mean_im : ndarray of float
- ``(channels, rows, cols)`` mean registered image.
+ (channels, rows, cols) mean registered image.
"""
path: str
@@ -1043,23 +1169,40 @@ class Alignment:
trim_r0: int
trim_c0: int
margin: int
- compensation: Optional[dict]
+ compensation: dict | None
mean_im: np.ndarray
@property
- def shape(self) -> Tuple[int, int]:
- """Registered frame ``(rows, cols)``."""
+ def shape(self) -> tuple[int, int]:
+ """Registered frame (rows, cols).
+
+ Returns
+ -------
+ tuple[int, int]
+ The number of rows and columns of the registered frame.
+ """
return self.mean_im.shape[1], self.mean_im.shape[2]
-def read_alignment(path: Union[str, Path]) -> Alignment:
+def read_alignment(path: str | Path) -> Alignment:
"""Read the fields injection needs from an alignment file.
Works for MATLAB- and Python-written files (both column-major).
+
+ Returns
+ -------
+ Alignment
+ The fields injection uses from the file.
"""
- def vec(ds):
- """A dataset as a flat float vector."""
+ def vec(ds: h5py.Dataset) -> np.ndarray:
+ """Read a dataset as a flat float vector.
+
+ Returns
+ -------
+ np.ndarray
+ The dataset's values as a flat float64 vector.
+ """
return np.asarray(ds[()], dtype=np.float64).ravel()
with h5py.File(path, "r") as f:
@@ -1089,10 +1232,15 @@ def vec(ds):
def _continuous(alignment: Alignment) -> np.ndarray:
- """``(2, frames)`` continuous motion of every DS frame (NaN if missing).
+ """(2, frames) continuous motion of every DS frame (NaN if missing).
+
+ With compensation, the recorded motion plus mapping @ (frameRef -
+ refOffset): the motion relative to the frame of refOffset.
- With compensation, the recorded motion plus ``mapping @ (frameRef -
- refOffset)``: the motion relative to the frame of ``refOffset``.
+ Returns
+ -------
+ np.ndarray
+ The (2, frames) motion (rows, then columns) of every DS frame.
"""
move = np.stack([alignment.motion_r, alignment.motion_c])
comp = alignment.compensation
@@ -1102,14 +1250,19 @@ def _continuous(alignment: Alignment) -> np.ndarray:
return move
-def continuous_motion(alignment: Alignment):
- """DS frame times and the motion to interpolate (``onlineCompensation``).
+def continuous_motion(alignment: Alignment) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """DS frame times and the motion to interpolate (onlineCompensation).
Returns
-------
times, motion_r, motion_c : ndarray
Frames with finite motion only. With compensation, the motion is
- relative to the frame of ``refOffset`` (as SILo's ``loadTrial``).
+ relative to the frame of refOffset (as SILo's loadTrial).
+
+ Raises
+ ------
+ ValueError
+ If no frame has motion.
"""
t = alignment.ds_frames
mr, mc = _continuous(alignment)
@@ -1119,38 +1272,34 @@ def continuous_motion(alignment: Alignment):
return t[ok], mr[ok], mc[ok]
-def motion_at(alignment: Alignment, lines) -> np.ndarray:
- """Continuous motion at line times (``pchip``, extrapolated).
+def motion_at(alignment: Alignment, lines: ArrayLike) -> np.ndarray:
+ """Continuous motion at line times (pchip, extrapolated).
Returns
-------
ndarray
- ``(2, n)`` rows and columns.
+ (2, n) rows and columns.
"""
t, mr, mc = continuous_motion(alignment)
lines = np.asarray(lines, dtype=np.float64)
if t.size == 1:
- return np.stack(
- [np.full(lines.shape, mr[0]), np.full(lines.shape, mc[0])]
- )
- return np.stack(
- [PchipInterpolator(t, m, extrapolate=True)(lines) for m in (mr, mc)]
- )
+ return np.stack([np.full(lines.shape, mr[0]), np.full(lines.shape, mc[0])])
+ return np.stack([PchipInterpolator(t, m, extrapolate=True)(lines) for m in (mr, mc)])
@dataclass
class TrialGeometry:
"""Registered position of the samples of every line of a trial.
- A sample of DMD pixel ``(r, c)`` (zero-based) on line ``l`` lies at
- ``(r, c) + shift[l - first_line]`` in the trial's registered frame.
+ A sample of DMD pixel (r, c) (zero-based) on line l lies at
+ (r, c) + shift[l - first_line] in the trial's registered frame.
Attributes
----------
first_line : int
- One-based line of ``shift[0]``.
+ One-based line of shift[0].
shift : ndarray of float
- ``(lines, 2)`` row and column displacement.
+ (lines, 2) row and column displacement.
compensated : bool
Whether the registration undid the online correction.
"""
@@ -1166,7 +1315,7 @@ def last_line(self) -> int:
def trial_geometry(
- layout: RasterLayout, alignment: Alignment, lines: Tuple[int, int]
+ layout: RasterLayout, alignment: Alignment, lines: tuple[int, int]
) -> TrialGeometry:
"""Where each line's samples lie in the trial's registered frame.
@@ -1199,10 +1348,21 @@ def trial_geometry(
return TrialGeometry(lo, np.ascontiguousarray(shift.T), comp is not None)
-def trial_lines(layout: RasterLayout, first, last) -> Tuple[int, int]:
- """Whole lines of a trial's (possibly fractional) line range."""
- lo = max(1, int(math.ceil(float(first))))
- hi = min(layout.total_lines, int(math.floor(float(last))))
+def trial_lines(layout: RasterLayout, first: float, last: float) -> tuple[int, int]:
+ """Whole lines of a trial's (possibly fractional) line range.
+
+ Returns
+ -------
+ tuple[int, int]
+ The first and last whole one-based line of the range.
+
+ Raises
+ ------
+ ValueError
+ If the line range holds no whole line.
+ """
+ lo = max(1, math.ceil(float(first)))
+ hi = min(layout.total_lines, math.floor(float(last)))
if hi < lo:
raise ValueError(f"trial lines {first}..{last} hold no whole line")
return lo, hi
@@ -1221,13 +1381,13 @@ class SampleModel:
geometry : TrialGeometry
Registered position of each line's samples.
positions : ndarray
- ``(sources, 2)`` source positions in the trial's registered frame.
+ (sources, 2) source positions in the trial's registered frame.
footprints : sequence
One footprint per source (callables of row and column offsets with
- a ``radius``).
+ a radius).
traces : ndarray
- ``(sources, lines)`` amplitude of each source at each line of
- ``geometry`` (size units).
+ (sources, lines) amplitude of each source at each line of
+ geometry (size units).
photon_scale : float
Raw counts per size unit.
@@ -1246,8 +1406,15 @@ def __init__(
footprints: Sequence,
traces: np.ndarray,
photon_scale: float = PHOTON_SCALE,
- ):
- """Find the (slot, source) pairs within reach."""
+ ) -> None:
+ """Find the (slot, source) pairs within reach.
+
+ Raises
+ ------
+ ValueError
+ If the positions, footprints and traces do not agree in the number of sources or
+ lines.
+ """
self.layout = layout
self.geometry = geometry
self.positions = np.asarray(positions, dtype=np.float64).reshape(-1, 2)
@@ -1281,18 +1448,24 @@ def __init__(
self.pair_src = np.concatenate(pj) if pj else np.zeros(0, np.int64)
self.slots, self.pair_k = np.unique(pair_slot, return_inverse=True)
self._r0, self._c0 = r0[self.slots], c0[self.slots]
- groups: Dict[int, list] = {}
+ groups: dict[int, list] = {}
for g, j in enumerate(self.pair_src):
groups.setdefault(id(self.footprints[j]), []).append(g)
self._groups = [np.array(v) for v in groups.values()]
def lines(self, cycles: np.ndarray) -> np.ndarray:
- """One-based line of each (cycle, slot) of :attr:`slots`."""
+ """One-based line of each (cycle, slot) of :attr:`slots`.
+
+ Returns
+ -------
+ np.ndarray
+ (cycles, slots) one-based line numbers.
+ """
p = self.layout.lines_per_cycle
return cycles[:, None] * p + self.layout.slot_line[self.slots][None, :]
- def expected(self, cycles) -> np.ndarray:
- """Expected extra raw counts of the reachable slots.
+ def expected(self, cycles: ArrayLike) -> np.ndarray:
+ """Compute the expected extra raw counts of the reachable slots.
Parameters
----------
@@ -1302,7 +1475,7 @@ def expected(self, cycles) -> np.ndarray:
Returns
-------
ndarray of float64
- ``(cycles, slots)``; 0 on lines outside the geometry.
+ (cycles, slots); 0 on lines outside the geometry.
"""
cycles = np.asarray(cycles, dtype=np.int64).ravel()
n_c, n_k = cycles.size, self.slots.size
@@ -1323,9 +1496,7 @@ def expected(self, cycles) -> np.ndarray:
dc = self._c0[k][None, :] + sh_c[:, k] - self.positions[j, 1]
v = fp(dr, dc) * self.traces[j[None, :], li[:, k]]
v[~inside[:, k]] = 0.0
- out += np.bincount(
- (rows + k[None, :]).ravel(), v.ravel(), minlength=n_c * n_k
- )
+ out += np.bincount((rows + k[None, :]).ravel(), v.ravel(), minlength=n_c * n_k)
return out.reshape(n_c, n_k) * self.photon_scale
@@ -1369,8 +1540,20 @@ class InjectionStats:
render_seconds: float = 0.0
-def _file_spans(layout: RasterLayout, c0: int, c1: int):
- """Yield (file index, first local cycle, count, first global cycle)."""
+def _file_spans(layout: RasterLayout, c0: int, c1: int) -> Iterator[tuple[int, int, int, int]]:
+ """Yield (file index, first local cycle, count, first global cycle).
+
+ Yields
+ ------
+ file : int
+ Index of the file.
+ first : int
+ First cycle to use, local to the file.
+ count : int
+ Number of cycles to use from the file.
+ start : int
+ The first of those cycles, counted over all the files.
+ """
ends = np.cumsum(layout.file_cycles)
starts = ends - layout.file_cycles
for f, (s, e) in enumerate(zip(starts, ends)):
@@ -1392,23 +1575,28 @@ def inject_samples(
Parameters
----------
layout : RasterLayout
- The recording to change (its ``files`` are opened read-write).
+ The recording to change (its files are opened read-write).
model : SampleModel
Expected extra raw counts.
raw_per_photon : float
- Raw units per photon ``g``.
+ Raw units per photon g.
channel : int
Zero-based channel changed.
seed_key : sequence of int
- ``(seed, path, trial)``: each cycle's draws come from their own
+ (seed, path, trial): each cycle's draws come from their own
generator keyed by it and the cycle, so they do not depend on
- ``chunk_cycles``.
+ chunk_cycles.
chunk_cycles : int
Cycles evaluated at a time.
Returns
-------
InjectionStats
+
+ Raises
+ ------
+ ValueError
+ If chunk_cycles is below 1, or if channel is not recorded.
"""
if int(chunk_cycles) < 1:
raise ValueError("chunk_cycles must be at least 1")
@@ -1425,11 +1613,7 @@ def inject_samples(
c_lo = (geo.first_line - 1) // p
c_hi = (geo.last_line - 1) // p + 1
li = layout.slot_line[model.slots] - 1
- word = (
- layout.row_base[li]
- + channel * layout.n_per_channel[li]
- + layout.slot_pos[model.slots]
- )
+ word = layout.row_base[li] + channel * layout.n_per_channel[li] + layout.slot_pos[model.slots]
seed, *key = (int(k) for k in seed_key)
for f, local, count, first in _file_spans(layout, c_lo, c_hi):
mm = np.memmap(
@@ -1454,9 +1638,7 @@ def inject_samples(
stats.expected_photons_invalid += float(lam[i][bad].sum())
if nz.size == 0:
continue
- inc = np.floor(n[nz] * g + rng.random(nz.size)).astype(
- np.int64
- )
+ inc = np.floor(n[nz] * g + rng.random(nz.size)).astype(np.int64)
ok = ~bad[nz]
nz, inc = nz[ok], inc[ok]
new = np.minimum(old[nz] + inc, SAMPLE_MAX)
@@ -1476,8 +1658,19 @@ def inject_samples(
# ------------------------------------------------------------ session level
-def meta_path(dat: Union[str, Path]) -> Path:
- """The ``.meta`` file of a ``.dat`` file (as GIAnT's ``loadMetadata``)."""
+def meta_path(dat: str | Path) -> Path:
+ """Return the .meta file of a .dat file (as GIAnT's loadMetadata).
+
+ Returns
+ -------
+ Path
+ The .meta file next to dat, named after the file's DMD.
+
+ Raises
+ ------
+ ValueError
+ If the file name does not name its DMD.
+ """
dat = Path(dat)
m = re.search(r"DMD\d", dat.stem)
if m is None:
@@ -1486,7 +1679,7 @@ def meta_path(dat: Union[str, Path]) -> Path:
def _copy_recording(layout: RasterLayout, dest: Path, done: set) -> None:
- """Copy a recording's data files (and ``.meta``) once into ``dest``."""
+ """Copy a recording's data files (and .meta) once into dest."""
dest.mkdir(parents=True, exist_ok=True)
for src in [Path(p) for p in layout.files]:
if src.name not in done:
@@ -1503,18 +1696,20 @@ def _copy_recording(layout: RasterLayout, dest: Path, done: set) -> None:
log.warning("%s has no %s; not copied", src.name, meta.name)
-def _recording_files(names, keep, paths, data_dir: Path) -> dict:
+def _recording_files(
+ names: np.ndarray, keep: np.ndarray, paths: Sequence[int], data_dir: Path
+) -> dict:
"""Each injected cell's data files; reject copies that would collide.
Returns
-------
dict
- ``{zero-based path: {zero-based trial: tuple of resolved files}}``.
+ {zero-based path: {zero-based trial: tuple of resolved files}}.
Raises
------
ValueError
- If two different originals (data or ``.meta`` files) would be
+ If two different originals (data or .meta files) would be
copied to the same name in the copy's flat folder.
"""
out, origin = {}, {}
@@ -1538,21 +1733,31 @@ def _recording_files(names, keep, paths, data_dir: Path) -> dict:
for src in [f] + extra:
name = Path(src).name
if origin.setdefault(name, src) != src:
- raise ValueError(
- f"{origin[name]} and {src} would both be copied "
- f"as {name}"
- )
+ raise ValueError(f"{origin[name]} and {src} would both be copied as {name}")
return out
def _relocated(layout: RasterLayout, dest: Path) -> RasterLayout:
- """The same layout with its files in ``dest``."""
+ """Return the same layout with its files in dest.
+
+ Returns
+ -------
+ RasterLayout
+ A copy of layout whose files are the same names in dest.
+ """
files = tuple(str(dest / Path(p).name) for p in layout.files)
return replace(layout, files=files)
-def _cols(value, keep: np.ndarray, n: int):
- """Columns ``keep`` of a per-trial value (others unchanged)."""
+def _cols(value: object, keep: np.ndarray, n: int) -> object:
+ """Columns keep of a per-trial value (others unchanged).
+
+ Returns
+ -------
+ object
+ The columns keep of value if it is a 2-D array with n columns, else
+ value unchanged.
+ """
arr = np.asarray(value)
if arr.ndim == 2 and arr.shape[1] == n:
return arr[:, keep]
@@ -1564,15 +1769,20 @@ def write_copy_table(
keep: np.ndarray,
data_dir: Path,
save_dir: Path,
- paths: Optional[Sequence[int]] = None,
+ paths: Sequence[int] | None = None,
) -> Path:
- """The trial table of the injected copy (``save_dir/trial_table.h5``).
+ """Write the trial table of the injected copy (save_dir/trial_table.h5).
- The original's table with only the trials ``keep`` (zero-based columns),
- ``datadr`` and ``savedr`` pointing to the copy (absolute), no
+ The original's table with only the trials keep (zero-based columns),
+ datadr and savedr pointing to the copy (absolute), no
registration or extraction results, filenames reduced to the copies'
- names in ``data_dir``, and empty filenames for paths not in ``paths``
+ names in data_dir, and empty filenames for paths not in paths
(one-based DMDs; default all), whose files are not copied.
+
+ Returns
+ -------
+ Path
+ The written trial table, save_dir/trial_table.h5.
"""
n = np.atleast_2d(np.asarray(table["filename"], dtype=object)).shape[1]
out = {}
@@ -1600,18 +1810,29 @@ def write_copy_table(
return path
-def _grid(value, n_paths: int, n: int) -> np.ndarray:
- """A per-path, per-trial value as a ``(paths, trials)`` array."""
+def _grid(value: ArrayLike, n_paths: int, n: int) -> np.ndarray:
+ """Shape a per-path, per-trial value as a (paths, trials) array.
+
+ Returns
+ -------
+ np.ndarray
+ value reshaped to (n_paths, n).
+ """
return np.asarray(value).reshape(n_paths, n)
-def _frame_lines(first, last, line_hz: float, hz: float) -> np.ndarray:
- """``ceil(first:dt:last)`` (SILo's 200 Hz frame lines)."""
+def _frame_lines(first: float, last: float, line_hz: float, hz: float) -> np.ndarray:
+ """ceil(first:dt:last) (SILo's 200 Hz frame lines).
+
+ Returns
+ -------
+ np.ndarray
+ The frame lines as int64, the ceiling of the MATLAB range from first to last
+ in steps of line_hz / hz.
+ """
from ..registration.multiroi import matlab_colon
- return np.ceil(
- matlab_colon(float(first), line_hz / hz, float(last))
- ).astype(np.int64)
+ return np.ceil(matlab_colon(float(first), line_hz / hz, float(last))).astype(np.int64)
@dataclass
@@ -1621,11 +1842,11 @@ class PathPlan:
Attributes
----------
positions : ndarray
- ``(sources, 2)`` in the path frame.
+ (sources, 2) in the path frame.
footprints : list
One footprint per source.
trial_shift : ndarray
- ``(trials, 2)``: trial frame = path frame + shift.
+ (trials, 2): trial frame = path frame + shift.
mean_image : ndarray
Mean image of the injected channel in the path frame.
valid : ndarray of bool
@@ -1648,10 +1869,10 @@ def plan_path(
settings: InjectionSettings,
placement: PlacementSettings,
rng: np.random.Generator,
- positions: Optional[np.ndarray] = None,
- exclude_rc: Optional[np.ndarray] = None,
- trial_shift: Optional[np.ndarray] = None,
- footprints: Optional[Sequence] = None,
+ positions: np.ndarray | None = None,
+ exclude_rc: np.ndarray | None = None,
+ trial_shift: np.ndarray | None = None,
+ footprints: Sequence | None = None,
max_shift: int = 8,
) -> PathPlan:
"""Align a path's trials and place its sources.
@@ -1659,29 +1880,31 @@ def plan_path(
The path frame is the first alignment's registered frame. Trial shifts
are estimated from the mean images unless given; the path's mean image
is the mean of the trials' mean images moved into the path frame.
+
+ Returns
+ -------
+ PathPlan
+ The sources' positions and footprints, the trial shifts, the path's mean image and
+ valid-pixel mask, and the number of placement candidates.
+
+ Raises
+ ------
+ ValueError
+ If there is not one trial shift per trial, or not one footprint per source.
"""
ch = settings.channel
ref = alignments[0].mean_im[ch]
if trial_shift is None:
- trial_shift = np.array(
- [
- (
- np.zeros(2)
- if k == 0
- else align_images(ref, a.mean_im[ch], max_shift)
- )
- for k, a in enumerate(alignments)
- ]
- )
+ trial_shift = np.array([
+ (np.zeros(2) if k == 0 else align_images(ref, a.mean_im[ch], max_shift))
+ for k, a in enumerate(alignments)
+ ])
trial_shift = np.asarray(trial_shift, dtype=np.float64).reshape(-1, 2)
if trial_shift.shape[0] != len(alignments):
raise ValueError("one trial shift per trial is needed")
- moved = np.stack(
- [
- shift_image(a.mean_im[ch], s, ref.shape)
- for a, s in zip(alignments, trial_shift)
- ]
- )
+ moved = np.stack([
+ shift_image(a.mean_im[ch], s, ref.shape) for a, s in zip(alignments, trial_shift)
+ ])
valid = np.all(np.isfinite(moved), axis=0)
with np.errstate(invalid="ignore"), warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning) # all-NaN pixels
@@ -1713,7 +1936,13 @@ def plan_path(
def _render_device(device: str) -> str:
- """``'auto'``: CUDA when available, else the CPU."""
+ """'auto': CUDA when available, else the CPU.
+
+ Returns
+ -------
+ str
+ The resolved device name.
+ """
from ..registration.multiroi import resolve_device
return str(resolve_device(device))
@@ -1725,20 +1954,20 @@ def expected_frames(
model: SampleModel,
frame_lines: np.ndarray,
pixels_rc: np.ndarray,
- shift_rc,
+ shift_rc: Sequence[float] | np.ndarray,
hz: float,
channel: int = 0,
device: str = "cpu",
) -> np.ndarray:
"""Noiseless registered frames of a sample model, at given pixels.
- The model's expected counts are formed into frames at ``frame_lines``
- as SILo's extraction forms them at ``hz`` (kernel ``ceil(line rate /
- hz)`` lines, the samples exactly at its reach and the recording's
+ The model's expected counts are formed into frames at frame_lines
+ as SILo's extraction forms them at hz (kernel ceil(line rate /
+ hz) lines, the samples exactly at its reach and the recording's
invalid samples, and those behind the DMD curtain, left out) and
resampled with the
registration's motion into the path frame (the trial frame moved by
- ``shift_rc``; see :func:`~giant_python.simulation.render.
+ shift_rc; see :func:`~giant_python.simulation.render.
iter_registered_frames`).
Parameters
@@ -1748,7 +1977,7 @@ def expected_frames(
frame_lines : ndarray of int
One-based frame times.
pixels_rc : ndarray of int
- ``(n, 2)`` zero-based pixels of the path frame; a pixel is NaN where
+ (n, 2) zero-based pixels of the path frame; a pixel is NaN where
its position in the trial's registered frame has no data.
shift_rc : (float, float)
Trial frame = path frame + shift.
@@ -1764,13 +1993,13 @@ def expected_frames(
Returns
-------
ndarray of float
- ``(n, frames)`` in raw counts (NaN where a pixel has no data).
+ (n, frames) in raw counts (NaN where a pixel has no data).
"""
from .render import iter_registered_frames
frame_lines = np.asarray(frame_lines, dtype=np.int64)
p = layout.lines_per_cycle
- dt = int(math.ceil((1.0 / layout.line_period_s) / hz))
+ dt = math.ceil((1.0 / layout.line_period_s) / hz)
reach = max(3 * dt, p)
c0 = max(0, (int(frame_lines.min()) - reach - 1) // p)
c1 = min(layout.num_cycles, (int(frame_lines.max()) + reach - 1) // p + 1)
@@ -1779,9 +2008,7 @@ def expected_frames(
samples = np.zeros((n_ch, layout.slot_line.size, c1 - c0), np.float32)
for a in range(c0, c1, 256):
cyc = np.arange(a, min(c1, a + 256))
- samples[-1][model.slots[:, None], (cyc - c0)[None, :]] = (
- model.expected(cyc).T
- )
+ samples[-1][model.slots[:, None], (cyc - c0)[None, :]] = model.expected(cyc).T
# as extraction reads them: samples behind the DMD curtain are invalid
orig = read_raster_samples(layout, (c0, c1), mask_unlit=True)
samples[-1][orig[channel] == INVALID_SAMPLE] = INVALID_SAMPLE
@@ -1793,9 +2020,7 @@ def expected_frames(
pix = np.asarray(pixels_rc, dtype=np.int64).reshape(-1, 2)
pix = pix + whole.astype(np.int64)
h, w = alignment.shape
- inside = (
- (pix[:, 0] >= 0) & (pix[:, 0] < h) & (pix[:, 1] >= 0) & (pix[:, 1] < w)
- )
+ inside = (pix[:, 0] >= 0) & (pix[:, 0] < h) & (pix[:, 1] >= 0) & (pix[:, 1] < w)
pr = np.clip(pix[:, 0], 0, h - 1)
pc = np.clip(pix[:, 1], 0, w - 1)
out = np.full((pix.shape[0], frame_lines.size), np.nan)
@@ -1819,7 +2044,7 @@ def expected_frames(
def overlap_classes(positions: np.ndarray, footprints: Sequence) -> np.ndarray:
"""Classes of sources whose footprints do not overlap (greedy colouring).
- Sources ``i`` and ``j`` overlap when they are closer than the sum of
+ Sources i and j overlap when they are closer than the sum of
their footprints' radii.
Returns
@@ -1843,7 +2068,7 @@ def calibrate_frame_peaks(
alignment: Alignment,
geometry: TrialGeometry,
positions: np.ndarray,
- shift_rc,
+ shift_rc: Sequence[float] | np.ndarray,
footprints: Sequence,
settings: InjectionSettings,
rng: np.random.Generator,
@@ -1853,29 +2078,29 @@ def calibrate_frame_peaks(
"""How much of an event's peak each source's frames keep.
Isolated unit events (tissue units) of every source are placed in a
- ``calibration_s`` stretch of the trial, at random phases of the frame
- grid; their noiseless frames at ``analyze_hz`` are formed as SILo forms
+ calibration_s stretch of the trial, at random phases of the frame
+ grid; their noiseless frames at analyze_hz are formed as SILo forms
them (:func:`expected_frames`), in the path frame. Sources whose
footprints overlap take turns (:func:`overlap_classes`), so that each
event is alone at its source's peak pixel.
- Raises
- ------
- ValueError
- If a source has no data at its peak pixel (``strict``).
-
Returns
-------
ndarray of float
Per source: the mean, over its events, of the event's largest frame
value at the source's peak pixel (the path-frame pixel nearest its
footprint's maximum, :func:`peak_pixels`), in units of
- ``photon_scale``. With ``strict=False`` a source without data at
+ photon_scale. With strict=False a source without data at
its peak pixel gets NaN instead of an error.
+
+ Raises
+ ------
+ ValueError
+ If a source has no data at its peak pixel (strict).
"""
period = layout.line_period_s
n_src = positions.shape[0]
- dt = int(math.ceil((1.0 / period) / settings.analyze_hz))
+ dt = math.ceil((1.0 / period) / settings.analyze_hz)
reach = max(3 * dt, layout.lines_per_cycle)
tail = peak_delay_s(settings.tau_s, settings.rise_s) + 6 * settings.tau_s
gap = tail / period + 2 * reach
@@ -1917,9 +2142,7 @@ def calibrate_frame_peaks(
settings.photon_scale,
)
step = (1.0 / period) / settings.analyze_hz
- fl = np.unique(np.ceil(np.arange(a - reach, b + gap, step))).astype(
- np.int64
- )
+ fl = np.unique(np.ceil(np.arange(a - reach, b + gap, step))).astype(np.int64)
vals = expected_frames(
layout,
alignment,
@@ -1938,12 +2161,9 @@ def calibrate_frame_peaks(
sel = (fl >= t0 - reach) & (fl <= t0 + tail / period)
if sel.any():
peaks[e] = np.nanmax(vals[j, sel])
- gain = np.array(
- [
- np.nanmean(peaks[src == j]) if np.any(src == j) else np.nan
- for j in range(n_src)
- ]
- )
+ gain = np.array([
+ np.nanmean(peaks[src == j]) if np.any(src == j) else np.nan for j in range(n_src)
+ ])
gain = gain / settings.photon_scale
bad = np.flatnonzero(~(gain > 0))
if bad.size and strict:
@@ -1956,8 +2176,18 @@ def calibrate_frame_peaks(
return gain
-def _inject_trial(ctx: dict, k: int, t: int) -> Tuple[dict, Events]:
- """Inject one trial-path (see :func:`inject_session`)."""
+def _inject_trial(ctx: dict, k: int, t: int) -> tuple[dict, Events]:
+ """Inject one trial-path (see :func:`inject_session`).
+
+ Returns
+ -------
+ detail : dict
+ The trial's record for the truth file: its numbers, lines, positions, frame lines,
+ injected trace, shift range, injection stats and, with frame_traces, the frame
+ traces.
+ events : Events
+ The events drawn for the trial (before scaling to the size reference).
+ """
s, plan, dmd = ctx["settings"], ctx["plan"], ctx["dmd"]
layout = raster_layout(ctx["data_dir"] / str(ctx["names"][t]))
_copy_recording(layout, ctx["raw_dir"], ctx["copied"])
@@ -2035,7 +2265,7 @@ def _inject_trial(ctx: dict, k: int, t: int) -> Tuple[dict, Events]:
ctx["device"],
)
reach = max(
- 3 * int(math.ceil((1.0 / period) / s.analyze_hz)),
+ 3 * math.ceil((1.0 / period) / s.analyze_hz),
layout.lines_per_cycle,
)
for a, b in ctx["neighbours"](t):
@@ -2044,8 +2274,7 @@ def _inject_trial(ctx: dict, k: int, t: int) -> Tuple[dict, Events]:
detail["trace_frames"] = (frames / s.photon_scale).astype(np.float32)
stats.render_seconds = time.perf_counter() - t0
log.info(
- "path %d trial %d: %d events, %.0f photons expected, %d drawn, "
- "%.1f s (+ %.1f s frames)",
+ "path %d trial %d: %d events, %.0f photons expected, %d drawn, %.1f s (+ %.1f s frames)",
dmd,
t + 1,
len(ev),
@@ -2057,23 +2286,40 @@ def _inject_trial(ctx: dict, k: int, t: int) -> Tuple[dict, Events]:
return detail, ev
-def _path_gain(settings: InjectionSettings, layout: RasterLayout):
- """Raw units per photon: given, or measured on the reference trial."""
+def _path_gain(settings: InjectionSettings, layout: RasterLayout) -> PhotonGain:
+ """Raw units per photon: given, or measured on the reference trial.
+
+ Returns
+ -------
+ PhotonGain
+ The given raw_per_photon (other fields unset), or the gain measured on layout.
+ """
if settings.raw_per_photon is not None:
- return PhotonGain(
- settings.raw_per_photon, float("nan"), 0, (0, 0), settings.channel
- )
+ return PhotonGain(settings.raw_per_photon, float("nan"), 0, (0, 0), settings.channel)
return measure_raw_per_photon(layout, settings.channel)
-def _neighbours(ctx: dict, cells: list):
- """For trial ``t``: line ranges of the other injected trials of the
- same recording (trials whose recordings share a data file, which may be
- named by different files of a CYCLE-split recording)."""
+def _neighbours(ctx: dict, cells: list) -> Callable[[int], list[tuple[float, float]]]:
+ """For trial t: line ranges of the other injected trials of the same recording.
+
+ Those are trials whose recordings share a data file, which may be named by
+ different files of a CYCLE-split recording.
+
+ Returns
+ -------
+ Callable[[int], list[tuple[float, float]]]
+ A function that gives, for a trial, the (first, last) lines of those trials.
+ """
files = {t: set(ctx["files"][t]) for t in cells}
- def ranges(t):
- """``(first, last)`` lines of the other trials of ``t``'s recording."""
+ def ranges(t: int) -> list[tuple[float, float]]:
+ """(first, last) lines of the other trials of t's recording.
+
+ Returns
+ -------
+ list[tuple[float, float]]
+ The (first, last) line range of each of those trials.
+ """
out = []
for u in cells:
if u != t and files[u] & files[t]:
@@ -2083,20 +2329,36 @@ def ranges(t):
return ranges
-def _replace_sources(ctx, plan, bad, attempt, calibrate) -> np.ndarray:
- """Place the sources ``bad`` anew and calibrate them there.
+def _replace_sources(
+ ctx: dict,
+ plan: PathPlan,
+ bad: np.ndarray,
+ attempt: int,
+ calibrate: Callable[[np.ndarray, int], np.ndarray],
+) -> np.ndarray:
+ """Place the sources bad anew and calibrate them there.
A source can be placed on a pixel that has data in every trial's mean
image and yet none in the stretch its frame peaks are calibrated on
(with online compensation the raster covers such a pixel only part of
the time). It is moved to a free candidate pixel that keeps the
- placement's distances: ``min_separation_px`` from the sources that
+ placement's distances: min_separation_px from the sources that
stay, from the other moved ones and from every place tried before
- (this round's and earlier rounds' unusable ones), and ``exclude_px``
+ (this round's and earlier rounds' unusable ones), and exclude_px
from the sources to keep away from. The places are drawn from a stream
- of their own (the seed, the path and ``attempt``): a path whose sources
+ of their own (the seed, the path and attempt): a path whose sources
all calibrate keeps its draws. Returns the moved sources' frame peaks,
- NaN for those that still have no data; ``plan.positions`` is updated.
+ NaN for those that still have no data; plan.positions is updated.
+
+ Returns
+ -------
+ np.ndarray
+ The moved sources' frame peaks, NaN for those that still have no data.
+
+ Raises
+ ------
+ ValueError
+ If fewer free places are left than there are sources to move.
"""
s, dmd = ctx["settings"], ctx["dmd"]
tried = ctx.setdefault("tried", {}).setdefault(dmd, [])
@@ -2118,8 +2380,7 @@ def _replace_sources(ctx, plan, bad, attempt, calibrate) -> np.ndarray:
"sources or size_reference='tissue'"
)
log.info(
- "path %d: %d source(s) without data at their peak pixel placed "
- "anew (round %d)",
+ "path %d: %d source(s) without data at their peak pixel placed anew (round %d)",
dmd,
bad.size,
attempt,
@@ -2129,12 +2390,24 @@ def _replace_sources(ctx, plan, bad, attempt, calibrate) -> np.ndarray:
def _inject_path(ctx: dict, cells: list, options: dict) -> dict:
- """Plan, calibrate and inject one path (see :func:`inject_session`)."""
+ """Plan, calibrate and inject one path (see :func:`inject_session`).
+
+ Returns
+ -------
+ dict
+ plan (the :class:`PathPlan`), gain (the :class:`PhotonGain`), frame_peak
+ (per-source frame peaks), events (all of the path's events) and trials (one
+ record per trial).
+
+ Raises
+ ------
+ ValueError
+ If some sources still have no data at their peak pixel after the replacement rounds, so
+ their frame peaks cannot be calibrated.
+ """
s, dmd = ctx["settings"], ctx["dmd"]
ctx["neighbours"] = _neighbours(ctx, cells)
- ctx["aligns"] = [
- read_alignment(ctx["moco_dir"] / str(ctx["adata"][t])) for t in cells
- ]
+ ctx["aligns"] = [read_alignment(ctx["moco_dir"] / str(ctx["adata"][t])) for t in cells]
plan = plan_path(
ctx["aligns"],
options["n_sources"],
@@ -2149,9 +2422,7 @@ def _inject_path(ctx: dict, cells: list, options: dict) -> dict:
ctx["plan"] = plan
ctx["exclude"] = options["exclude"]
n_src = plan.positions.shape[0]
- log.info(
- "path %d: %d sources (%d candidates)", dmd, n_src, plan.n_candidates
- )
+ log.info("path %d: %d sources (%d candidates)", dmd, n_src, plan.n_candidates)
ref = raster_layout(ctx["data_dir"] / str(ctx["names"][cells[0]]))
ctx["gain"] = _path_gain(s, ref)
log.info(
@@ -2162,16 +2433,20 @@ def _inject_path(ctx: dict, cells: list, options: dict) -> dict:
)
peaks = np.ones(n_src)
if s.size_reference == "frames" and n_src and s.rate_hz > 0:
- lo, hi = trial_lines(
- ref, ctx["first"][cells[0]], ctx["last"][cells[0]]
- )
+ lo, hi = trial_lines(ref, ctx["first"][cells[0]], ctx["last"][cells[0]])
geometry = trial_geometry(ref, ctx["aligns"][0], (lo, hi))
# positions that were given stay where they are, and one without
# data is an error; a source the tool placed is moved instead
placed = options["positions"] is None
- def calibrate(index, *key):
- """Frame peaks of the sources ``index`` where they are now."""
+ def calibrate(index: np.ndarray, *key: int) -> np.ndarray:
+ """Frame peaks of the sources index where they are now.
+
+ Returns
+ -------
+ np.ndarray
+ The frame peaks of those sources, as from :func:`calibrate_frame_peaks`.
+ """
return calibrate_frame_peaks(
ref,
ctx["aligns"][0],
@@ -2200,8 +2475,7 @@ def calibrate(index, *key):
"size_reference='tissue'"
)
log.info(
- "path %d: frames keep %.2f of an event's peak (median; "
- "%.2f-%.2f)",
+ "path %d: frames keep %.2f of an event's peak (median; %.2f-%.2f)",
dmd,
np.median(peaks),
peaks.min(),
@@ -2223,20 +2497,20 @@ def calibrate(index, *key):
def inject_session(
- trial_table: Union[str, Path],
- out_dir: Union[str, Path],
+ trial_table: str | Path,
+ out_dir: str | Path,
*,
- trials: Optional[Sequence[int]] = None,
+ trials: Sequence[int] | None = None,
paths: Sequence[int] = (1, 2),
n_sources: int = 50,
- settings: Optional[InjectionSettings] = None,
- placement: Optional[PlacementSettings] = None,
- positions: Optional[Dict[int, np.ndarray]] = None,
- exclude: Optional[Dict[int, np.ndarray]] = None,
- trial_shifts: Optional[Dict[int, np.ndarray]] = None,
- footprints: Optional[Dict[int, Sequence]] = None,
- data_dir: Optional[Union[str, Path]] = None,
- moco_dir: Optional[Union[str, Path]] = None,
+ settings: InjectionSettings | None = None,
+ placement: PlacementSettings | None = None,
+ positions: dict[int, np.ndarray] | None = None,
+ exclude: dict[int, np.ndarray] | None = None,
+ trial_shifts: dict[int, np.ndarray] | None = None,
+ footprints: dict[int, Sequence] | None = None,
+ data_dir: str | Path | None = None,
+ moco_dir: str | Path | None = None,
chunk_cycles: int = 64,
) -> dict:
"""Make an injected copy of a registered SLAP2 session and its truth.
@@ -2244,19 +2518,19 @@ def inject_session(
Parameters
----------
trial_table : str or Path
- The original session's ``trial_table.h5``, registered (its
- ``motion_correction/fn_adata`` names the alignment files).
+ The original session's trial_table.h5, registered (its
+ motion_correction/fn_adata names the alignment files).
out_dir : str or Path
- Output folder: the copy's data files and ``.meta`` files go to
- ``raw/``, its trial table (only the injected trials, nothing
- registered) to ``trial_table.h5`` and the truth to
- ``injection_truth.h5``.
+ Output folder: the copy's data files and .meta files go to
+ raw/, its trial table (only the injected trials, nothing
+ registered) to trial_table.h5 and the truth to
+ injection_truth.h5.
trials : sequence of int, optional
One-based trials (columns of the table) to inject (default: all).
paths : sequence of int
DMDs to inject.
n_sources : int
- Sources placed per path (when ``positions`` does not give them).
+ Sources placed per path (when positions does not give them).
settings, placement : optional
What is injected and where sources may go.
positions, exclude, trial_shifts, footprints : dict, optional
@@ -2266,7 +2540,7 @@ def inject_session(
footprints (one per source).
data_dir, moco_dir : str or Path, optional
Where the raw data and the registration are (default: the table's
- ``datadr`` and ``savedr/motion_correction``).
+ datadr and savedr/motion_correction).
chunk_cycles : int
Cycles evaluated at a time.
@@ -2275,6 +2549,14 @@ def inject_session(
dict
Summary: the output files, per path the sources, gain and
statistics.
+
+ Raises
+ ------
+ ValueError
+ If trials is empty or holds a trial outside the table, if trials or paths
+ repeat a value, if chunk_cycles is below 1, if the copy's raw folder is the
+ original's data folder, if out_dir already holds output, or if a path is not in the
+ trial table.
"""
settings = settings or InjectionSettings()
out_dir = Path(out_dir).absolute()
@@ -2291,18 +2573,13 @@ def inject_session(
raise ValueError("trials and paths must not repeat")
keep = np.array(trials) - 1
data_dir = Path(data_dir or table["datadr"]).absolute()
- moco_dir = Path(
- moco_dir or Path(table["savedr"]) / "motion_correction"
- ).absolute()
- adata = np.atleast_2d(
- np.asarray(table["motion_correction"]["fn_adata"], dtype=object)
- )
+ moco_dir = Path(moco_dir or Path(table["savedr"]) / "motion_correction").absolute()
+ adata = np.atleast_2d(np.asarray(table["motion_correction"]["fn_adata"], dtype=object))
if int(chunk_cycles) < 1:
raise ValueError("chunk_cycles must be at least 1")
if (out_dir / "raw").resolve() == data_dir.resolve():
raise ValueError(
- f"{out_dir / 'raw'} is the original's data folder; the copy "
- "must go elsewhere"
+ f"{out_dir / 'raw'} is the original's data folder; the copy must go elsewhere"
)
found = [
name
@@ -2310,10 +2587,7 @@ def inject_session(
if (out_dir / name).exists()
]
if found:
- raise ValueError(
- f"{out_dir} already holds {', '.join(found)}; inject into a new "
- "folder"
- )
+ raise ValueError(f"{out_dir} already holds {', '.join(found)}; inject into a new folder")
base = {
"settings": settings,
"placement": placement or PlacementSettings(),
@@ -2365,19 +2639,12 @@ def inject_session(
"raw_per_photon": p["gain"].raw_per_photon,
"mean_pulse": p["gain"].mean_pulse,
"frame_peak_median": (
- float(np.median(p["frame_peak"]))
- if p["frame_peak"].size
- else None
+ float(np.median(p["frame_peak"])) if p["frame_peak"].size else None
),
"n_events": len(p["events"]),
- "trials": [
- {"trial": q["trial"], **asdict(q["stats"])}
- for q in p["trials"]
- ],
+ "trials": [{"trial": q["trial"], **asdict(q["stats"])} for q in p["trials"]],
}
- copy_table = write_copy_table(
- table, keep, base["raw_dir"], out_dir, sorted(truth_paths)
- )
+ copy_table = write_copy_table(table, keep, base["raw_dir"], out_dir, sorted(truth_paths))
origin = {
"trial_table": str(Path(trial_table).absolute()),
"data_dir": str(data_dir),
@@ -2386,9 +2653,7 @@ def inject_session(
"copy_trial_table": str(copy_table),
"trials": trials,
}
- write_truth(
- out_dir / TRUTH_NAME, truth_paths, settings, base["placement"], origin
- )
+ write_truth(out_dir / TRUTH_NAME, truth_paths, settings, base["placement"], origin)
summary.update(
out_dir=str(out_dir),
raw_dir=str(base["raw_dir"]),
@@ -2402,14 +2667,20 @@ def inject_session(
def _code_version() -> str:
- """The package version."""
+ """Return the package version.
+
+ Returns
+ -------
+ str
+ giant_python followed by the package version.
+ """
from .. import __version__
return f"giant_python {__version__}"
def write_truth(
- path: Union[str, Path],
+ path: str | Path,
paths: dict,
settings: InjectionSettings,
placement: PlacementSettings,
@@ -2457,20 +2728,14 @@ def write_truth(
)
g.create_dataset("positions_rc", data=plan.positions)
g.create_dataset("trial_shift_rc", data=plan.trial_shift)
- g.create_dataset(
- "trials", data=np.array([t["trial"] for t in p["trials"]])
- )
+ g.create_dataset("trials", data=np.array([t["trial"] for t in p["trials"]]))
g.create_dataset(
"mean_image",
data=plan.mean_image.astype(np.float32),
compression="gzip",
)
g.create_dataset("valid", data=plan.valid, compression="gzip")
- half = int(
- math.ceil(
- max((fp.radius for fp in plan.footprints), default=0)
- )
- )
+ half = math.ceil(max((fp.radius for fp in plan.footprints), default=0))
patches, origins = [], []
for pos, fp in zip(plan.positions, plan.footprints):
patch, o = footprint_patch(fp, pos, half)
@@ -2479,16 +2744,10 @@ def write_truth(
fg = g.create_group("footprint")
fg.create_dataset(
"patch",
- data=np.array(patches, dtype=np.float32).reshape(
- -1, 2 * half + 1, 2 * half + 1
- ),
- )
- fg.create_dataset(
- "patch_origin_rc", data=np.array(origins).reshape(-1, 2)
- )
- fg.attrs["params"] = json.dumps(
- [fp.describe() for fp in plan.footprints]
+ data=np.array(patches, dtype=np.float32).reshape(-1, 2 * half + 1, 2 * half + 1),
)
+ fg.create_dataset("patch_origin_rc", data=np.array(origins).reshape(-1, 2))
+ fg.attrs["params"] = json.dumps([fp.describe() for fp in plan.footprints])
eg = g.create_group("events")
line_period = {t["trial"]: t["line_period_s"] for t in p["trials"]}
first = {t["trial"]: t["first_line"] for t in p["trials"]}
@@ -2529,28 +2788,33 @@ def write_truth(
h.create_dataset("shift_range", data=t["shift_range"])
-def read_truth(path: Union[str, Path]) -> dict:
+def read_truth(path: str | Path) -> dict:
"""Read a truth file.
Returns
-------
dict
- ``settings``, ``placement``, ``origin`` (dicts), ``seed``,
- ``frame`` and ``units`` (descriptions), and per DMD ``paths[k]``:
- ``positions_rc`` (sources x 2, path frame), ``trial_shift_rc``
- (trials x 2), ``trials`` (one-based original trial numbers),
- ``raw_per_photon``, ``gain``, ``frame_peak`` (share of an event's
- peak each source's frames keep), ``peak_pixel_rc``, ``mean_image``,
- ``valid``,
- ``footprint`` (``patch``, ``patch_origin_rc``, ``params``),
- ``events`` (``source``, ``trial``, ``onset_line``, ``onset_s``,
- ``peak_line``, ``size``, ``size_class``) and ``trials_detail[t]``
- (``positions_rc`` in the trial's registered frame, ``frame_lines``
- at ``analyze_hz``, ``trace`` and ``trace_frames`` sources x frames
- (``trace_frames`` NaN where a frame's kernel reads another injected
- trial of the same file), ``stats`` and the trial's lines; after
- :func:`record_copy_registration` also ``copy_shift_rc`` and
- ``positions_copy_rc``).
+ settings, placement, origin (dicts), seed,
+ frame and units (descriptions), and per DMD paths[k]:
+ positions_rc (sources x 2, path frame), trial_shift_rc
+ (trials x 2), trials (one-based original trial numbers),
+ raw_per_photon, gain, frame_peak (share of an event's
+ peak each source's frames keep), peak_pixel_rc, mean_image,
+ valid,
+ footprint (patch, patch_origin_rc, params),
+ events (source, trial, onset_line, onset_s,
+ peak_line, size, size_class) and trials_detail[t]
+ (positions_rc in the trial's registered frame, frame_lines
+ at analyze_hz, trace and trace_frames sources x frames
+ (trace_frames NaN where a frame's kernel reads another injected
+ trial of the same file), stats and the trial's lines; after
+ :func:`record_copy_registration` also copy_shift_rc and
+ positions_copy_rc).
+
+ Raises
+ ------
+ ValueError
+ If the file is not a truth file.
"""
out = {"paths": {}}
with h5py.File(path, "r") as f:
@@ -2560,7 +2824,7 @@ def read_truth(path: Union[str, Path]) -> dict:
out[key] = json.loads(f.attrs[key])
for key in ("seed", "frame", "units", "code", "created"):
out[key] = f.attrs[key]
- for name, g in f.items():
+ for g in f.values():
p = {k: g[k][()] for k in g if isinstance(g[k], h5py.Dataset)}
p.update({k: g.attrs[k] for k in g.attrs})
p["gain"] = json.loads(p["gain"])
@@ -2569,7 +2833,7 @@ def read_truth(path: Union[str, Path]) -> dict:
p["footprint"]["params"] = json.loads(fg.attrs["params"])
p["events"] = {k: g["events"][k][()] for k in g["events"]}
detail = {}
- for tname, h in g["trials_detail"].items():
+ for h in g["trials_detail"].values():
d = {k: h[k][()] for k in h}
d.update({k: h.attrs[k] for k in h.attrs})
d["stats"] = json.loads(d["stats"])
@@ -2583,11 +2847,16 @@ def read_truth(path: Union[str, Path]) -> dict:
def _grid_origin(alignment: Alignment) -> np.ndarray:
- """What a registration adds to a sample's DMD position besides motion.
+ """Compute what a registration adds to a sample's DMD position besides motion.
+
+ shift(l) = o(l) - (trim - 1) + maxshift - M(l) (see
+ :func:`trial_geometry`); the constant part is maxshift - (trim - 1)
+ less mapping @ refOffset when compensated.
- ``shift(l) = o(l) - (trim - 1) + maxshift - M(l)`` (see
- :func:`trial_geometry`); the constant part is ``maxshift - (trim - 1)``
- less ``mapping @ refOffset`` when compensated.
+ Returns
+ -------
+ np.ndarray
+ The constant (row, col) part of the shift.
"""
trim = np.array([alignment.trim_r0, alignment.trim_c0], np.float64)
origin = alignment.margin - (trim - 1)
@@ -2598,32 +2867,30 @@ def _grid_origin(alignment: Alignment) -> np.ndarray:
def registration_offset(original: Alignment, copy: Alignment) -> dict:
- """Where a copy's registration puts what the original's put at ``p``.
+ """Where a copy's registration puts what the original's put at p.
Two registrations of the same lines can differ by a constant: a grid is
anchored on its initial template, and its window, padding and online
- reference offset may differ. A tissue point at ``p`` in the original's
- registered frame is at ``p + shift_rc`` in the copy's.
+ reference offset may differ. A tissue point at p in the original's
+ registered frame is at p + shift_rc in the copy's.
+
+ Returns
+ -------
+ dict
+ shift_rc; motion_offset_rc: median of the copy's minus the
+ original's continuous motion; rms_px and max_px: length of
+ the motion difference after removing that median; n_frames.
Raises
------
ValueError
For registrations of different frames, or when only one of them
undid the online correction (they then differ line by line).
-
- Returns
- -------
- dict
- ``shift_rc``; ``motion_offset_rc``: median of the copy's minus the
- original's continuous motion; ``rms_px`` and ``max_px``: length of
- the motion difference after removing that median; ``n_frames``.
"""
if not np.array_equal(original.ds_frames, copy.ds_frames):
raise ValueError("the registrations are of different frames")
if (original.compensation is None) != (copy.compensation is None):
- raise ValueError(
- "only one registration undid the online motion correction"
- )
+ raise ValueError("only one registration undid the online motion correction")
d = (_continuous(copy) - _continuous(original)).T
d = d[np.all(np.isfinite(d), axis=1)]
if d.shape[0] == 0:
@@ -2639,28 +2906,31 @@ def registration_offset(original: Alignment, copy: Alignment) -> dict:
}
-def record_copy_registration(out_dir: Union[str, Path]) -> dict:
+def record_copy_registration(out_dir: str | Path) -> dict:
"""Compare the copy's registration with the original's; record it.
- ``out_dir`` is an :func:`inject_session` output whose ``trial_table.h5``
- has been registered (``giant register``). For each injected trial-path
- the truth file gains ``copy_shift_rc`` and ``positions_copy_rc`` (the
- sources in the copy's registered frame: ``positions_rc + copy_shift_rc``)
- and the attributes ``copy_alignment``, ``copy_motion_rms_px`` and
- ``copy_motion_max_px``.
+ out_dir is an :func:`inject_session` output whose trial_table.h5
+ has been registered (giant register). For each injected trial-path
+ the truth file gains copy_shift_rc and positions_copy_rc (the
+ sources in the copy's registered frame: positions_rc + copy_shift_rc)
+ and the attributes copy_alignment, copy_motion_rms_px and
+ copy_motion_max_px.
Returns
-------
dict
- ``{dmd: {trial: registration_offset(...)}}``.
+ {dmd: {trial: registration_offset(...)}}.
+
+ Raises
+ ------
+ ValueError
+ If the copy's trial table is not registered.
"""
out_dir = Path(out_dir)
table = load_struct_h5(out_dir / "trial_table.h5")
if "motion_correction" not in table:
raise ValueError(f"{out_dir / 'trial_table.h5'} is not registered")
- adata = np.atleast_2d(
- np.asarray(table["motion_correction"]["fn_adata"], dtype=object)
- )
+ adata = np.atleast_2d(np.asarray(table["motion_correction"]["fn_adata"], dtype=object))
moco = Path(table["savedr"]) / "motion_correction"
result = {}
with h5py.File(out_dir / TRUTH_NAME, "r+") as f:
@@ -2677,9 +2947,7 @@ def record_copy_registration(out_dir: Union[str, Path]) -> dict:
if key in h:
del h[key]
h["copy_shift_rc"] = cmp["shift_rc"]
- h["positions_copy_rc"] = (
- h["positions_rc"][()] + cmp["shift_rc"]
- )
+ h["positions_copy_rc"] = h["positions_rc"][()] + cmp["shift_rc"]
h.attrs["copy_alignment"] = str(path)
h.attrs["copy_motion_rms_px"] = cmp["rms_px"]
h.attrs["copy_motion_max_px"] = cmp["max_px"]
@@ -2690,8 +2958,14 @@ def record_copy_registration(out_dir: Union[str, Path]) -> dict:
# --------------------------------------------------------------------- CLI
-def _read_per_path(path: Optional[str]) -> dict:
- """``{dmd: array}`` from an HDF5 file with datasets ``path1``, ..."""
+def _read_per_path(path: str | None) -> dict:
+ """{dmd: array} from an HDF5 file with datasets path1, ...
+
+ Returns
+ -------
+ dict
+ One float64 array per DMD number found in the file; empty if path is empty.
+ """
if not path:
return {}
out = {}
@@ -2704,13 +2978,11 @@ def _read_per_path(path: Optional[str]) -> dict:
def _add_inject_args(ap: argparse.ArgumentParser) -> None:
- """Options of ``inject``."""
+ """Options of inject."""
d = InjectionSettings()
pl = PlacementSettings()
ap.add_argument("trial_table", help="the original's trial_table.h5")
- ap.add_argument(
- "out_dir", help=f"output folder (raw/, trial_table.h5, {TRUTH_NAME})"
- )
+ ap.add_argument("out_dir", help=f"output folder (raw/, trial_table.h5, {TRUTH_NAME})")
ap.add_argument(
"--trials",
type=int,
@@ -2728,9 +3000,7 @@ def _add_inject_args(ap: argparse.ArgumentParser) -> None:
help="share of the events at onsets common to all sources (0-1)",
)
ap.add_argument("--edge-s", type=float, default=d.edge_s)
- ap.add_argument(
- "--sizes", type=float, nargs="+", default=list(d.size_classes)
- )
+ ap.add_argument("--sizes", type=float, nargs="+", default=list(d.size_classes))
ap.add_argument("--class-weights", type=float, nargs="+")
ap.add_argument("--tau-s", type=float, default=d.tau_s)
ap.add_argument("--rise-s", type=float, default=d.rise_s)
@@ -2762,25 +3032,20 @@ def _add_inject_args(ap: argparse.ArgumentParser) -> None:
help="do not render each source's noiseless frame trace",
)
ap.add_argument("--device", default=d.device)
- ap.add_argument(
- "--min-separation-px", type=float, default=pl.min_separation_px
- )
+ ap.add_argument("--min-separation-px", type=float, default=pl.min_separation_px)
ap.add_argument("--edge-px", type=float, default=pl.edge_px)
ap.add_argument("--exclude-px", type=float, default=pl.exclude_px)
ap.add_argument(
"--exclude",
- help="HDF5 with datasets pathK: existing sources (n x 2, zero-based "
- "row/col, path frame)",
+ help="HDF5 with datasets pathK: existing sources (n x 2, zero-based row/col, path frame)",
)
ap.add_argument(
"--positions",
- help="HDF5 with datasets pathK: source positions (path frame) "
- "instead of placing them",
+ help="HDF5 with datasets pathK: source positions (path frame) instead of placing them",
)
ap.add_argument(
"--trial-shifts",
- help="HDF5 with datasets pathK: one (row, col) shift per injected "
- "trial",
+ help="HDF5 with datasets pathK: one (row, col) shift per injected trial",
)
ap.add_argument("--data-dir", help="raw data folder (default: datadr)")
ap.add_argument(
@@ -2790,7 +3055,13 @@ def _add_inject_args(ap: argparse.ArgumentParser) -> None:
def build_parser() -> argparse.ArgumentParser:
- """Command-line options of the ``python -m`` entry point."""
+ """Command-line options of the python -m entry point.
+
+ Returns
+ -------
+ argparse.ArgumentParser
+ The parser with the inject and compare subcommands.
+ """
ap = argparse.ArgumentParser(
prog="python -m giant_python.simulation.injection",
description="Inject synthetic events into a copy of a registered "
@@ -2798,9 +3069,7 @@ def build_parser() -> argparse.ArgumentParser:
)
ap.add_argument("-v", "--verbose", action="store_true")
sub = ap.add_subparsers(dest="command", required=True)
- _add_inject_args(
- sub.add_parser("inject", help="make the injected copy and its truth")
- )
+ _add_inject_args(sub.add_parser("inject", help="make the injected copy and its truth"))
cmp = sub.add_parser(
"compare",
help="after registering OUT_DIR/trial_table.h5: record the copy's "
@@ -2810,13 +3079,19 @@ def build_parser() -> argparse.ArgumentParser:
return ap
-def _settings_from_args(args) -> Tuple[InjectionSettings, PlacementSettings]:
- """Settings of ``inject``."""
+def _settings_from_args(args: argparse.Namespace) -> tuple[InjectionSettings, PlacementSettings]:
+ """Build the settings of inject.
+
+ Returns
+ -------
+ settings : InjectionSettings
+ What is injected, from the command-line arguments.
+ placement : PlacementSettings
+ Where sources may go, from the command-line arguments.
+ """
settings = InjectionSettings(
size_classes=tuple(args.sizes),
- class_weights=(
- tuple(args.class_weights) if args.class_weights else None
- ),
+ class_weights=(tuple(args.class_weights) if args.class_weights else None),
rate_hz=args.rate_hz,
min_interval_s=args.min_interval_s,
sync_share=args.sync_share,
@@ -2842,15 +3117,27 @@ def _settings_from_args(args) -> Tuple[InjectionSettings, PlacementSettings]:
return settings, placement
-def _json_default(x):
- """Arrays as lists, anything else as text."""
+def _json_default(x: object) -> list | str:
+ """Arrays as lists, anything else as text.
+
+ Returns
+ -------
+ list or str
+ x as a list if it is an array, else its text.
+ """
if isinstance(x, np.ndarray):
return x.tolist()
return str(x)
-def main(argv: Optional[Sequence[str]] = None) -> int:
- """Run ``inject`` or ``compare``; print a JSON summary."""
+def main(argv: Sequence[str] | None = None) -> int:
+ """Run inject or compare; print a JSON summary.
+
+ Returns
+ -------
+ int
+ The process exit status, 0.
+ """
args = build_parser().parse_args(argv)
logging.basicConfig(
level=logging.INFO if args.verbose else logging.WARNING,
diff --git a/src/giant_python/simulation/render.py b/src/giant_python/simulation/render.py
index 0ee436fd..0dc2ce24 100644
--- a/src/giant_python/simulation/render.py
+++ b/src/giant_python/simulation/render.py
@@ -1,9 +1,9 @@
"""Registered frames of any raw samples, with a recording's registration.
The frames registration would make of a recording if its samples were
-``samples``, moved by the recorded motion instead of a new estimate: frames
+samples, moved by the recorded motion instead of a new estimate: frames
are formed at the given line times with the exponential kernel, the online
-correction undone as the alignment file records it (``compensateOnline``),
+correction undone as the alignment file records it (compensateOnline),
and resampled onto the registered grid with freshness-weighted bilinear
interpolation, as :func:`~giant_python.registration.multiroi.register_trial`
does. Samples can be any array of raw counts in the recording's slot order,
@@ -11,7 +11,7 @@
counts of :class:`~giant_python.simulation.injection.SampleModel`.
A frame is moved by the continuous motion interpolated to its time as SILo's
-``loadTrial`` does (``pchip``, which passes through the recorded motion at the
+loadTrial does (pchip, which passes through the recorded motion at the
registered frames), less its own online reference offset when compensated: a
frame formed with another kernel than the registration's can have another
reference than the registered frame at the same time.
@@ -19,11 +19,12 @@
from __future__ import annotations
+from collections.abc import Iterator
from dataclasses import replace
-from typing import Iterator, Optional, Tuple
import numpy as np
import torch
+from numpy.typing import ArrayLike
from ..io.slap2_raster import RasterLayout
from ..registration.compensation import line_offsets
@@ -33,8 +34,22 @@
from .injection import Alignment, motion_at
-def _source(former: FrameFormer, alignment: Alignment, times, dt: int):
- """The frame source matching the alignment's window and compensation."""
+def _source(
+ former: FrameFormer, alignment: Alignment, times: np.ndarray, dt: int
+) -> CompensatedFrames | PlainFrames:
+ """Build the frame source matching the alignment's window and compensation.
+
+ Returns
+ -------
+ CompensatedFrames or PlainFrames
+ The online-compensated source when the alignment records a compensation, a
+ plain source otherwise.
+
+ Raises
+ ------
+ ValueError
+ If the samples' raster does not match the alignment's registration window.
+ """
layout = former.layout
m = alignment.margin
h, w = (s - 2 * m for s in alignment.shape)
@@ -63,16 +78,13 @@ def _source(former: FrameFormer, alignment: Alignment, times, dt: int):
or win.shape != (h, w)
):
raise ValueError(
- "the samples' raster does not match the registration window of "
- f"{alignment.path}"
+ f"the samples' raster does not match the registration window of {alignment.path}"
)
return src
-def frame_motion(
- alignment: Alignment, times: np.ndarray, refs: Optional[np.ndarray]
-) -> np.ndarray:
- """Motion to resample frames at ``times`` with (rows, cols per frame).
+def frame_motion(alignment: Alignment, times: np.ndarray, refs: np.ndarray | None) -> np.ndarray:
+ """Motion to resample frames at times with (rows, cols per frame).
Parameters
----------
@@ -81,14 +93,14 @@ def frame_motion(
times : ndarray of int
One-based frame line times.
refs : ndarray or None
- ``(frames, 2)`` online offset [x, y] each frame is formed around
+ (frames, 2) online offset [x, y] each frame is formed around
(compensated registrations), else None.
Returns
-------
ndarray
- ``(frames, 2)``: the interpolated continuous motion, less ``mapping @
- (ref - refOffset)`` when compensated.
+ (frames, 2): the interpolated continuous motion, less mapping @
+ (ref - refOffset) when compensated.
"""
move = motion_at(alignment, times).T
comp = alignment.compensation
@@ -103,25 +115,25 @@ def iter_registered_frames(
samples: np.ndarray,
cycle0: int,
alignment: Alignment,
- times,
+ times: ArrayLike,
dt: int,
- device="cpu",
+ device: str | torch.device = "cpu",
chunk: int = 64,
- offset_rc=(0.0, 0.0),
+ offset_rc: tuple[float, float] = (0.0, 0.0),
exclusive: bool = False,
-) -> Iterator[Tuple[np.ndarray, torch.Tensor, torch.Tensor]]:
- """Registered frames of ``samples``, a chunk of frames at a time.
+) -> Iterator[tuple[np.ndarray, torch.Tensor, torch.Tensor]]:
+ """Yield registered frames of samples, a chunk of frames at a time.
Parameters
----------
layout : RasterLayout
The recording the samples belong to (slot order, lines, headers).
samples : ndarray
- ``(channels, slots, cycles)`` raw counts (any real dtype; -32768
- marks invalid samples) of the cycles ``cycle0 ...``; the channels
+ (channels, slots, cycles) raw counts (any real dtype; -32768
+ marks invalid samples) of the cycles cycle0 ...; the channels
need not be the recording's.
cycle0 : int
- Zero-based cycle of ``samples[:, :, 0]``.
+ Zero-based cycle of samples[:, :, 0].
alignment : Alignment
The recording's registration of this trial.
times : array_like of int
@@ -134,22 +146,22 @@ def iter_registered_frames(
Frames per yielded chunk.
offset_rc : (float, float)
Frames are rendered in the trial's registered frame moved by this
- offset: pixel ``p`` shows the trial frame's ``p + offset_rc`` (the
+ offset: pixel p shows the trial frame's p + offset_rc (the
way SILo reads a trial on its consensus grid, with the trial shift
- ``motOutput``). Default: the trial's own registered frame.
+ motOutput). Default: the trial's own registered frame.
exclusive : bool
- Leave out the samples exactly ``max(3 dt, P)`` lines from a frame's
- time, as SILo's extraction frames do (``getImages``); registration's
+ Leave out the samples exactly max(3 dt, P) lines from a frame's
+ time, as SILo's extraction frames do (getImages); registration's
frames keep them (the default).
Yields
------
index : ndarray of int
- Positions in ``times`` of the chunk's frames.
+ Positions in times of the chunk's frames.
frames : torch.Tensor
- ``(channels, n, rows, cols)`` registered frames (NaN without data).
+ (channels, n, rows, cols) registered frames (NaN without data).
var_factor : torch.Tensor
- ``(n, rows, cols)`` variance factor (``1 / freshness``).
+ (n, rows, cols) variance factor (1 / freshness).
"""
times = np.asarray(times, dtype=np.int64).ravel()
n_ch = samples.shape[0]
diff --git a/src/giant_python/spine/__init__.py b/src/giant_python/spine/__init__.py
index ac1c0bb5..78e5f120 100644
--- a/src/giant_python/spine/__init__.py
+++ b/src/giant_python/spine/__init__.py
@@ -8,15 +8,15 @@
The per-trial images that the readout projects come from:
-* the F0 network's baseline (``_BASELINE-80Hz.h5`` of ``slap2-f0
- predict-registered``), averaged over each trial's kept frames and
+* the F0 network's baseline (_BASELINE-80Hz.h5 of slap2-f0
+ predict-registered), averaged over each trial's kept frames and
resampled into the run's consensus frame (:mod:`.images`);
-* the run's own per-trial images (``per_trial_mean_im``, and MATLAB's
- ``per_trial_F0_im`` where a run has it).
+* the run's own per-trial images (per_trial_mean_im, and MATLAB's
+ per_trial_F0_im where a run has it).
:mod:`.summary_io` reads a run's summaries (MATLAB's schema, written by
GIAnT-MATLAB or by GIAnT-Python's raster SILo), :mod:`.rois` builds the
windows (sources' mean footprints, user ROIs, disks), :mod:`.readout`
projects images on them, and :mod:`.product` writes everything a viewer
-or a later analysis needs into one compact ``spine_summary`` file.
+or a later analysis needs into one compact spine_summary file.
"""
diff --git a/src/giant_python/spine/coverage.py b/src/giant_python/spine/coverage.py
index d7d49ab7..bd6c3cf4 100644
--- a/src/giant_python/spine/coverage.py
+++ b/src/giant_python/spine/coverage.py
@@ -9,10 +9,10 @@
reaches into the band reads a size that drops in those trials.
:func:`unimaged_pixels` finds the band from the per-trial mean images: in a
-trial, pixels below ``frac`` of their usual level (the 75th percentile over
+trial, pixels below frac of their usual level (the 75th percentile over
trials, so that a band in most trials still stands out) in every mean
channel, connected (8 neighbours) to that trial's pixels without a value or
-to the frame's border (the edge of the scan), and then ``dilate`` pixels
+to the frame's border (the edge of the scan), and then dilate pixels
around them (registration's interpolation smears the band's edge). The
connection to the edge keeps real dimming inside an ROI from being taken
as a band, and requiring every channel keeps activity or a change in one
@@ -24,6 +24,8 @@
from __future__ import annotations
+from collections.abc import Sequence
+
import numpy as np
from .rois import RoiSet
@@ -32,12 +34,12 @@
def unimaged_pixels(
- channels,
+ channels: Sequence[np.ndarray],
frac: float = 0.5,
dilate: int = 1,
max_share: float = 0.25,
with_skipped: bool = False,
-):
+) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
"""Pixels each trial did not image, from its mean images.
Parameters
@@ -50,7 +52,7 @@ def unimaged_pixels(
brightness scale (the 75th percentile, over the pixels every trial
with values has, of each pixel's ratio to its usual level, so that
a change of the whole field's brightness is not dark), it is below
- ``frac`` of its usual level, its 75th percentile over trials, in
+ frac of its usual level, its 75th percentile over trials, in
every channel (0 finds nothing).
dilate : int
Pixels added around each trial's band (within its pixels with
@@ -63,15 +65,20 @@ def unimaged_pixels(
brightness, cannot be told apart from a change of the scene in the
images alone.
with_skipped : bool
- Also return the trials skipped for ``max_share``.
+ Also return the trials skipped for max_share.
Returns
-------
ndarray of bool, shape (trials, rows, cols)
True where a trial has values but did not image the pixel.
skipped : ndarray of int
- Only with ``with_skipped``: the trials (zero-based) whose band was
+ Only with with_skipped: the trials (zero-based) whose band was
too large to mark.
+
+ Raises
+ ------
+ ValueError
+ If no channel is given.
"""
chans = [np.asarray(c, dtype=np.float64) for c in channels]
if not chans:
@@ -80,8 +87,14 @@ def unimaged_pixels(
out = np.zeros(shape, bool)
skipped: list = []
- def result():
- """The mask, and the skipped trials if asked for."""
+ def result() -> np.ndarray | tuple[np.ndarray, np.ndarray]:
+ """Return the mask, and the skipped trials if asked for.
+
+ Returns
+ -------
+ np.ndarray or tuple of np.ndarray
+ The mask, or the mask and the skipped trials if with_skipped.
+ """
if with_skipped:
return out, np.asarray(skipped, np.int64)
return out
@@ -102,7 +115,23 @@ def result():
def _missing(chans: list) -> np.ndarray:
- """Pixels missing in any channel (the channels must share a shape)."""
+ """Return the pixels missing in any channel (the channels must share a shape).
+
+ Parameters
+ ----------
+ chans : list
+ The per-trial mean images of each channel.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean stack, True where a pixel is not finite in any channel.
+
+ Raises
+ ------
+ ValueError
+ If the channels' image stacks differ in shape.
+ """
shape = chans[0].shape
missing = np.zeros(shape, bool)
for c in chans:
@@ -113,8 +142,7 @@ def _missing(chans: list) -> np.ndarray:
def nanpercentile_over_trials(stack: np.ndarray, q: float) -> np.ndarray:
- """``np.nanpercentile(stack, q, axis=0)``, to the bit, for a stack of
- images.
+ """``np.nanpercentile(stack, q, axis=0)``, to the bit, for a stack of images.
numpy takes the percentile along an axis with NaN one pixel at a time
(seconds per call on a field of 500,000 pixels); here the stack is
@@ -131,13 +159,13 @@ def nanpercentile_over_trials(stack: np.ndarray, q: float) -> np.ndarray:
Returns
-------
- ndarray of float64, shape ``stack.shape[1:]``
+ ndarray of float64, shape stack.shape[1:]
NaN where no trial has a value.
Raises
------
ValueError
- If ``q`` is not within 0 to 100 (as numpy).
+ If q is not within 0 to 100 (as numpy).
"""
if not 0 <= q <= 100: # also NaN
raise ValueError("Percentiles must be in the range [0, 100]")
@@ -156,15 +184,13 @@ def nanpercentile_over_trials(stack: np.ndarray, q: float) -> np.ndarray:
with np.errstate(invalid="ignore"):
# numpy's _lerp, term for term (so NaN at an infinite neighbour too)
diff = above - below
- out = np.where(
- gamma >= 0.5, above - diff * (1 - gamma), below + diff * gamma
- )
+ out = np.where(gamma >= 0.5, above - diff * (1 - gamma), below + diff * gamma)
out[n == 0] = np.nan
return out.reshape(stack.shape[1:])
def _dark(chans: list, missing: np.ndarray, frac: float) -> np.ndarray:
- """Pixels below ``frac`` of their usual level in every channel.
+ """Pixels below frac of their usual level in every channel.
The usual level is a pixel's 75th percentile over trials, so that a band
present in up to ~75% of the trials still stands out. Each trial is
@@ -173,14 +199,28 @@ def _dark(chans: list, missing: np.ndarray, frac: float) -> np.ndarray:
every trial with values has, of each pixel's ratio to its usual level.
A band, whose ratios are low, does not set the scale unless it covers
most of those pixels.
+
+ Parameters
+ ----------
+ chans : list
+ The per-trial mean images of each channel, each of shape
+ (trials, rows, cols).
+ missing : np.ndarray
+ Boolean stack of the pixels missing in any channel.
+ frac : float
+ A pixel is dark when it is below this share of its usual level.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean stack, True where a pixel is below frac of its usual level
+ in every channel.
"""
shape = missing.shape
# the pixels every trial with values has (a trial without any value,
# e.g. one not extracted, does not empty them)
has = ~missing.reshape(shape[0], -1).all(axis=1)
- common = (
- ~missing[has].any(axis=0) if has.any() else np.zeros(shape[1:], bool)
- )
+ common = ~missing[has].any(axis=0) if has.any() else np.zeros(shape[1:], bool)
dark = np.ones(shape, bool)
for c in chans:
ref = nanpercentile_over_trials(c, 75)
@@ -200,10 +240,27 @@ def _dark(chans: list, missing: np.ndarray, frac: float) -> np.ndarray:
return dark
-def _edge_band(dark: np.ndarray, missing: np.ndarray, dilate: int):
- """One trial's dark pixels connected (8 neighbours) to its missing
- pixels or to the frame's border, and ``dilate`` pixels around them,
- without the missing pixels."""
+def _edge_band(dark: np.ndarray, missing: np.ndarray, dilate: int) -> np.ndarray:
+ """One trial's dark pixels connected to its missing pixels or the border.
+
+ The dark pixels connected (8 neighbours) to its missing pixels or to the
+ frame's border, and dilate pixels around them, without the missing
+ pixels.
+
+ Parameters
+ ----------
+ dark : np.ndarray
+ Boolean image of the trial's dark pixels.
+ missing : np.ndarray
+ Boolean image of the trial's pixels without a value.
+ dilate : int
+ Pixels added around the band.
+
+ Returns
+ -------
+ np.ndarray
+ Boolean image of the band, without the missing pixels.
+ """
from scipy import ndimage
# the frame's border counts as the scan's edge too
@@ -213,15 +270,28 @@ def _edge_band(dark: np.ndarray, missing: np.ndarray, dilate: int):
touching = np.unique(lab[edge])
band = (np.isin(lab, touching[touching > 0]) & cand)[1:-1, 1:-1]
if dilate > 0 and band.any():
- band = ndimage.binary_dilation(
- band, structure=_EIGHT, iterations=int(dilate)
- )
+ band = ndimage.binary_dilation(band, structure=_EIGHT, iterations=int(dilate))
return band & ~missing
def window_weight_kept(rois: RoiSet, valid: np.ndarray) -> np.ndarray:
- """Share of each window's weight on the ``valid`` pixels (0 for a
- window without weight)."""
+ """Share of each window's weight on the valid pixels.
+
+ A window without weight gets 0.
+
+ Parameters
+ ----------
+ rois : RoiSet
+ The windows.
+ valid : np.ndarray
+ Boolean image of the valid pixels.
+
+ Returns
+ -------
+ np.ndarray
+ For each window, the share (0 to 1) of its positive weight that falls on
+ valid pixels; 0 for a window without weight.
+ """
vflat = np.asarray(valid, bool).ravel()
out = np.zeros(len(rois))
for k in range(len(rois)):
diff --git a/src/giant_python/spine/gains.py b/src/giant_python/spine/gains.py
index 5c24f9c7..9d6cd511 100644
--- a/src/giant_python/spine/gains.py
+++ b/src/giant_python/spine/gains.py
@@ -1,33 +1,33 @@
-"""The network's baseline as rescaled by SILo's gain fit (``net·gain``).
+"""The network's baseline as rescaled by SILo's gain fit (net·gain).
In the 'gain' baseline mode (N1, the default with the network's baseline)
the solver fits one gain per selected pixel in each subproblem, after the
-first activity fit: ``B = max(min_baseline, g * b_net)``. The final ``B`` is
-not saved, but each subproblem's gains are, in its results file's ``info``
-record (``baseline_step.gain``, one per subproblem pixel). A trial's mean of
-``B`` is therefore ``g`` times the trial's mean of the network's baseline
+first activity fit: B = max(min_baseline, g * b_net). The final B is
+not saved, but each subproblem's gains are, in its results file's info
+record (baseline_step.gain, one per subproblem pixel). A trial's mean of
+B is therefore g times the trial's mean of the network's baseline
(apart from the floor, which the network's baseline rarely reaches), and
-the per-trial F0 image of the rescaled baseline is ``g`` times the network's
+the per-trial F0 image of the rescaled baseline is g times the network's
per-trial F0 image, at the selected pixels.
A pixel that belongs to overlapping subproblems has one gain in each; the
image takes their mean, and :func:`gain_maps` also returns their spread so
that the disagreement can be checked.
-Results files: ``/results/path_trial[_s...].h5`` (path
-and trial one-based); the plan ``/plan/path.h5`` gives the
-selected pixels (``sources/sel``, listed column by column, as MATLAB's
-``find(selPix)``). As in SILo's collect stage, only results made from the
+Results files: /results/path_trial[_s...].h5 (path
+and trial one-based); the plan /plan/path.h5 gives the
+selected pixels (sources/sel, listed column by column, as MATLAB's
+find(selPix)). As in SILo's collect stage, only results made from the
current plan are read. A work folder that holds results of more than one
solve for a trial (other solve settings or inputs) is an error, since the
summaries do not record which solve they used, and so are a trial's files
that leave out some of its subproblems (an incomplete set of shards), which
the collect stage also refuses.
-Only the gain modes whose baseline is ``g * b_net`` are read: 'gain' (N1),
+Only the gain modes whose baseline is g * b_net are read: 'gain' (N1),
and 'gain_shared' (N2) subproblems whose shared time course stayed at 1.
The gains apply only to the baseline files they were fitted against: each
-results file records that file's identity (``network_baseline``), and
+results file records that file's identity (network_baseline), and
:func:`check_gain_baselines` compares it with the files of the network's F0
images, as SILo's extraction compares the localization's baseline.
"""
@@ -35,37 +35,74 @@
from __future__ import annotations
import json
+from collections.abc import Iterable, Mapping, Sequence
from pathlib import Path
+from typing import Any
import h5py
import numpy as np
-def selected_pixels(plan_path) -> tuple[np.ndarray, np.ndarray, tuple]:
- """Rows and columns of a plan's selected-pixel list, and the frame
- shape."""
+def selected_pixels(plan_path: str | Path) -> tuple[np.ndarray, np.ndarray, tuple]:
+ """Read the rows and columns of a plan's selected-pixel list.
+
+ Also returns the frame shape.
+
+ Returns
+ -------
+ rows : np.ndarray
+ Row index of each selected pixel, in the plan's column-by-column order.
+ cols : np.ndarray
+ Column index of each selected pixel, in the same order.
+ shape : tuple
+ Shape of the plan's selection mask (the frame shape).
+ """
with h5py.File(plan_path, "r") as f:
sel = f["sources/sel"][()].astype(bool)
cols, rows = np.nonzero(sel.T)
return rows, cols, sel.shape
-def _attr(f: h5py.File, name: str):
- """A file's attribute as a string (None if absent)."""
+def _attr(f: h5py.File, name: str) -> str | None:
+ """Read a file's attribute as a string (None if absent).
+
+ Returns
+ -------
+ str or None
+ The attribute decoded to a string, or None if the file does not have it.
+ """
v = f.attrs.get(name)
if v is None:
return None
return v.decode() if isinstance(v, bytes) else str(v)
-def plan_file(work_dir, path: int) -> Path:
- """The work folder's plan of a path."""
+def plan_file(work_dir: str | Path, path: int) -> Path:
+ """Return the work folder's plan of a path.
+
+ Returns
+ -------
+ Path
+ /plan/path.h5.
+ """
return Path(work_dir) / "plan" / f"path{path}.h5"
-def plan_hash(plan_path) -> str:
- """The plan's settings hash, which its results files record as
- ``plan_hash``."""
+def plan_hash(plan_path: str | Path) -> str:
+ """Read the plan's settings hash.
+
+ Its results files record it as plan_hash.
+
+ Returns
+ -------
+ str
+ The plan's settings_hash.
+
+ Raises
+ ------
+ ValueError
+ If the plan has no settings_hash.
+ """
with h5py.File(plan_path, "r") as f:
h = _attr(f, "settings_hash")
if h is None:
@@ -73,16 +110,23 @@ def plan_hash(plan_path) -> str:
return h
-def current_results(files, plan: str) -> list:
- """The results files of one trial-path that belong to the plan with
- settings hash ``plan``, as SILo's collect stage selects them.
+def current_results(files: Iterable[str | Path], plan: str) -> list[str | Path]:
+ """Select the results files of one trial-path that belong to the plan.
+
+ The plan is the one with settings hash plan; files are selected as
+ SILo's collect stage selects them.
Files of other plans are left out. The rest must come from one solve
- (one ``solve_science``, ``solve_settings`` and ``container_hash``, as
+ (one solve_science, solve_settings and container_hash, as
the collect stage requires of a container's files); otherwise the work
folder holds results of earlier runs that the summaries may not have
used.
+ Returns
+ -------
+ list[str | Path]
+ The files recorded with plan hash plan, in input order; empty if there are none.
+
Raises
------
ValueError
@@ -100,9 +144,7 @@ def current_results(files, plan: str) -> list:
)
groups.setdefault(key, []).append(path)
if len(groups) > 1:
- names = "; ".join(
- ", ".join(Path(p).name for p in v) for v in groups.values()
- )
+ names = "; ".join(", ".join(Path(p).name for p in v) for v in groups.values())
raise ValueError(
"results of more than one solve of the same plan (other solve "
f"settings or inputs): {names}. Remove the stale files."
@@ -110,10 +152,22 @@ def current_results(files, plan: str) -> list:
return next(iter(groups.values()), [])
-def _n_subproblems(path, f: h5py.File, n_sub):
- """The trial's number of subproblems as the file records it (or
- ``n_sub`` if it does not), checked against ``n_sub`` from its other
- files."""
+def _n_subproblems(path: str | Path, f: h5py.File, n_sub: int | None) -> int | None:
+ """Read the trial's number of subproblems as the file records it.
+
+ Or n_sub if it does not; checked against n_sub from its other
+ files.
+
+ Returns
+ -------
+ int or None
+ The n_subproblems attribute of the file, or n_sub if the file has none.
+
+ Raises
+ ------
+ ValueError
+ If the trial's number of subproblems differs from that in another of its results files.
+ """
ns = f.attrs.get("n_subproblems")
if ns is None:
return n_sub
@@ -126,19 +180,30 @@ def _n_subproblems(path, f: h5py.File, n_sub):
return ns
-def _subproblem_gains(path, k: int, g: h5py.Group):
- """A subproblem's pixels and gains (``baseline_step.gain`` of its
- ``info`` record), checked as :func:`trial_gains` describes."""
+def _subproblem_gains(path: str | Path, k: int, g: h5py.Group) -> tuple[np.ndarray, np.ndarray]:
+ """Read a subproblem's pixels and gains.
+
+ The gains are baseline_step.gain of its info record, checked as
+ :func:`trial_gains` describes.
+
+ Returns
+ -------
+ pixels : np.ndarray
+ The subproblem's pixel indices into the plan's selected-pixel list.
+ gains : np.ndarray
+ The matching gains (baseline_step.gain).
+
+ Raises
+ ------
+ ValueError
+ If the subproblem has no gain record, has a shared baseline time course, or has a
+ different number of pixels and gains.
+ """
step = json.loads(g.attrs["info"]).get("baseline_step")
if not step or "gain" not in step:
- raise ValueError(
- f"{path}: subproblem {k} has no gain record "
- "(not a 'gain' baseline mode)"
- )
+ raise ValueError(f"{path}: subproblem {k} has no gain record (not a 'gain' baseline mode)")
shared = step.get("shared")
- if shared is not None and not np.allclose(
- np.asarray(shared, dtype=np.float64), 1.0
- ):
+ if shared is not None and not np.allclose(np.asarray(shared, dtype=np.float64), 1.0):
raise ValueError(
f"{path}: subproblem {k} has a shared baseline time "
"course ('gain_shared'); its baseline is not "
@@ -147,18 +212,16 @@ def _subproblem_gains(path, k: int, g: h5py.Group):
p = np.asarray(g["pixels"][()], dtype=np.int64).ravel()
v = np.asarray(step["gain"], dtype=np.float64).ravel()
if p.size != v.size:
- raise ValueError(
- f"{path}: subproblem {k} has {p.size} pixels but {v.size} gains"
- )
+ raise ValueError(f"{path}: subproblem {k} has {p.size} pixels but {v.size} gains")
return p, v
-def trial_gains(results_files) -> tuple[np.ndarray, np.ndarray]:
+def trial_gains(results_files: Sequence[str | Path]) -> tuple[np.ndarray, np.ndarray]:
"""Every subproblem pixel's gain in one trial-path's results files.
A subproblem that is in several files (identical copies, which SILo's
collect stage also allows) counts once. As in the collect stage, every
- subproblem of the trial (``n_subproblems``, where the files record it)
+ subproblem of the trial (n_subproblems, where the files record it)
must be in the files.
Returns
@@ -174,7 +237,7 @@ def trial_gains(results_files) -> tuple[np.ndarray, np.ndarray]:
ValueError
If a subproblem has no gain record (the run did not use a 'gain'
mode), has a shared time course other than 1 ('gain_shared',
- whose baseline is then not ``g * b_net``), or has two different
+ whose baseline is then not g * b_net), or has two different
copies; or if the files disagree on the trial's number of
subproblems or leave some out.
"""
@@ -194,10 +257,7 @@ def trial_gains(results_files) -> tuple[np.ndarray, np.ndarray]:
if k in seen:
p0, v0 = seen[k]
if not (np.array_equal(p0, p) and np.array_equal(v0, v)):
- raise ValueError(
- f"subproblem {k} has two different results "
- f"({path})"
- )
+ raise ValueError(f"subproblem {k} has two different results ({path})")
continue
seen[k] = (p, v)
if n_sub is not None and extracted:
@@ -217,17 +277,23 @@ def trial_gains(results_files) -> tuple[np.ndarray, np.ndarray]:
)
-def results_files(work_dir, path: int, trial: int) -> list:
- """A trial-path's results files (``trial`` zero-based) of the work
- folder's current plan: ``path_trial.h5`` and its ``_s...``
- shards, selected as SILo's collect stage does
- (:func:`current_results`)."""
+def results_files(work_dir: str | Path, path: int, trial: int) -> list:
+ """Find a trial-path's results files of the work folder's current plan.
+
+ trial is zero-based. The files are path_trial.h5 and its
+ _s... shards, selected as SILo's collect stage does
+ (:func:`current_results`).
+
+ Returns
+ -------
+ list
+ The trial-path's results files (sorted) that belong to the current plan; empty if
+ there are none.
+ """
d = Path(work_dir) / "results"
stem = f"path{path}_trial{trial + 1:04d}"
files = sorted(
- p
- for p in d.glob(f"{stem}*.h5")
- if p.stem == stem or p.stem.startswith(stem + "_s")
+ p for p in d.glob(f"{stem}*.h5") if p.stem == stem or p.stem.startswith(stem + "_s")
)
if not files:
return []
@@ -238,10 +304,18 @@ def results_files(work_dir, path: int, trial: int) -> list:
"""The fields of a file identity that SILo records."""
-def recorded_baseline(files):
- """The baseline file a trial-path's results files record as fitted
- against (``network_baseline``: its name, size and modification time),
- or None. The files are of one solve, so they record the same file."""
+def recorded_baseline(files: Iterable[str | Path]) -> dict[str, Any] | None:
+ """Return the baseline file a trial-path's results files record as fitted against.
+
+ That is network_baseline: its name, size and modification time; or
+ None. The files are of one solve, so they record the same file.
+
+ Returns
+ -------
+ dict[str, Any] or None
+ The file identity (name, size, modification time) recorded in the first file that
+ has a network_baseline, or None if none does.
+ """
for path in files:
with h5py.File(path, "r") as f:
v = _attr(f, "network_baseline")
@@ -250,9 +324,12 @@ def recorded_baseline(files):
return None
-def check_gain_baselines(work_dir, path: int, baselines) -> None:
- """Check that every trial's gains were fitted against the baseline file
- that its network F0 image is made from.
+def check_gain_baselines(
+ work_dir: str | Path, path: int, baselines: Sequence[Mapping[str, Any] | None]
+) -> None:
+ """Check that every trial's gains were fitted against the right baseline file.
+
+ That is, the baseline file that its network F0 image is made from.
Parameters
----------
@@ -294,7 +371,9 @@ def check_gain_baselines(work_dir, path: int, baselines) -> None:
)
-def gain_maps(work_dir, path: int, n_trials: int):
+def gain_maps(
+ work_dir: str | Path, path: int, n_trials: int
+) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Per-trial gain images of one path, in the plan's consensus frame.
Returns
@@ -307,6 +386,11 @@ def gain_maps(work_dir, path: int, n_trials: int):
pixel in one subproblem).
n_files : ndarray of int, shape (trials,)
Results files read per trial.
+
+ Raises
+ ------
+ ValueError
+ If a pixel index of a trial is beyond the plan's selected pixels.
"""
rows, cols, shape = selected_pixels(plan_file(work_dir, path))
gain = np.full((n_trials,) + shape, np.nan, np.float32)
diff --git a/src/giant_python/spine/images.py b/src/giant_python/spine/images.py
index 5200ed79..0a8106d3 100644
--- a/src/giant_python/spine/images.py
+++ b/src/giant_python/spine/images.py
@@ -1,19 +1,19 @@
"""Per-trial F0 images from the F0 network's baseline.
-``slap2-f0 predict-registered`` writes one ``_BASELINE-80Hz.h5`` per
+slap2-f0 predict-registered writes one _BASELINE-80Hz.h5 per
trial-path: the baseline of the trial's registered 80 Hz movie, in movie
-counts, ``(frame, MATLAB column, MATLAB row)``, NaN outside the trial's
+counts, (frame, MATLAB column, MATLAB row), NaN outside the trial's
valid pixels. For the spine-size readout each trial's baseline is averaged
over its kept frames (those not discarded for motion, as SiLo discards them
-from the alignment file's ``recNegErr``, and not in the first or last
-``trim_s`` seconds) and resampled into a run's consensus frame through that
+from the alignment file's recNegErr, and not in the first or last
+trim_s seconds) and resampled into a run's consensus frame through that
run's across-trial map (bilinear, NaN outside the image or next to NaN, as
-``warp_trial_image``). Trials of different sizes are placed at the top left
+warp_trial_image). Trials of different sizes are placed at the top left
of the consensus canvas first, as SiLo places them.
The network gives a value at every registered frame, including those that
SiLo discards (it fills them from neighbouring frames); they are left out
-here, as GIAnT-MATLAB's ``F0im`` leaves out ``discard_frames``.
+here, as GIAnT-MATLAB's F0im leaves out discard_frames.
"""
from __future__ import annotations
@@ -21,6 +21,8 @@
import hashlib
import json
import math
+from collections.abc import Callable, Iterator
+from concurrent.futures import Executor
from contextlib import closing
from dataclasses import dataclass, field
from pathlib import Path
@@ -28,23 +30,36 @@
import h5py
import numpy as np
-from ..extraction.raster.alignment import interp2_linear
+from ..extraction.raster.alignment import TrialWarp, interp2_linear
from ..extraction.raster.baseline_map import baseline_file
from ..extraction.raster.trial import discard_frames
-from .parallel import ordered_map
+from .parallel import LazyPool, ordered_map
+from .summary_io import TrialMap
ALIGNMENT_SUFFIX = "_ALIGNMENTDATA.h5"
def trim_frames(trim_s: float, align_hz: float) -> int:
- """Frames left out at each end of a trial: ``round(trim_s *
- align_hz)``."""
- return int(math.floor(trim_s * align_hz + 0.5))
+ """Return the frames left out at each end of a trial: round(trim_s * align_hz).
+
+ Returns
+ -------
+ int
+ Number of frames left out at each end.
+ """
+ return math.floor(trim_s * align_hz + 0.5)
def trim_dropped(keep: np.ndarray, n_trim: int) -> bool:
- """Whether :func:`kept_frames` dropped the trim (a trial too short to
- trim): a kept frame lies within ``n_trim`` frames of either end."""
+ """Return whether :func:`kept_frames` dropped the trim (a trial too short to trim).
+
+ That is the case when a kept frame lies within n_trim frames of either end.
+
+ Returns
+ -------
+ bool
+ True if a kept frame lies within n_trim frames of either end.
+ """
keep = np.asarray(keep, bool).ravel()
if n_trim <= 0:
return False
@@ -59,17 +74,17 @@ def kept_frames(
motion_thresh: float = 2.0,
discard_initial_s: float = 0.0,
) -> np.ndarray:
- """A trial's registered frames that enter its F0 image.
+ """Return a trial's registered frames that enter its F0 image.
Frames that SiLo discards for motion (:func:`~giant_python.extraction.
raster.trial.discard_frames`) are left out, and so are the first and last
- ``round(trim_s * align_hz)`` frames. If nothing would remain, the trim is
+ round(trim_s * align_hz) frames. If nothing would remain, the trim is
dropped (GIAnT-MATLAB averages a trial too short to trim whole).
Parameters
----------
rec_neg_err : array_like
- The alignment file's ``recNegErr`` (one value per registered frame).
+ The alignment file's recNegErr (one value per registered frame).
align_hz : float
Frame rate of the registered movie.
trim_s : float
@@ -91,30 +106,36 @@ def kept_frames(
return trimmed if trimmed.any() else keep
-def read_rec_neg_err(alignment_path) -> np.ndarray:
- """``recNegErr`` of an alignment file (one value per registered frame)."""
+def read_rec_neg_err(alignment_path: str | Path) -> np.ndarray:
+ """Return recNegErr of an alignment file (one value per registered frame).
+
+ Returns
+ -------
+ np.ndarray
+ recNegErr as a flat float64 array, one value per registered frame.
+ """
with h5py.File(alignment_path, "r") as f:
return np.asarray(f["recNegErr"][()], dtype=np.float64).ravel()
def baseline_trial_mean(
- path, keep: np.ndarray, chunk: int = 64
+ path: str | Path, keep: np.ndarray, chunk: int = 64
) -> tuple[np.ndarray, int]:
"""Mean of a network baseline file over the kept frames.
- The frames are summed in blocks of ``chunk`` frames as float64, so a
+ The frames are summed in blocks of chunk frames as float64, so a
trial never has to fit in memory in that type. They are read from the
file in the stored type and in whole storage chunks along the frames
(the network writes 256 frames per chunk): a compressed chunk larger
than HDF5's chunk cache is otherwise decompressed again for every block
that touches it. Where a storage chunk does not end on a block of
- ``chunk`` frames, the block's frames are completed from the next read,
+ chunk frames, the block's frames are completed from the next read,
so the same frames are summed together whatever the storage chunks.
Parameters
----------
path : str or Path
- A ``_BASELINE-80Hz.h5`` file.
+ A _BASELINE-80Hz.h5 file.
keep : ndarray of bool, shape (frames,)
Frames to average.
chunk : int
@@ -126,6 +147,12 @@ def baseline_trial_mean(
Movie counts; NaN where no kept frame has a value.
n_frames : int
Number of frames averaged.
+
+ Raises
+ ------
+ ValueError
+ If /baseline is not (frame, col, row), or its number of frames
+ differs from the number of frame flags in keep.
"""
keep = np.asarray(keep, dtype=bool).ravel()
with h5py.File(path, "r") as f:
@@ -133,9 +160,7 @@ def baseline_trial_mean(
if ds.ndim != 3:
raise ValueError(f"{path}: /baseline must be (frame, col, row)")
if ds.shape[0] != keep.size:
- raise ValueError(
- f"{path}: {ds.shape[0]} frames, but {keep.size} frame flags"
- )
+ raise ValueError(f"{path}: {ds.shape[0]} frames, but {keep.size} frame flags")
total = np.zeros(ds.shape[1:], np.float64)
count = np.zeros(ds.shape[1:], np.int64)
n = ds.shape[0]
@@ -164,7 +189,7 @@ def baseline_trial_mean(
def to_consensus(
- image: np.ndarray, trial_map, trial: int, shape: tuple[int, int]
+ image: np.ndarray, trial_map: TrialMap | TrialWarp, trial: int, shape: tuple[int, int]
) -> np.ndarray:
"""Resample a trial's image into the consensus frame.
@@ -172,18 +197,18 @@ def to_consensus(
----------
image : ndarray of shape (rows, cols)
The image on the trial's registered frame.
- trial_map : object with ``grid_coords(trial, shape)``
+ trial_map : object with grid_coords(trial, shape)
The run's map from consensus to each trial's registered image
(:class:`~giant_python.spine.summary_io.TrialMap` or
:class:`~giant_python.extraction.raster.alignment.TrialWarp`).
trial : int
Zero-based trial.
shape : tuple of int
- ``(rows, cols)`` of the consensus frame.
+ (rows, cols) of the consensus frame.
Returns
-------
- ndarray of float64, shape ``shape``
+ ndarray of float64, shape shape
NaN outside the image or next to NaN.
"""
canvas = _canvas(image, shape)
@@ -191,9 +216,16 @@ def to_consensus(
return interp2_linear(canvas, rows, cols)
-def _canvas(image: np.ndarray, shape) -> np.ndarray:
- """``image`` on a NaN canvas of the consensus frame's ``shape`` (cut
- where it is larger), as :func:`to_consensus` resamples it."""
+def _canvas(image: np.ndarray, shape: tuple[int, int]) -> np.ndarray:
+ """Return image on a NaN canvas of the consensus frame's shape.
+
+ The image is cut where it is larger, as :func:`to_consensus` resamples it.
+
+ Returns
+ -------
+ np.ndarray
+ The canvas, of the given shape, NaN outside image.
+ """
canvas = np.full(tuple(shape), np.nan)
h = min(shape[0], image.shape[0])
w = min(shape[1], image.shape[1])
@@ -201,12 +233,18 @@ def _canvas(image: np.ndarray, shape) -> np.ndarray:
return canvas
-def file_identity(path) -> dict:
- """Resolved path, name, size and modification time of a file (its
- identity for caching).
+def file_identity(path: str | Path) -> dict:
+ """Return the resolved path, name, size and modification time of a file.
+
+ This is the file's identity for caching.
The path keeps files of other folders apart, such as copies that kept
their modification times.
+
+ Returns
+ -------
+ dict
+ The keys path, name, size and mtime_ns.
"""
path = Path(path)
st = path.stat()
@@ -247,37 +285,37 @@ class F0Stack:
def network_f0_stack(
- baseline_dir,
- moco_dir,
+ baseline_dir: str | Path,
+ moco_dir: str | Path,
stems: list,
- trial_map,
+ trial_map: TrialMap | TrialWarp,
shape: tuple[int, int],
align_hz: float = 80.0,
trim_s: float = 1.0,
motion_thresh: float = 2.0,
discard_initial_s: float = 0.0,
- progress=None,
- pool=None,
+ progress: Callable[[int, int, str | None], None] | None = None,
+ pool: Executor | LazyPool | None = None,
) -> F0Stack:
"""Per-trial F0 images of one path from the network's baselines.
Parameters
----------
baseline_dir : str or Path
- Folder of ``_BASELINE-80Hz.h5`` files.
+ Folder of _BASELINE-80Hz.h5 files.
moco_dir : str or Path
- Folder of the ``_ALIGNMENTDATA.h5`` files the baselines were
- predicted from (their ``recNegErr`` gives the discarded frames).
+ Folder of the _ALIGNMENTDATA.h5 files the baselines were
+ predicted from (their recNegErr gives the discarded frames).
stems : list of str or None
- Each trial's stem (``E1T1DMD1``), None for a trial to leave out.
+ Each trial's stem (E1T1DMD1), None for a trial to leave out.
trial_map : TrialMap or TrialWarp
The run's map from consensus to each trial's registered image.
shape : tuple of int
- ``(rows, cols)`` of the consensus frame.
+ (rows, cols) of the consensus frame.
align_hz, trim_s, motion_thresh, discard_initial_s : float
See :func:`kept_frames`.
progress : callable, optional
- Called with ``(trial, n_trials, stem)`` as each trial is started, in
+ Called with (trial, n_trials, stem) as each trial is started, in
trial order (also for the trials left out): without a pool (or with
one worker) just before the trial's files are looked at and read;
with a pool when the trial is handed to the workers, which hold
@@ -310,9 +348,26 @@ def network_f0_stack(
settings = (align_hz, trim_s, motion_thresh, discard_initial_s)
files: dict = {}
- def tasks():
- """Each trial with a stem, a map and both files as a task, after
- reporting the trial."""
+ def tasks() -> Iterator[
+ tuple[
+ int,
+ Path,
+ Path,
+ tuple[float, float, float, float],
+ np.ndarray,
+ np.ndarray,
+ tuple[int, int],
+ ]
+ ]:
+ """Yield each trial with a stem, a map and both files as a task.
+
+ The trial is reported first.
+
+ Yields
+ ------
+ tuple
+ The job of :func:`_trial_image` for the trial.
+ """
for t, stem in enumerate(stems):
if progress is not None:
progress(t, n, stem)
@@ -340,9 +395,8 @@ def tasks():
return F0Stack(images, n_frames, untrimmed, inputs, attrs)
-def _network_attrs(bpath, attrs: dict) -> None:
- """Add a baseline file's network attributes (checkpoint, step,
- precision) to ``attrs``."""
+def _network_attrs(bpath: str | Path, attrs: dict) -> None:
+ """Add a baseline file's network attributes (checkpoint, step, precision) to attrs."""
with h5py.File(bpath, "r") as f:
for key in ("checkpoint", "step", "precision"):
if key in f.attrs:
@@ -350,21 +404,45 @@ def _network_attrs(bpath, attrs: dict) -> None:
attrs[key] = v.item() if hasattr(v, "item") else v
-def _trial_files(baseline_dir, moco_dir, stem: str) -> tuple[Path, Path]:
- """A trial's baseline and alignment files, as absolute paths (resolved
- against the current folder here, not in a worker that may have started
- in another)."""
+def _trial_files(baseline_dir: str | Path, moco_dir: str | Path, stem: str) -> tuple[Path, Path]:
+ """Return a trial's baseline and alignment files, as absolute paths.
+
+ They are resolved against the current folder here, not in a worker that may have
+ started in another.
+
+ Returns
+ -------
+ bpath : Path
+ The trial's baseline file.
+ apath : Path
+ The trial's alignment file.
+ """
bpath = Path(baseline_file(baseline_dir, stem)).absolute()
apath = (Path(moco_dir) / f"{stem}{ALIGNMENT_SUFFIX}").absolute()
return bpath, apath
-def _trial_image(job) -> tuple[int, np.ndarray, int, np.ndarray]:
- """One trial's F0 image in the consensus frame (a pool task): ``job`` is
- ``(trial, baseline file, alignment file, (align_hz, trim_s,
- motion_thresh, discard_initial_s), grid rows, grid cols, shape)``.
- Returns the trial, the image (float32), the frames averaged and the
- kept-frame flags."""
+def _trial_image(
+ job: tuple[
+ int, Path, Path, tuple[float, float, float, float], np.ndarray, np.ndarray, tuple[int, int]
+ ],
+) -> tuple[int, np.ndarray, int, np.ndarray]:
+ """Return one trial's F0 image in the consensus frame (a pool task).
+
+ job is (trial, baseline file, alignment file, (align_hz, trim_s,
+ motion_thresh, discard_initial_s), grid rows, grid cols, shape).
+
+ Returns
+ -------
+ trial : int
+ The trial.
+ image : np.ndarray
+ The image (float32).
+ used : int
+ The frames averaged.
+ keep : np.ndarray
+ The kept-frame flags.
+ """
t, bpath, apath, settings, rows, cols, shape = job
keep = kept_frames(read_rec_neg_err(apath), *settings)
mean, used = baseline_trial_mean(bpath, keep)
@@ -372,8 +450,14 @@ def _trial_image(job) -> tuple[int, np.ndarray, int, np.ndarray]:
return t, image.astype(np.float32), used, keep
-def stack_key(*parts) -> str:
- """A short hash of JSON-serializable parts and arrays (cache keys)."""
+def stack_key(*parts: object) -> str:
+ """Return a short hash of JSON-serializable parts and arrays (cache keys).
+
+ Returns
+ -------
+ str
+ The first 12 hexadecimal digits of the SHA-1 of the parts.
+ """
h = hashlib.sha1()
for p in parts:
if isinstance(p, np.ndarray):
diff --git a/src/giant_python/spine/parallel.py b/src/giant_python/spine/parallel.py
index 905670e6..1539d161 100644
--- a/src/giant_python/spine/parallel.py
+++ b/src/giant_python/spine/parallel.py
@@ -10,11 +10,11 @@
not depend on the number of workers.
The workers are spawned, so a script that starts a readout with more than
-one worker must do so under ``if __name__ == "__main__":`` (each worker
+one worker must do so under if __name__ == "__main__": (each worker
imports the script's module). With one worker everything runs in the
calling process and nothing is started. That is also what happens, whatever
the number of workers, in a daemonic process (such as a
-``multiprocessing.Pool`` worker), which cannot start processes of its own,
+multiprocessing.Pool worker), which cannot start processes of its own,
and, with a warning, when the workers cannot be started (for example from
a script read from standard input, which they cannot import).
"""
@@ -28,7 +28,9 @@
import sys
import warnings
from collections import deque
-from concurrent.futures import Future, ProcessPoolExecutor
+from collections.abc import Callable, Iterable, Iterator
+from concurrent.futures import Executor, Future, ProcessPoolExecutor
+from typing import Any
from ..parallel import THREAD_VARS, spawn_pool, stop_pool
@@ -39,20 +41,25 @@
"""The most workers a process pool takes on Windows."""
-def n_workers(workers) -> int:
- """The number of workers to use.
+def n_workers(workers: int | None) -> int:
+ """Return the number of workers to use.
Parameters
----------
workers : int or None
None: up to :data:`DEFAULT_WORKERS`, one per CPU. A number is
- taken as by ``int`` (at least 1); on Windows at most
+ taken as by int (at least 1); on Windows at most
:data:`WINDOWS_MAX_WORKERS`.
+ Returns
+ -------
+ int
+ The number of workers to use.
+
Raises
------
ValueError
- If ``workers`` is not None and not a number ``int`` takes.
+ If workers is not None and not a number int takes.
"""
if workers is None:
n = min(DEFAULT_WORKERS, os.cpu_count() or 1)
@@ -60,9 +67,7 @@ def n_workers(workers) -> int:
try:
n = int(workers)
except (TypeError, ValueError, OverflowError) as e:
- raise ValueError(
- f"workers must be a whole number or None, not {workers!r}"
- ) from e
+ raise ValueError(f"workers must be a whole number or None, not {workers!r}") from e
n = max(1, n)
if sys.platform == "win32":
n = min(n, WINDOWS_MAX_WORKERS)
@@ -70,15 +75,22 @@ def n_workers(workers) -> int:
def _check_started(reports: list, n: int) -> None:
- """Raise unless ``reports`` (the workers' start reports of
- :func:`~giant_python.parallel.spawn_pool`) come from ``n`` distinct
+ """Raise unless the workers started as asked.
+
+ reports (the workers' start reports of
+ :func:`~giant_python.parallel.spawn_pool`) must come from n distinct
workers, each with the thread variables at 1 and, where its BLAS
- thread counts could be read, one BLAS thread."""
+ thread counts could be read, one BLAS thread.
+
+ Raises
+ ------
+ RuntimeError
+ If the reports do not come from n distinct workers, or a worker
+ started without one BLAS/OpenMP thread.
+ """
pids = {r["pid"] for r in reports}
if len(pids) != n:
- raise RuntimeError(
- f"{len(pids)} of the {n} worker processes started together"
- )
+ raise RuntimeError(f"{len(pids)} of the {n} worker processes started together")
bad = [
r
for r in reports
@@ -86,27 +98,27 @@ def _check_started(reports: list, n: int) -> None:
or any(c != 1 for c in (r["blas"] or {}).values())
]
if bad:
- raise RuntimeError(
- "worker processes started without one BLAS/OpenMP thread "
- f"each: {bad}"
- )
+ raise RuntimeError(f"worker processes started without one BLAS/OpenMP thread each: {bad}")
def _worker_init() -> None:
- """A worker's initializer. It ignores the keyboard interrupt, which a
+ """Initialize a worker.
+
+ It ignores the keyboard interrupt, which a
terminal sends to the workers as well: the calling process handles it
and stops them, and a worker interrupted while it hands over a result
could leave the pool, and with it the command, waiting for the rest.
And it loads numpy, and with it its BLAS, so that the worker's start
- report can read the BLAS thread count."""
+ report can read the BLAS thread count.
+ """
import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)
import numpy # noqa: F401
-def make_pool(workers) -> ProcessPoolExecutor | None:
- """Worker processes for the readout, or None for one worker.
+def make_pool(workers: int | None) -> ProcessPoolExecutor | None:
+ """Return worker processes for the readout, or None for one worker.
The workers are spawned (not forked: a forked worker would inherit the
numerical libraries' thread pools) with the thread variables of those
@@ -124,12 +136,17 @@ def make_pool(workers) -> ProcessPoolExecutor | None:
workers : int or None
See :func:`n_workers`.
+ Returns
+ -------
+ concurrent.futures.ProcessPoolExecutor or None
+ The started worker pool, or None when there is one worker.
+
Raises
------
RuntimeError
If the workers do not all start in time, or one did not start
with the thread variables at 1 and one OpenBLAS thread.
- """
+ """ # noqa: DOC502
n = n_workers(workers)
if n <= 1:
return None
@@ -143,10 +160,17 @@ def make_pool(workers) -> ProcessPoolExecutor | None:
return pool
-def _pool_workers(pool) -> int:
- """The number of workers of an executor (or of a :class:`LazyPool`):
- its ``_max_workers``, as the standard library's executors have it; an
- executor without one counts as one worker."""
+def _pool_workers(pool: Executor | LazyPool) -> int:
+ """Return the number of workers of an executor (or of a :class:`LazyPool`).
+
+ This is its _max_workers, as the standard library's executors have it; an
+ executor without one counts as one worker.
+
+ Returns
+ -------
+ int
+ The number of workers (at least 1).
+ """
if isinstance(pool, LazyPool):
return pool.max_workers
return max(1, int(getattr(pool, "_max_workers", 1)))
@@ -155,17 +179,22 @@ def _pool_workers(pool) -> int:
_NO_TASK = object()
-def ordered_map(pool, func, tasks, ahead: int | None = None):
- """``func`` of each task, in the order of the tasks.
+def ordered_map(
+ pool: Executor | LazyPool | None,
+ func: Callable[[Any], Any],
+ tasks: Iterable,
+ ahead: int | None = None,
+) -> Iterator[Any]:
+ """Return func of each task, in the order of the tasks.
Without a pool, or with a pool of one worker, each task is made and run
here, one after the other, and nothing is made ahead. With a pool of
- more workers, at most ``ahead`` tasks are submitted and not yet taken
+ more workers, at most ahead tasks are submitted and not yet taken
(default: twice the pool's workers), so that the tasks' inputs are made
only shortly before they run. When the iteration stops early (a task
or the caller raises, the caller closes the iterator, or an interrupt)
the tasks not yet started are cancelled and no more are made; close the
- iterator (``contextlib.closing``) to stop at once when the caller
+ iterator (contextlib.closing) to stop at once when the caller
raises. Results are taken in the order of the tasks, so a task's error
is raised when its turn comes, after the results before it (as when
the tasks run one after the other); so is an error of the iterable
@@ -178,7 +207,7 @@ def ordered_map(pool, func, tasks, ahead: int | None = None):
----------
pool : concurrent.futures.Executor or LazyPool or None
A standard-library executor (its number of workers is read from
- its ``_max_workers``; an executor without that attribute is taken
+ its _max_workers; an executor without that attribute is taken
to have one worker, and the tasks then run here), a
:class:`LazyPool`, or None.
func : callable
@@ -187,22 +216,36 @@ def ordered_map(pool, func, tasks, ahead: int | None = None):
ahead : int, optional
A positive integer.
+ Returns
+ -------
+ Iterator
+ func of each task, in the order of the tasks.
+
Raises
------
ValueError
- If ``ahead`` is not a positive integer.
+ If ahead is not a positive integer.
"""
if ahead is not None and (
- isinstance(ahead, bool)
- or not isinstance(ahead, numbers.Integral)
- or ahead < 1
+ isinstance(ahead, bool) or not isinstance(ahead, numbers.Integral) or ahead < 1
):
raise ValueError(f"ahead must be a positive integer, not {ahead!r}")
return _ordered(pool, func, tasks, ahead)
-def _ordered(pool, func, tasks, ahead):
- """The generator of :func:`ordered_map`."""
+def _ordered(
+ pool: Executor | LazyPool | None,
+ func: Callable[[Any], Any],
+ tasks: Iterable,
+ ahead: int | None,
+) -> Iterator[Any]:
+ """Generate the results of :func:`ordered_map`.
+
+ Yields
+ ------
+ object
+ func of each task, in the order of the tasks.
+ """
tasks = iter(tasks)
first = next(tasks, _NO_TASK)
if first is _NO_TASK:
@@ -219,9 +262,22 @@ def _ordered(pool, func, tasks, ahead):
yield from _ordered_ahead(pool, func, tasks, ahead)
-def _ordered_ahead(pool, func, tasks, ahead: int):
- """:func:`ordered_map` with worker processes: the results in order,
- at most ``ahead`` tasks submitted and not yet taken."""
+def _ordered_ahead(
+ pool: Executor | LazyPool,
+ func: Callable[[Any], Any],
+ tasks: Iterator,
+ ahead: int,
+) -> Iterator[Any]:
+ """Run :func:`ordered_map` with worker processes.
+
+ The results are in order, with
+ at most ahead tasks submitted and not yet taken.
+
+ Yields
+ ------
+ object
+ func of each task, in the order of the tasks.
+ """
pending: deque = deque()
failed = None
try:
@@ -254,14 +310,15 @@ def _ordered_ahead(pool, func, tasks, ahead: int):
class LazyPool:
- """Worker processes started when the first task is submitted (a readout
- that reuses its cached images and runs no permutations starts none);
- with one worker, tasks run here. They also run here when this process
+ """Worker processes started when the first task is submitted.
+
+ A readout that reuses its cached images and runs no permutations starts
+ none; with one worker, tasks run here. They also run here when this process
is daemonic (it may not have children) and, after a warning, when the
workers cannot be started (:func:`make_pool` fails with an OSError or
a RuntimeError); in a spawned process that is still importing its main
- module (the worker of a script that starts a readout outside ``if
- __name__ == "__main__":``) that error is raised as it is, so that such
+ module (the worker of a script that starts a readout outside if
+ __name__ == "__main__":) that error is raised as it is, so that such
a worker ends instead of running the caller's script again.
Parameters
@@ -280,12 +337,35 @@ def __init__(self, workers: int | None = None) -> None:
@property
def max_workers(self) -> int:
- """The number of workers (:func:`n_workers`; 1 once the workers
- could not be started)."""
+ """The number of workers (:func:`n_workers`).
+
+ It is 1 once the workers
+ could not be started.
+
+ Returns
+ -------
+ int
+ The number of workers.
+ """
return 1 if self._here else n_workers(self._workers)
- def _start(self):
- """The workers' pool, or None when the tasks are to run here."""
+ def _start(self) -> ProcessPoolExecutor | None:
+ """Return the workers' pool, or None when the tasks are to run here.
+
+ Returns
+ -------
+ concurrent.futures.ProcessPoolExecutor or None
+ The started pool, or None when the tasks are to run here.
+
+ Raises
+ ------
+ OSError
+ If the workers cannot be started, in a spawned process that is
+ still importing its main module.
+ RuntimeError
+ If the workers cannot be started, in a spawned process that is
+ still importing its main module.
+ """
proc = multiprocessing.current_process()
if proc.daemon:
return None
@@ -304,17 +384,28 @@ def _start(self):
return None
def start(self) -> bool:
- """Start the workers now, if there are to be any and they are not
- started yet (as the first :meth:`submit` does); whether tasks go
- to workers."""
+ """Start the workers now, if there are to be any and they are not started yet.
+
+ This is what the first :meth:`submit` does.
+
+ Returns
+ -------
+ bool
+ Whether tasks go to workers.
+ """
if self.max_workers > 1 and self._pool is None:
self._pool = self._start()
self._here = self._pool is None
return self._pool is not None
- def submit(self, func, *args) -> Future:
- """Submit ``func(*args)``; returns a future (already done when the
- task ran here)."""
+ def submit(self, func: Callable[..., Any], *args: object) -> Future:
+ """Submit ``func(*args)``.
+
+ Returns
+ -------
+ concurrent.futures.Future
+ A future (already done when the task ran here).
+ """
if not self.start():
fut: Future = Future()
try:
@@ -325,15 +416,18 @@ def submit(self, func, *args) -> Future:
return self._pool.submit(func, *args)
def shutdown(self, cancel: bool = False) -> None:
- """Stop the workers (if any were started): after their tasks, or
- with ``cancel`` without waiting for them
+ """Stop the workers (if any were started).
+
+ They stop after their tasks, or
+ with cancel without waiting for them
(:func:`~giant_python.parallel.stop_pool`: the workers end once
the tasks they hold have, those they are at and the few the
executor has already queued for them; they are not killed, since
a worker killed while it hands over an image can leave the pool
waiting for the rest of it; the Python process itself ends only
once they have). Tasks still waiting are cancelled by whoever
- submitted them, as :func:`ordered_map` does when it is closed."""
+ submitted them, as :func:`ordered_map` does when it is closed.
+ """
pool, self._pool = self._pool, None
if pool is None:
return
diff --git a/src/giant_python/spine/pipeline.py b/src/giant_python/spine/pipeline.py
index 804560f3..001ca63b 100644
--- a/src/giant_python/spine/pipeline.py
+++ b/src/giant_python/spine/pipeline.py
@@ -1,31 +1,31 @@
-"""Make a ``spine_summary`` file from a SILo run (``giant spine readout``).
+"""Make a spine_summary file from a SILo run (giant spine readout).
Inputs:
-* a run folder with ``experiment_summary.h5`` and ``per_trial_summary.h5``
+* a run folder with experiment_summary.h5 and per_trial_summary.h5
(GIAnT-MATLAB or GIAnT-Python raster SILo);
-* the session's ``trial_table.h5`` (the registered movies' names, which
+* the session's trial_table.h5 (the registered movies' names, which
give the baseline files, and the raw files' acquisition trial numbers);
-* optionally the folder of the F0 network's ``_BASELINE-80Hz.h5``
+* optionally the folder of the F0 network's _BASELINE-80Hz.h5
files and the motion-correction folder they were predicted from.
-Images: the run's per-trial mean images (``mean_ch``), the run's own
-per-trial F0 images where it has them (``f0_silo_ch``: raster
-``giant silo`` runs and GIAnT-MATLAB's spine-size branch), and the
-network's per-trial F0 images (``f0_net``).
+Images: the run's per-trial mean images (mean_ch), the run's own
+per-trial F0 images where it has them (f0_silo_ch: raster
+giant silo runs and GIAnT-MATLAB's spine-size branch), and the
+network's per-trial F0 images (f0_net).
The network images take minutes (every trial's baseline is read); they are
cached per path under a key of their inputs' identities and settings, so a
rerun with other readout settings reuses them.
Every image is read out in the same windows: pixels with a value in every
trial used, in every image that covers the field of view (the mean images
-and ``f0_net``; :func:`~giant_python.spine.readout.common_valid`), so the
+and f0_net; :func:`~giant_python.spine.readout.common_valid`), so the
variants can be compared trial by trial. The images that have values only
-at the pixels SILo fitted (``f0_silo_ch``, ``f0_gain``) are read out in
+at the pixels SILo fitted (f0_silo_ch, f0_gain) are read out in
the same windows, with NaN where they do not cover one, so that they do not
take pixels or trials away from the other images; the report counts those
windows and trials. User ROIs are also read out as GIAnT-MATLAB's
-``user_rois/per_trial_F0`` (``readout/user_any``), whose windows can differ
+user_rois/per_trial_F0 (readout/user_any), whose windows can differ
between trials and images.
Each image's normalized source sizes then go through the trend tests of
@@ -38,10 +38,13 @@
import json
import re
+from collections.abc import Callable
+from concurrent.futures import Executor
from pathlib import Path, PurePosixPath
import h5py
import numpy as np
+import numpy.typing as npt
from .coverage import unimaged_pixels, window_weight_kept
from .gains import (
@@ -51,6 +54,7 @@
results_files,
)
from .images import F0Stack, file_identity, network_f0_stack, stack_key
+from .parallel import LazyPool
from .product import FORMAT_VERSION, _code_version, write_product
from .qc import (
primary_image,
@@ -59,8 +63,8 @@
window_motion,
)
from .readout import common_valid, mask_mean, norm_log, project
-from .rois import masks_roiset, sources_roiset
-from .summary_io import RunSummary
+from .rois import RoiSet, masks_roiset, sources_roiset
+from .summary_io import RunSummary, TrialMap
from .trends import (
check_trend_settings,
image_blocks,
@@ -74,8 +78,14 @@
_F0_CACHE_FORMAT = 1
-def _stem(name) -> str | None:
- """A registered movie's trial stem (``E1T1DMD1``), or None."""
+def _stem(name: object) -> str | None:
+ """Return a registered movie's trial stem (E1T1DMD1), or None.
+
+ Returns
+ -------
+ str or None
+ The trial stem, or None when name is not a registered movie.
+ """
name = str(name) if name is not None else ""
if _REGISTERED not in name:
return None
@@ -84,10 +94,12 @@ def _stem(name) -> str | None:
return _base_name(name).split(_REGISTERED)[0]
-def _replay_report(out: Path, report: dict, say) -> None:
- """Fill ``report`` from the report stored in a reused summary file
- (keeping what this call already found, such as the network images'
- cache keys) and pass its notes to ``say`` again."""
+def _replay_report(out: Path, report: dict, say: Callable[[str], None]) -> None:
+ """Fill report from the report stored in a reused summary file.
+
+ What this call already found (such as the network images' cache keys) is
+ kept, and the stored notes are passed to say again.
+ """
with h5py.File(out, "r") as f:
v = f.attrs.get("report")
if v is None:
@@ -101,13 +113,26 @@ def _replay_report(out: Path, report: dict, say) -> None:
say(msg)
-def _trials_and_window(n: int, images: dict, nfr, say):
- """The trials read out and the images that set the windows.
+def _trials_and_window(
+ n: int, images: dict, nfr: npt.ArrayLike, say: Callable[[str], None]
+) -> tuple[np.ndarray, list[str]]:
+ """Return the trials read out and the images that set the windows.
- The images that cover the field of view (``covers`` 'field') set them:
+ The images that cover the field of view (covers 'field') set them:
a trial is used if it has frames and each of them has values in it.
An image without any values is left out (with a note), so that it does
not empty every window. Without field images, all images set them.
+
+ Returns
+ -------
+ tuple of (np.ndarray, list of str)
+ The indices of the trials read out, and the names of the images that
+ set the windows.
+
+ Raises
+ ------
+ ValueError
+ If none of the per-trial images has values.
"""
frames = np.asarray(nfr) > 0
has = {
@@ -134,16 +159,23 @@ def _trials_and_window(n: int, images: dict, nfr, say):
ok &= has[k]
if frames.any() and not ok.any():
say(
- f"Path{n}: no trial has values in every one of {', '.join(window)}"
- "; nothing is read out"
+ f"Path{n}: no trial has values in every one of {', '.join(window)}; nothing is read out"
)
return np.flatnonzero(ok), window
-def _not_covered(r: dict, images: dict, window: list, used) -> dict:
- """Per image that does not set the windows: how many windows it leaves
+def _not_covered(r: dict, images: dict, window: list, used: np.ndarray) -> dict:
+ """Count, per image that does not set the windows, the windows it leaves uncovered.
+
+ That is how many windows it leaves
without a value in some trial used where the window images have one
- (only images that leave some)."""
+ (only images that leave some).
+
+ Returns
+ -------
+ dict
+ The number of such windows per image name (only images that leave some).
+ """
if used.size == 0:
return {}
ref = np.ones(r[window[0]][used].shape, bool)
@@ -159,15 +191,21 @@ def _not_covered(r: dict, images: dict, window: list, used) -> dict:
return out
-def _normalize(r: dict, images: dict, window: list, used) -> dict:
- """The normalized sizes (:func:`~giant_python.spine.readout.norm_log`)
- of every image's source readouts.
+def _normalize(r: dict, images: dict, window: list, used: np.ndarray) -> dict:
+ """Return the normalized sizes of every image's source readouts.
- The per-trial median is taken over one set of sources (``ok``): those
+ The sizes are normalized by :func:`~giant_python.spine.readout.norm_log`.
+ The per-trial median is taken over one set of sources (ok): those
whose readouts are positive in every trial used, in every image. An
image that does not cover a source (or a trial) leaves it out of its
own normalization only, so that images with values only at the pixels
SILo fitted do not change the reference set of the others.
+
+ Returns
+ -------
+ dict
+ The normalized sizes per image name, and the set of sources used for the
+ per-trial median under "ok".
"""
ok = np.ones(r[window[0]].shape[1], bool)
cover = {}
@@ -190,30 +228,31 @@ def _normalize(r: dict, images: dict, window: list, used) -> dict:
def _trends(
- n,
+ n: int,
norm: dict,
- acq,
+ acq: np.ndarray,
opts: dict,
- workers,
- say,
- note,
- activity_channel=1,
- pool=None,
+ workers: int | None,
+ say: Callable[[str], None],
+ note: Callable[[str], None],
+ activity_channel: int = 1,
+ pool: Executor | LazyPool | None = None,
) -> tuple:
- """The trend tests of every image's normalized source sizes
- (:func:`~giant_python.spine.trends.trend_tests`), over the trials in
- which the image has values. ``say`` gets progress lines, ``note`` the
+ """Run the trend tests of every image's normalized source sizes.
+
+ The tests are :func:`~giant_python.spine.trends.trend_tests`, over the
+ trials in which the image has values. say gets progress lines, note the
notes stored with the summary (trials without acquisition numbers).
Every other image also gets the structural channel's change beyond its
- trend at the image's own beyond-trend split (``structural_d``;
+ trend at the image's own beyond-trend split (structural_d;
:func:`~giant_python.spine.qc.structural_change`), when the run has a
- channel other than ``activity_channel``. ``pool`` (worker processes)
- runs the permutations instead of ``workers`` threads.
+ channel other than activity_channel. pool (worker processes)
+ runs the permutations instead of workers threads.
Returns
-------
trends : dict
- Per image, the arrays of the product's ``trends`` group (trial
+ Per image, the arrays of the product's trends group (trial
positions as zero-based trial-table indices, -1 where untested or
where a test found no split or run) and its attributes.
summary : dict
@@ -274,9 +313,7 @@ def _trends(
# trial positions as trial-table indices
for test in ("step", "resid"):
k = r[f"{test}_k"]
- arrays[f"{test}_after"] = np.where(
- k > 0, rows[np.maximum(k - 1, 0)], -1
- )
+ arrays[f"{test}_after"] = np.where(k > 0, rows[np.maximum(k - 1, 0)], -1)
bs = r["brief_start"]
arrays["brief_first"] = np.where(bs >= 0, rows[np.maximum(bs, 0)], -1)
v = np.full(n_trials, np.nan)
@@ -304,47 +341,54 @@ def _trends(
return trends, summary
-def _check_coverage_settings(frac, dilate, min_window, max_share) -> None:
- """Refuse settings of the not-imaged pixels and windows that cannot
- work (ValueError)."""
+def _check_coverage_settings(frac: float, dilate: int, min_window: float, max_share: float) -> None:
+ """Refuse settings of the not-imaged pixels and windows that cannot work.
+
+ Raises
+ ------
+ ValueError
+ If a setting is out of range.
+ """
if not 0 <= frac < 1:
raise ValueError(f"unimaged_frac must be in [0, 1), not {frac}")
if int(dilate) != dilate or dilate < 0:
- raise ValueError(
- f"unimaged_dilate must be a whole number >= 0, not {dilate}"
- )
+ raise ValueError(f"unimaged_dilate must be a whole number >= 0, not {dilate}")
if not 0 <= min_window <= 1:
raise ValueError(f"min_window must be in [0, 1], not {min_window}")
if not 0 < max_share <= 1:
- raise ValueError(
- f"unimaged_max_share must be in (0, 1], not {max_share}"
- )
+ raise ValueError(f"unimaged_max_share must be in (0, 1], not {max_share}")
+
+
+def _leave_out_unimaged(
+ n: int,
+ images: dict,
+ opts: tuple[float, int, float],
+ report: dict,
+ note: Callable[[str], None],
+) -> tuple[dict, np.ndarray | None]:
+ """Leave out of every image the pixels its trial did not image.
+ The pixels are found by :func:`~giant_python.spine.coverage.unimaged_pixels`, from the mean
+ images; opts = (frac, dilate, max_share).
-def _leave_out_unimaged(n, images: dict, opts: tuple, report, note):
- """Every image without the pixels its trial did not image
- (:func:`~giant_python.spine.coverage.unimaged_pixels`, from the mean
- images; ``opts`` = (frac, dilate, max_share)), and those pixels
- ``(trials, rows, cols)`` (None when not looked for)."""
+ Returns
+ -------
+ tuple of (dict, np.ndarray or None)
+ The images without those pixels, and those pixels
+ (trials, rows, cols) (None when not looked for).
+ """
frac, dilate, max_share = opts
if frac <= 0:
return images, None
- means = [
- s for s, a in images.values() if a.get("source") == "per_trial_mean_im"
- ]
+ means = [s for s, a in images.values() if a.get("source") == "per_trial_mean_im"]
if not means:
note(
- f"Path{n}: no per-trial mean images, so pixels a trial did not "
- "image are not looked for"
+ f"Path{n}: no per-trial mean images, so pixels a trial did not image are not looked for"
)
return images, None
- un, skipped = unimaged_pixels(
- means, frac, dilate, max_share=max_share, with_skipped=True
- )
+ un, skipped = unimaged_pixels(means, frac, dilate, max_share=max_share, with_skipped=True)
if skipped.size:
- report["paths"].setdefault(n, {})["unimaged_skipped"] = [
- int(t) + 1 for t in skipped
- ]
+ report["paths"].setdefault(n, {})["unimaged_skipped"] = [int(t) + 1 for t in skipped]
note(
f"Path{n}: in trial(s) "
f"{', '.join(str(int(t) + 1) for t in skipped)} the dark band "
@@ -355,25 +399,32 @@ def _leave_out_unimaged(n, images: dict, opts: tuple, report, note):
if not per.any():
return images, un
hit = np.flatnonzero(per)
- report["paths"].setdefault(n, {})["unimaged"] = {
- str(int(t) + 1): int(per[t]) for t in hit
- }
+ report["paths"].setdefault(n, {})["unimaged"] = {str(int(t) + 1): int(per[t]) for t in hit}
note(
f"Path{n}: {int(per.sum())} pixels in {hit.size} trial(s) "
f"({', '.join(str(int(t) + 1) for t in hit)}) were not imaged "
"(near-zero band at the scan's edge); left out of every image"
)
- out = {
- k: (np.where(un, np.nan, s).astype(np.float32), a)
- for k, (s, a) in images.items()
- }
+ out = {k: (np.where(un, np.nan, s).astype(np.float32), a) for k, (s, a) in images.items()}
return out, un
-def _drop_small_windows(n, r, rs, valid, images, min_window, report, note):
- """NaN sizes for the sources whose window keeps less than
- ``min_window`` of their footprint weight; records each source's share
- kept (``weight_kept``)."""
+def _drop_small_windows(
+ n: int,
+ r: dict,
+ rs: RoiSet,
+ valid: np.ndarray,
+ images: dict,
+ min_window: float,
+ report: dict,
+ note: Callable[[str], None],
+) -> None:
+ """Set NaN sizes for the sources whose window keeps little of their footprint.
+
+ These are the sources whose window keeps less than
+ min_window of their footprint weight; records each source's share
+ kept (weight_kept).
+ """
kept = window_weight_kept(rs, valid)
r["weight_kept"] = kept
small = np.flatnonzero(kept < min_window)
@@ -391,19 +442,40 @@ def _drop_small_windows(n, r, rs, valid, images, min_window, report, note):
def _sized_images(norm: dict) -> list:
- """The images with at least one finite normalized size (an image can
- keep its key with none, e.g. one that covers no window)."""
+ """Return the images with at least one finite normalized size.
+
+ An image can keep its key with none, e.g. one that covers no window.
+
+ Returns
+ -------
+ list
+ The names of the images with at least one finite normalized size.
+ """
return [
- k
- for k, v in norm.items()
- if k != "ok" and np.isfinite(np.asarray(v, np.float64)).any()
+ k for k, v in norm.items() if k != "ok" and np.isfinite(np.asarray(v, np.float64)).any()
]
-def _window_motion(run, n, affine_base, rs, valid, used, shape, note):
- """The sources' window motion beyond each trial's shift
- (:func:`~giant_python.spine.qc.window_motion`); NaN, with a note, when
- the run has no trial maps."""
+def _window_motion(
+ run: RunSummary,
+ n: int,
+ affine_base: int | None,
+ rs: RoiSet,
+ valid: np.ndarray,
+ used: np.ndarray,
+ shape: tuple[int, int],
+ note: Callable[[str], None],
+) -> np.ndarray:
+ """Return the sources' window motion beyond each trial's shift.
+
+ The motion is :func:`~giant_python.spine.qc.window_motion`; NaN, with a note, when
+ the run has no trial maps.
+
+ Returns
+ -------
+ np.ndarray
+ The window motion of each source (NaN where the run has no trial maps).
+ """
try:
# the index base only moves an affine map's translation, which the
# column removes
@@ -414,10 +486,21 @@ def _window_motion(run, n, affine_base, rs, valid, used, shape, note):
return window_motion(tmap, rs, valid, used, shape)
-def _report_calls(n, image, rec, rs, opts, report, note):
- """Report a path's calls in its default image: the sources (one-based
- ids) whose change beyond the shared trend passes ``q <= fdr_q`` and is
- at least ``min_change``."""
+def _report_calls(
+ n: int,
+ image: str,
+ rec: dict,
+ rs: RoiSet,
+ opts: dict,
+ report: dict,
+ note: Callable[[str], None],
+) -> None:
+ """Report a path's calls in its default image.
+
+ The calls are the sources (one-based
+ ids) whose change beyond the shared trend passes q <= fdr_q and is
+ at least min_change.
+ """
arr = rec["arrays"]
call = np.asarray(arr["call"], bool)
d = np.asarray(arr["resid_d"], np.float64)
@@ -438,13 +521,19 @@ def _report_calls(n, image, rec, rs, opts, report, note):
)
-def table_trials(table_path, path: int) -> tuple[list, np.ndarray]:
+def table_trials(table_path: str | Path, path: int) -> tuple[list, np.ndarray]:
"""Each trial's stem and acquisition trial number for one path.
Returns
-------
stems : list of (str or None)
acquisition : ndarray of int (-1 where the raw name has no number)
+
+ Raises
+ ------
+ ValueError
+ If the trial table has no registered path, or lists a different number of raw
+ files and registered movies for it.
"""
from ..io.trial_table import read_trial_table
@@ -469,29 +558,39 @@ def table_trials(table_path, path: int) -> tuple[list, np.ndarray]:
return stems, np.asarray(acq, np.int64)
-def _base_name(name) -> str:
- """The last part of a path written on any system."""
+def _base_name(name: object) -> str:
+ """Return the last part of a path written on any system.
+
+ Returns
+ -------
+ str
+ The file or folder name at the end of name.
+ """
name = str(name) if name is not None else ""
return PurePosixPath(name.replace("\\", "/")).name
-def _write_atomic(dest, write) -> None:
- """Write ``dest`` through a temporary file of its own in the same folder
- (``write(tmp)``), then move it into place.
+def _write_atomic(dest: str | Path, write: Callable[[Path], None]) -> None:
+ """Write dest through a temporary file of its own in the same folder.
+
+ The file is written by write(tmp), then moved into place.
Concurrent writers of the same file each have their own temporary file.
If the move is refused because another writer's file is in place and
open (Windows), that file is kept: the same name means the same key and
so the same content.
+
+ Raises
+ ------
+ PermissionError
+ If the move is refused and dest is not in place.
"""
import os
import tempfile
dest = Path(dest)
dest.parent.mkdir(parents=True, exist_ok=True)
- fd, name = tempfile.mkstemp(
- prefix=f"{dest.name}.", suffix=".tmp", dir=dest.parent
- )
+ fd, name = tempfile.mkstemp(prefix=f"{dest.name}.", suffix=".tmp", dir=dest.parent)
os.close(fd)
tmp = Path(name)
try:
@@ -507,9 +606,24 @@ def _write_atomic(dest, write) -> None:
raise
-def _f0_cache_key(stems, baseline_dir, moco_dir, tmap, shape, settings):
- """Cache key of a path's network F0 stack: its inputs' identities, the
- map, the frame and the settings."""
+def _f0_cache_key(
+ stems: list[str | None],
+ baseline_dir: str | Path,
+ moco_dir: str | Path,
+ tmap: TrialMap,
+ shape: tuple[int, int],
+ settings: dict,
+) -> str:
+ """Return the cache key of a path's network F0 stack.
+
+ The key is made of its inputs' identities, the
+ map, the frame and the settings.
+
+ Returns
+ -------
+ str
+ The cache key.
+ """
ids = []
for stem in stems:
if stem is None:
@@ -517,12 +631,10 @@ def _f0_cache_key(stems, baseline_dir, moco_dir, tmap, shape, settings):
continue
b = Path(baseline_dir) / f"{stem}_BASELINE-80Hz.h5"
a = Path(moco_dir) / f"{stem}_ALIGNMENTDATA.h5"
- ids.append(
- [
- file_identity(b) if b.is_file() else None,
- file_identity(a) if a.is_file() else None,
- ]
- )
+ ids.append([
+ file_identity(b) if b.is_file() else None,
+ file_identity(a) if a.is_file() else None,
+ ])
disp = tmap.displacement
return stack_key(
"f0net-v1",
@@ -535,19 +647,20 @@ def _f0_cache_key(stems, baseline_dir, moco_dir, tmap, shape, settings):
def cached_f0_stack(
- cache_dir,
+ cache_dir: str | Path,
path: int,
- stems,
- baseline_dir,
- moco_dir,
- tmap,
- shape,
+ stems: list[str | None],
+ baseline_dir: str | Path,
+ moco_dir: str | Path,
+ tmap: TrialMap,
+ shape: tuple[int, int],
settings: dict,
- progress=None,
- pool=None,
+ progress: Callable[[int, int, str | None], None] | None = None,
+ pool: Executor | LazyPool | None = None,
) -> tuple[F0Stack, str, bool]:
- """A path's network F0 stack, from the cache when its key matches
- (otherwise made with ``pool``'s workers when given).
+ """Return a path's network F0 stack, from the cache when its key matches.
+
+ Otherwise it is made with pool's workers when given.
Returns
-------
@@ -589,8 +702,8 @@ def cached_f0_stack(
pool=pool,
)
- def write(tmp):
- """Write the stack to ``tmp``."""
+ def write(tmp: Path) -> None:
+ """Write the stack to tmp."""
with h5py.File(tmp, "w") as f:
f.create_dataset(
"images",
@@ -609,22 +722,22 @@ def write(tmp):
return st, key, False
-def make_spine_summary( # noqa: C901
- run_dir,
- table_path,
- out_dir,
- baseline_dir=None,
- moco_dir=None,
- paths=None,
+def make_spine_summary(
+ run_dir: str | Path,
+ table_path: str | Path,
+ out_dir: str | Path,
+ baseline_dir: str | Path | None = None,
+ moco_dir: str | Path | None = None,
+ paths: list[int] | None = None,
trim_s: float = 1.0,
align_hz: float | None = None,
motion_thresh: float | None = None,
discard_initial_s: float | None = None,
- cache_dir=None,
+ cache_dir: str | Path | None = None,
overwrite: bool = False,
images_only: bool = False,
- affine_base=None,
- gain_work_dir=None,
+ affine_base: int | None = None,
+ gain_work_dir: str | Path | None = None,
unimaged_frac: float = 0.5,
unimaged_dilate: int = 1,
unimaged_max_share: float = 0.25,
@@ -634,22 +747,22 @@ def make_spine_summary( # noqa: C901
max_brief: int = 3,
seed: int = 1,
workers: int | None = None,
- progress=None,
+ progress: Callable[[str], None] | None = None,
min_change: float = 0.1,
) -> dict:
- """Read out spine sizes from a run and write a ``spine_summary`` file.
+ """Read out spine sizes from a run and write a spine_summary file.
Parameters
----------
run_dir : str or Path
Folder with the run's summaries.
table_path : str or Path
- The session's ``trial_table.h5``.
+ The session's trial_table.h5.
out_dir : str or Path
- Where the ``spine_summary_.h5`` file goes.
+ Where the spine_summary_.h5 file goes.
baseline_dir, moco_dir : str or Path, optional
The network's baselines and the motion-correction folder; without
- them there is no ``f0_net`` image.
+ them there is no f0_net image.
paths : list of int, optional
Imaging paths (default: all in the run).
trim_s : float
@@ -657,20 +770,20 @@ def make_spine_summary( # noqa: C901
F0 images (:func:`~giant_python.spine.images.kept_frames`).
align_hz, motion_thresh, discard_initial_s : float, optional
The registered frame rate and SILo's motion discards for those
- images; by default the run's own (``params/alignHz``,
- ``params/motionThresh``, ``params/discardInitial_s``; 80, 2 and 0
+ images; by default the run's own (params/alignHz,
+ params/motionThresh, params/discardInitial_s; 80, 2 and 0
where the run does not record them), so that the images leave out
the frames that SILo left out.
cache_dir : str or Path, optional
- Cache of the network's F0 stacks (default ``/cache``).
+ Cache of the network's F0 stacks (default /cache).
overwrite : bool
Rewrite an existing output with the same key.
images_only : bool
Only build the network's F0 stacks (the slow part).
gain_work_dir : str or Path, optional
Work folder of the run (a 'gain' baseline mode, N1): its results
- files' per-pixel gains give the ``f0_gain`` image, the network's F0
- image rescaled as the solver rescaled it (needs ``baseline_dir``,
+ files' per-pixel gains give the f0_gain image, the network's F0
+ image rescaled as the solver rescaled it (needs baseline_dir,
with the baseline files the run's gains were fitted against).
affine_base : {0, 1, None}
Index base of the run's affine trial maps (see
@@ -679,14 +792,14 @@ def make_spine_summary( # noqa: C901
Pixels a trial did not image although its images have values there
(a band of near-zero values at the edge of the scan, left when
online motion correction steps): with each trial divided by its
- brightness scale, below ``unimaged_frac`` of their usual level
+ brightness scale, below unimaged_frac of their usual level
(their 75th percentile over trials) in every mean channel,
connected to the trial's missing pixels (in any channel) or to the
- frame's border, and ``unimaged_dilate`` pixels around them
+ frame's border, and unimaged_dilate pixels around them
(:func:`~giant_python.spine.coverage.unimaged_pixels`). They are
left out of every image of that trial, and so out of the windows.
- ``unimaged_frac`` 0 turns this off. A trial whose band would cover
- more than ``unimaged_max_share`` of its imaged pixels gets nothing
+ unimaged_frac 0 turns this off. A trial whose band would cover
+ more than unimaged_max_share of its imaged pixels gets nothing
left out (reported): a band is a narrow strip, and something that
large cannot be told from a change of the scene.
min_window : float
@@ -702,11 +815,11 @@ def make_spine_summary( # noqa: C901
permutations (at most 61 on Windows; the results do not depend on
it, :mod:`~giant_python.spine.parallel`). None (the default) and 1
run everything in the calling process and start none; the
- ``giant spine`` commands ask for up to 8, one per CPU. They are
+ giant spine commands ask for up to 8, one per CPU. They are
spawned when there is work for them, so a script that calls this
- with more than one worker must do so under ``if __name__ ==
- "__main__":``. In a daemonic process (such as a
- ``multiprocessing.Pool`` worker, which cannot start processes), and
+ with more than one worker must do so under if __name__ ==
+ "__main__":. In a daemonic process (such as a
+ multiprocessing.Pool worker, which cannot start processes), and
with a warning where the workers cannot be started, everything
runs in the calling process too. The value is checked only when
the workers have work.
@@ -714,7 +827,7 @@ def make_spine_summary( # noqa: C901
Called with a message string.
min_change : float
Smallest relative change beyond the shared trend that makes a call
- (with ``q <= fdr_q``; :func:`~giant_python.spine.trends.trend_tests`).
+ (with q <= fdr_q; :func:`~giant_python.spine.trends.trend_tests`).
The report lists each path's calls in its default image
(:func:`~giant_python.spine.qc.primary_image`).
@@ -725,10 +838,8 @@ def make_spine_summary( # noqa: C901
and window counts and the windows that images leave without a
value. The file stores this report and its notes; when an existing
file is reused, they are read back and the notes passed to
- ``progress`` again.
+ progress again.
"""
- from .parallel import LazyPool
-
pool = LazyPool(1 if workers is None else workers)
try:
report = _spine_summary(
@@ -768,42 +879,54 @@ def make_spine_summary( # noqa: C901
return report
-def _spine_summary( # noqa: C901
- run_dir,
- table_path,
- out_dir,
- baseline_dir,
- moco_dir,
- paths,
- trim_s,
- align_hz,
- motion_thresh,
- discard_initial_s,
- cache_dir,
- overwrite,
- images_only,
- affine_base,
- gain_work_dir,
- unimaged_frac,
- unimaged_dilate,
- unimaged_max_share,
- min_window,
- n_perm,
- fdr_q,
- max_brief,
- seed,
- workers,
- progress,
- min_change,
- pool,
+def _spine_summary(
+ run_dir: str | Path,
+ table_path: str | Path,
+ out_dir: str | Path,
+ baseline_dir: str | Path | None,
+ moco_dir: str | Path | None,
+ paths: list[int] | None,
+ trim_s: float,
+ align_hz: float | None,
+ motion_thresh: float | None,
+ discard_initial_s: float | None,
+ cache_dir: str | Path | None,
+ overwrite: bool,
+ images_only: bool,
+ affine_base: int | None,
+ gain_work_dir: str | Path | None,
+ unimaged_frac: float,
+ unimaged_dilate: int,
+ unimaged_max_share: float,
+ min_window: float,
+ n_perm: int,
+ fdr_q: float,
+ max_brief: int,
+ seed: int,
+ workers: int | None,
+ progress: Callable[[str], None] | None,
+ min_change: float,
+ pool: LazyPool,
) -> dict:
- """:func:`make_spine_summary` with its worker processes ``pool``."""
+ """Run :func:`make_spine_summary` with its worker processes pool.
+
+ Returns
+ -------
+ dict
+ The report (see :func:`make_spine_summary`).
+
+ Raises
+ ------
+ ValueError
+ If only one of baseline_dir and moco_dir is given, gain_work_dir is
+ given without baseline_dir, a path is not in the run, the table and the run
+ disagree in the number of trials, a path has no per-trial images, or the gain
+ run's frame is not the run's.
+ """
if (baseline_dir is None) != (moco_dir is None):
raise ValueError("give both --baseline-dir and --moco-dir, or neither")
check_trend_settings(n_perm, fdr_q, max_brief, seed, min_change)
- _check_coverage_settings(
- unimaged_frac, unimaged_dilate, min_window, unimaged_max_share
- )
+ _check_coverage_settings(unimaged_frac, unimaged_dilate, min_window, unimaged_max_share)
if gain_work_dir is not None and baseline_dir is None:
raise ValueError("--gain-work-dir needs --baseline-dir")
run = RunSummary(run_dir)
@@ -848,9 +971,7 @@ def _spine_summary( # noqa: C901
"run": {
"experiment_summary": file_identity(run.experiment_path),
"per_trial_summary": (
- file_identity(run.per_trial_path)
- if run.per_trial_path.is_file()
- else None
+ file_identity(run.per_trial_path) if run.per_trial_path.is_file() else None
),
},
"trial_table": file_identity(table_path),
@@ -866,15 +987,16 @@ def _spine_summary( # noqa: C901
stems, acq = table_trials(table_path, n)
if len(stems) != run.n_trials(n):
raise ValueError(
- f"Path{n}: {len(stems)} trials in the table, "
- f"{run.n_trials(n)} in the run"
+ f"Path{n}: {len(stems)} trials in the table, {run.n_trials(n)} in the run"
)
if baseline_dir is not None:
shape = run.shape(n)
- def prog(t, total, stem, n=n):
- """Report a trial's start (when it is handed to the
- workers, with more than one)."""
+ def prog(t: int, total: int, stem: str | None, n: int = n) -> None:
+ """Report a trial's start.
+
+ That is when it is handed to the workers, with more than one.
+ """
say(f"Path{n}: network F0 image {t + 1}/{total} ({stem})")
st, key, reused = cached_f0_stack(
@@ -902,10 +1024,7 @@ def prog(t, total, stem, n=n):
inputs["gain_results"][n] = {
"plan": file_identity(plan_file(gain_work_dir, n)),
"results": [
- [
- file_identity(f)
- for f in results_files(gain_work_dir, n, t)
- ]
+ [file_identity(f) for f in results_files(gain_work_dir, n, t)]
for t in range(len(stems))
],
}
@@ -925,8 +1044,8 @@ def prog(t, total, stem, n=n):
content: dict = {}
notes: list = []
- def note(msg):
- """A note about the readout: shown, and stored with it."""
+ def note(msg: str) -> None:
+ """Show a note about the readout, and store it with the readout."""
notes.append(msg)
say(msg)
@@ -979,12 +1098,8 @@ def note(msg):
many = np.isfinite(rel) & (spread > 0)
report["paths"].setdefault(n, {})["gain"] = {
"median": float(np.nanmedian(gain)),
- "shared_pixel_share": float(
- many.mean() / max(np.isfinite(gain).mean(), 1e-12)
- ),
- "median_rel_spread_shared": (
- float(np.median(rel[many])) if many.any() else 0.0
- ),
+ "shared_pixel_share": float(many.mean() / max(np.isfinite(gain).mean(), 1e-12)),
+ "median_rel_spread_shared": (float(np.median(rel[many])) if many.any() else 0.0),
}
if n in stacks:
st = stacks[n]
@@ -1001,9 +1116,7 @@ def note(msg):
)
short = np.flatnonzero(st.untrimmed)
if short.size:
- report["paths"].setdefault(n, {})["f0_untrimmed"] = [
- int(t) + 1 for t in short
- ]
+ report["paths"].setdefault(n, {})["f0_untrimmed"] = [int(t) + 1 for t in short]
note(
f"Path{n}: f0_net of trial(s) "
f"{', '.join(str(t + 1) for t in short)} averages the "
@@ -1035,10 +1148,7 @@ def note(msg):
# the same windows as the sources: valid pixels only
vflat = valid.ravel()
r["n_pixels"] = np.array(
- [
- np.count_nonzero(vflat[rs.pixels(k)[0]])
- for k in range(len(rs))
- ],
+ [np.count_nonzero(vflat[rs.pixels(k)[0]]) for k in range(len(rs))],
np.int64,
)
for name, (stack, _) in images.items():
@@ -1053,12 +1163,8 @@ def note(msg):
else:
for name, (stack, _) in images.items():
r[name], r["n_pixels"] = project(stack, rs, valid)
- _drop_small_windows(
- n, r, rs, valid, images, min_window, report, note
- )
- r["align_px"] = _window_motion(
- run, n, affine_base, rs, valid, used, shape, note
- )
+ _drop_small_windows(n, r, rs, valid, images, min_window, report, note)
+ r["align_px"] = _window_motion(run, n, affine_base, rs, valid, used, shape, note)
readout[set_name] = r
gaps = _not_covered(r, images, window, used)
if gaps:
@@ -1086,9 +1192,7 @@ def note(msg):
report["paths"].setdefault(n, {})["trends"] = summ
# the default image is one with sizes (an image with fewer than
# three trials has no trend tests, and so no calls)
- prim = primary_image(
- _sized_images(normalized[set_name]), run.activity_channel()
- )
+ prim = primary_image(_sized_images(normalized[set_name]), run.activity_channel())
if prim is not None and prim in trends[set_name]:
_report_calls(
n,
@@ -1129,22 +1233,18 @@ def note(msg):
"trends": trends,
"activity": activity,
}
- report["paths"].setdefault(n, {}).update(
- {
- "images": list(images),
- "window_images": list(window),
- "trials_used": int(used.size),
- "valid_pixels": int(valid.sum()),
- "rois": {k: len(v) for k, v in rois.items()},
- }
- )
+ report["paths"].setdefault(n, {}).update({
+ "images": list(images),
+ "window_images": list(window),
+ "trials_used": int(used.size),
+ "valid_pixels": int(valid.sum()),
+ "rois": {k: len(v) for k, v in rois.items()},
+ })
say(f"writing {out}")
stored = {"paths": report["paths"], "notes": notes}
_write_atomic(
out,
- lambda tmp: write_product(
- tmp, content, settings, inputs, run_dir, report=stored
- ),
+ lambda tmp: write_product(tmp, content, settings, inputs, run_dir, report=stored),
)
report["reused"] = False
return report
diff --git a/src/giant_python/spine/product.py b/src/giant_python/spine/product.py
index aafe088b..22fc8727 100644
--- a/src/giant_python/spine/product.py
+++ b/src/giant_python/spine/product.py
@@ -1,7 +1,8 @@
-"""The ``spine_summary`` file: everything the spine-size viewer and later
-analyses need from one run, in one compact HDF5 file.
+"""The spine_summary file: everything the spine-size viewer and later analyses need.
-Layout (row-major, numpy orientation; images ``(trials, rows, cols)`` in the
+Everything comes from one run, in one compact HDF5 file.
+
+Layout (row-major, numpy orientation; images (trials, rows, cols) in the
run's consensus frame, zero-based coordinates)::
/ attrs: format, format_version, code_version,
@@ -24,10 +25,10 @@
'fitted': values only at the pixels SILo
fitted); n_frames (T,) where known; for f0_net
untrimmed (T,): trials averaged whole, too short
- for the trim. ``mean_ch``
- and ``f0_silo_ch`` are of file channel
+ for the trim. mean_ch
+ and f0_silo_ch are of file channel
(one-based; the activity channel is the group's
- activity_channel); ``f0_net`` and ``f0_gain`` are
+ activity_channel); f0_net and f0_gain are
of the channel the baselines were predicted from
unimaged (T, H, W) uint8 pixels a trial did not image although
its images had values there (left out of
@@ -48,11 +49,11 @@
user_rois/per_trial_F0 (every pixel with a
value in the trial)
readout/user_any/coverage_ (T, R) share of the ROI's pixels
- normalized//